activemq-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From chir...@apache.org
Subject svn commit: r419422 [10/11] - in /incubator/activemq/trunk/openwire-cpp/src/main/cpp: activemq/ activemq/command/ activemq/protocol/openwire/ activemq/transport/ activemq/transport/tcp/ cms/ ppr/ ppr/io/ ppr/io/encoding/ ppr/net/ ppr/thread/ ppr/util/
Date Thu, 06 Jul 2006 03:18:03 GMT
Modified: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/io/encoding/AsciiToUTF8Encoder.cpp
URL: http://svn.apache.org/viewvc/incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/io/encoding/AsciiToUTF8Encoder.cpp?rev=419422&r1=419421&r2=419422&view=diff
==============================================================================
--- incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/io/encoding/AsciiToUTF8Encoder.cpp (original)
+++ incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/io/encoding/AsciiToUTF8Encoder.cpp Wed Jul  5 20:17:58 2006
@@ -1,187 +1,187 @@
-/*
- * Copyright 2006 The Apache Software Foundation or its licensors, as
- * applicable.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "ppr/io/encoding/AsciiToUTF8Encoder.hpp"
-
-using namespace apache::ppr::io::encoding;
-
-
-// Init static members
-const char* AsciiToUTF8Encoder::NAME = "AsciiToUTF8" ;
-
-/*
- *
- */
-AsciiToUTF8Encoder::AsciiToUTF8Encoder()
-{
-    // no-op
-}
-
-/*
- *
- */
-AsciiToUTF8Encoder::~AsciiToUTF8Encoder()
-{
-    // no-op
-}
-
-/*
- * Counts length of encoded version of given string.
- */
-int AsciiToUTF8Encoder::length(p<string> str)
-{
-    // Assert parameter
-    if( str == NULL )
-    {
-        // Nothing to encode
-        return 0 ;
-    }
-
-    int  ch,
-         utflen = 0,
-         strlen = (int)str->length() ;
-
-    for( int i = 0 ; i < strlen ; i++ )
-    {
-        ch = ((*str)[i] & 0xFF) ;
-
-        // Single byte in range 0x0001 - 0x007F
-        if( (ch >= 0x0001) && (ch <= 0x007F) )
-            utflen++ ;
-
-        // Triple bytes above 0x07FF (should never occur, ASCII 0x00 - 0xFF)
-        else if( ch > 0x07FF )
-            utflen += 3 ;
-
-        // Double bytes for 0x0000 and in range 0x0080 - 0x07FF
-        else
-            utflen += 2 ;
-    }
-    return utflen ;
-}
-
-/*
- * Encodes given string from ASCII into modified UTF-8.
- */
-p<string> AsciiToUTF8Encoder::encode(p<string> str, int *enclen) throw (CharsetEncodingException) 
-{
-    // Assert parameter
-    if( str == NULL )
-    {
-        // Nothing to encode
-        *enclen = 0 ;
-        return NULL ;
-    }
-
-    p<string> encstr = new string("") ;
-    int  ch, strlen = (int)str->length() ;
-
-    // Init encoded length
-    *enclen = 0 ;
-
-    // Loop through string and encode each char
-    for( int i = 0 ; i < strlen ; i++ )
-    {
-        ch = ((*str)[i] & 0xFF) ;
-
-        // Single byte in range 0x0001 - 0x007F
-        if( (ch >= 0x0001) && (ch <= 0x007F) )
-        {
-            encstr->append(1, (char)ch) ;
-            (*enclen)++ ;
-        }
-        // Triple bytes above 0x07FF (should never occur, ASCII 0x00 - 0xFF)
-        else if( ch > 0x07FF )
-        {
-            encstr->append(1, (char)( ((ch >> 12) & 0x0F) | 0xE0 )) ;
-            encstr->append(1, (char)( ((ch >> 6) & 0x3F) | 0x80 )) ;
-            encstr->append(1, (char)( ((ch >> 0) & 0x3F) | 0x80 )) ;
-            *enclen += 3 ;
-        }
-        // Double bytes for 0x0000 and in range 0x0080 - 0x07FF
-        else
-        {
-            encstr->append(1, (char)( ((ch >> 6) & 0x1F) | 0xC0 )) ;
-            encstr->append(1, (char)( ((ch >> 0) & 0x3F) | 0x80 )) ;
-            *enclen += 2 ;
-        }
-    }
-    return encstr ;
-}
-
-/*
- * Decodes given string from modified UTF-8 into ASCII.
- */
-p<string> AsciiToUTF8Encoder::decode(p<string> str) throw (CharsetEncodingException)
-{
-    // Assert argument
-    if( str == NULL || str->length() == 0 )
-        return NULL ;
-
-    p<string>     decstr = new string("") ;
-    int           length = (int)str->length() ;
-    unsigned char ch, ch2, ch3;
-    int           i = 0 ;
-
-    // Loop through and decode each char
-    while( i < length )
-    {
-        ch = ((*str)[i] & 0xFF) ;
-
-        switch( ch >> 4 )
-        {
-            case 0:
-            case 1:
-            case 2:
-            case 3:
-            case 4:
-            case 5:
-            case 6:
-            case 7:   // Single byte char, 0xxxxxxx
-                i++ ;
-                decstr->append( 1, (char)ch ) ;
-                break ;
-            case 12:
-            case 13:  // Double bytes char, 110xxxxx 10xxxxxx
-                i += 2 ;
-
-                if( i > length )
-                    throw CharsetEncodingException("Missing character in double pair") ;
-
-                ch2 = (*str)[i - 1] ;
-                if( (ch2 & 0xC0) != 0x80 )
-                    throw CharsetEncodingException("Invalid second character in double byte pair") ;
-
-                decstr->append( 1, (char)(((ch & 0x1F) << 6) | (ch2 & 0x3F)) ) ;
-                break ;
-            case 14:  // Triple bytes char, 1110xxxx 10xxxxxx 10xxxxxx
-                i += 3 ;
-                if( i > length )
-                    throw CharsetEncodingException("Missing character in triple set") ;
-
-                ch2 = (*str)[i - 2] ;
-                ch3 = (*str)[i - 1] ;
-                if( ((ch2 & 0xC0) != 0x80) || ((ch3 & 0xC0) != 0x80) )
-                    throw CharsetEncodingException("Invalid second and/or third character in triple set") ;
-
-                decstr->append( 1, (char)(((ch & 0x0F) << 12) | ((ch2 & 0x3F) << 6) | ((ch3 & 0x3F) << 0)) ) ;
-                break ;
-            default:  // Unsupported, 10xxxxxx 1111xxxx
-                throw CharsetEncodingException("Unsupported type flag") ;
-        }
-    }
-    return decstr ;
-}
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as
+ * applicable.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "ppr/io/encoding/AsciiToUTF8Encoder.hpp"
+
+using namespace apache::ppr::io::encoding;
+
+
+// Init static members
+const char* AsciiToUTF8Encoder::NAME = "AsciiToUTF8" ;
+
+/*
+ *
+ */
+AsciiToUTF8Encoder::AsciiToUTF8Encoder()
+{
+    // no-op
+}
+
+/*
+ *
+ */
+AsciiToUTF8Encoder::~AsciiToUTF8Encoder()
+{
+    // no-op
+}
+
+/*
+ * Counts length of encoded version of given string.
+ */
+int AsciiToUTF8Encoder::length(p<string> str)
+{
+    // Assert parameter
+    if( str == NULL )
+    {
+        // Nothing to encode
+        return 0 ;
+    }
+
+    int  ch,
+         utflen = 0,
+         strlen = (int)str->length() ;
+
+    for( int i = 0 ; i < strlen ; i++ )
+    {
+        ch = ((*str)[i] & 0xFF) ;
+
+        // Single byte in range 0x0001 - 0x007F
+        if( (ch >= 0x0001) && (ch <= 0x007F) )
+            utflen++ ;
+
+        // Triple bytes above 0x07FF (should never occur, ASCII 0x00 - 0xFF)
+        else if( ch > 0x07FF )
+            utflen += 3 ;
+
+        // Double bytes for 0x0000 and in range 0x0080 - 0x07FF
+        else
+            utflen += 2 ;
+    }
+    return utflen ;
+}
+
+/*
+ * Encodes given string from ASCII into modified UTF-8.
+ */
+p<string> AsciiToUTF8Encoder::encode(p<string> str, int *enclen) throw (CharsetEncodingException) 
+{
+    // Assert parameter
+    if( str == NULL )
+    {
+        // Nothing to encode
+        *enclen = 0 ;
+        return NULL ;
+    }
+
+    p<string> encstr = new string("") ;
+    int  ch, strlen = (int)str->length() ;
+
+    // Init encoded length
+    *enclen = 0 ;
+
+    // Loop through string and encode each char
+    for( int i = 0 ; i < strlen ; i++ )
+    {
+        ch = ((*str)[i] & 0xFF) ;
+
+        // Single byte in range 0x0001 - 0x007F
+        if( (ch >= 0x0001) && (ch <= 0x007F) )
+        {
+            encstr->append(1, (char)ch) ;
+            (*enclen)++ ;
+        }
+        // Triple bytes above 0x07FF (should never occur, ASCII 0x00 - 0xFF)
+        else if( ch > 0x07FF )
+        {
+            encstr->append(1, (char)( ((ch >> 12) & 0x0F) | 0xE0 )) ;
+            encstr->append(1, (char)( ((ch >> 6) & 0x3F) | 0x80 )) ;
+            encstr->append(1, (char)( ((ch >> 0) & 0x3F) | 0x80 )) ;
+            *enclen += 3 ;
+        }
+        // Double bytes for 0x0000 and in range 0x0080 - 0x07FF
+        else
+        {
+            encstr->append(1, (char)( ((ch >> 6) & 0x1F) | 0xC0 )) ;
+            encstr->append(1, (char)( ((ch >> 0) & 0x3F) | 0x80 )) ;
+            *enclen += 2 ;
+        }
+    }
+    return encstr ;
+}
+
+/*
+ * Decodes given string from modified UTF-8 into ASCII.
+ */
+p<string> AsciiToUTF8Encoder::decode(p<string> str) throw (CharsetEncodingException)
+{
+    // Assert argument
+    if( str == NULL || str->length() == 0 )
+        return NULL ;
+
+    p<string>     decstr = new string("") ;
+    int           length = (int)str->length() ;
+    unsigned char ch, ch2, ch3;
+    int           i = 0 ;
+
+    // Loop through and decode each char
+    while( i < length )
+    {
+        ch = ((*str)[i] & 0xFF) ;
+
+        switch( ch >> 4 )
+        {
+            case 0:
+            case 1:
+            case 2:
+            case 3:
+            case 4:
+            case 5:
+            case 6:
+            case 7:   // Single byte char, 0xxxxxxx
+                i++ ;
+                decstr->append( 1, (char)ch ) ;
+                break ;
+            case 12:
+            case 13:  // Double bytes char, 110xxxxx 10xxxxxx
+                i += 2 ;
+
+                if( i > length )
+                    throw CharsetEncodingException("Missing character in double pair") ;
+
+                ch2 = (*str)[i - 1] ;
+                if( (ch2 & 0xC0) != 0x80 )
+                    throw CharsetEncodingException("Invalid second character in double byte pair") ;
+
+                decstr->append( 1, (char)(((ch & 0x1F) << 6) | (ch2 & 0x3F)) ) ;
+                break ;
+            case 14:  // Triple bytes char, 1110xxxx 10xxxxxx 10xxxxxx
+                i += 3 ;
+                if( i > length )
+                    throw CharsetEncodingException("Missing character in triple set") ;
+
+                ch2 = (*str)[i - 2] ;
+                ch3 = (*str)[i - 1] ;
+                if( ((ch2 & 0xC0) != 0x80) || ((ch3 & 0xC0) != 0x80) )
+                    throw CharsetEncodingException("Invalid second and/or third character in triple set") ;
+
+                decstr->append( 1, (char)(((ch & 0x0F) << 12) | ((ch2 & 0x3F) << 6) | ((ch3 & 0x3F) << 0)) ) ;
+                break ;
+            default:  // Unsupported, 10xxxxxx 1111xxxx
+                throw CharsetEncodingException("Unsupported type flag") ;
+        }
+    }
+    return decstr ;
+}

Propchange: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/io/encoding/AsciiToUTF8Encoder.cpp
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/io/encoding/CharsetEncoderRegistry.cpp
URL: http://svn.apache.org/viewvc/incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/io/encoding/CharsetEncoderRegistry.cpp?rev=419422&r1=419421&r2=419422&view=diff
==============================================================================
--- incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/io/encoding/CharsetEncoderRegistry.cpp (original)
+++ incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/io/encoding/CharsetEncoderRegistry.cpp Wed Jul  5 20:17:58 2006
@@ -1,121 +1,121 @@
-/*
- * Copyright 2006 The Apache Software Foundation or its licensors, as
- * applicable.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "ppr/io/encoding/CharsetEncoderRegistry.hpp"
-#include <cctype>
-#include <algorithm>
-
-using namespace apache::ppr::io::encoding;
-
-// Init static members
-map<string, p<ICharsetEncoder> > CharsetEncoderRegistry::encoders ;
-const char* CharsetEncoderRegistry::DEFAULT = AsciiToUTF8Encoder::NAME ;
-
-// Init the default set of encoders
-static CharsetEncoderRegistry::MapInitializer initializer ;
-
-
-// --- Constructors -------------------------------------------------
-
-/*
- *
- */
-CharsetEncoderRegistry::CharsetEncoderRegistry()
-{
-    // no-op
-}
-
-/*
- *
- */
-CharsetEncoderRegistry::~CharsetEncoderRegistry()
-{
-    // no-op
-}
-
-
-// --- Attribute methods --------------------------------------------
-
-/*
- *
- */
-p<ICharsetEncoder> CharsetEncoderRegistry::getEncoder()
-{
-    return getEncoder( CharsetEncoderRegistry::DEFAULT ) ;
-}
-
-/*
- *
- */
-p<ICharsetEncoder> CharsetEncoderRegistry::getEncoder(const char* name)
-{
-    // Assert argument
-    if( name == NULL )
-        return NULL ;
-
-    map<string, p<ICharsetEncoder> >::iterator tempIter ;
-    string key = string(name) ;
-
-    // Make key string all lower case
-    std::transform(key.begin(), key.end(), key.begin(), (int(*)(int))tolower) ;  // The explicit cast is needed to compile on Linux
-
-    // Check if key exists in map
-    tempIter = encoders.find( key ) ;
-    if( tempIter != encoders.end() )
-        return tempIter->second ;
-    else   // Not found
-        return NULL ;
-}
-
-
-// --- Operation methods --------------------------------------------
-
-/*
- *
- */
-void CharsetEncoderRegistry::addEncoder(const char* name, p<ICharsetEncoder> encoder) throw(IllegalArgumentException)
-{
-    // Assert arguments
-    if( name == NULL || encoder == NULL )
-        throw IllegalArgumentException("Name and/or encoder cannot be NULL") ;
-
-    // Make key string all lower case
-    string key = string(name) ;
-    std::transform(key.begin(), key.end(), key.begin(), (int(*)(int))tolower) ;  // The explicit cast is needed to compile on Linux
-
-    encoders[key] = encoder ;
-}
-
-/*
- *
- */
-void CharsetEncoderRegistry::removeEncoder(const char* name) throw(IllegalArgumentException)
-{
-    // Assert argument
-    if( name == NULL )
-        throw IllegalArgumentException("Name cannot be NULL") ;
-
-    map<string, p<ICharsetEncoder> >::iterator tempIter ;
-    string key = string(name) ;
-
-    // Make key string all lower case
-    std::transform(key.begin(), key.end(), key.begin(), (int(*)(int))tolower) ;  // The explicit cast is needed to compile on Linux
-
-    // Check if key exists in map
-    tempIter = encoders.find( key ) ;
-    if( tempIter != encoders.end() )
-        encoders.erase( tempIter ) ;
-}
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as
+ * applicable.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "ppr/io/encoding/CharsetEncoderRegistry.hpp"
+#include <cctype>
+#include <algorithm>
+
+using namespace apache::ppr::io::encoding;
+
+// Init static members
+map<string, p<ICharsetEncoder> > CharsetEncoderRegistry::encoders ;
+const char* CharsetEncoderRegistry::DEFAULT = AsciiToUTF8Encoder::NAME ;
+
+// Init the default set of encoders
+static CharsetEncoderRegistry::MapInitializer initializer ;
+
+
+// --- Constructors -------------------------------------------------
+
+/*
+ *
+ */
+CharsetEncoderRegistry::CharsetEncoderRegistry()
+{
+    // no-op
+}
+
+/*
+ *
+ */
+CharsetEncoderRegistry::~CharsetEncoderRegistry()
+{
+    // no-op
+}
+
+
+// --- Attribute methods --------------------------------------------
+
+/*
+ *
+ */
+p<ICharsetEncoder> CharsetEncoderRegistry::getEncoder()
+{
+    return getEncoder( CharsetEncoderRegistry::DEFAULT ) ;
+}
+
+/*
+ *
+ */
+p<ICharsetEncoder> CharsetEncoderRegistry::getEncoder(const char* name)
+{
+    // Assert argument
+    if( name == NULL )
+        return NULL ;
+
+    map<string, p<ICharsetEncoder> >::iterator tempIter ;
+    string key = string(name) ;
+
+    // Make key string all lower case
+    std::transform(key.begin(), key.end(), key.begin(), (int(*)(int))tolower) ;  // The explicit cast is needed to compile on Linux
+
+    // Check if key exists in map
+    tempIter = encoders.find( key ) ;
+    if( tempIter != encoders.end() )
+        return tempIter->second ;
+    else   // Not found
+        return NULL ;
+}
+
+
+// --- Operation methods --------------------------------------------
+
+/*
+ *
+ */
+void CharsetEncoderRegistry::addEncoder(const char* name, p<ICharsetEncoder> encoder) throw(IllegalArgumentException)
+{
+    // Assert arguments
+    if( name == NULL || encoder == NULL )
+        throw IllegalArgumentException("Name and/or encoder cannot be NULL") ;
+
+    // Make key string all lower case
+    string key = string(name) ;
+    std::transform(key.begin(), key.end(), key.begin(), (int(*)(int))tolower) ;  // The explicit cast is needed to compile on Linux
+
+    encoders[key] = encoder ;
+}
+
+/*
+ *
+ */
+void CharsetEncoderRegistry::removeEncoder(const char* name) throw(IllegalArgumentException)
+{
+    // Assert argument
+    if( name == NULL )
+        throw IllegalArgumentException("Name cannot be NULL") ;
+
+    map<string, p<ICharsetEncoder> >::iterator tempIter ;
+    string key = string(name) ;
+
+    // Make key string all lower case
+    std::transform(key.begin(), key.end(), key.begin(), (int(*)(int))tolower) ;  // The explicit cast is needed to compile on Linux
+
+    // Check if key exists in map
+    tempIter = encoders.find( key ) ;
+    if( tempIter != encoders.end() )
+        encoders.erase( tempIter ) ;
+}

Propchange: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/io/encoding/CharsetEncoderRegistry.cpp
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/ServerSocket.cpp
URL: http://svn.apache.org/viewvc/incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/ServerSocket.cpp?rev=419422&r1=419421&r2=419422&view=diff
==============================================================================
--- incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/ServerSocket.cpp (original)
+++ incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/ServerSocket.cpp Wed Jul  5 20:17:58 2006
@@ -1,158 +1,158 @@
-/*
- * Copyright 2006 The Apache Software Foundation or its licensors, as
- * applicable.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifdef unix
-#include <unistd.h>
-#include <netdb.h>
-#include <fcntl.h>
-#include <sys/file.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#else
-#include <Winsock2.h>
-#include <Ws2tcpip.h> 
-#include <sys/stat.h>
-#define stat _stat
-#endif
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdarg.h>
-#include <ctype.h>
-#include <errno.h>
-#include <sys/types.h>
-#include "ppr/net/ServerSocket.hpp"
-
-using namespace apache::ppr::net;
-
-inline int SOCKETclose( Socket::SocketHandle sock )
-{
-#ifdef unix
-	return ::close(sock);
-#else
-	return ::closesocket(sock);
-#endif
-}
-
-ServerSocket::ServerSocket() : socketHandle (Socket::INVALID_SOCKET_HANDLE)
-{
-#ifndef unix
-    if( Socket::staticSocketInitializer.getSocketInitError() != NULL )
-        throw *Socket::staticSocketInitializer.getSocketInitError();
-#endif
-}
-
-ServerSocket::~ServerSocket()
-{
-    if( isBound() )
-    {
-        // No shutdown, just close - dont want blocking destructor.
-        SOCKETclose (socketHandle);
-    }
-}
-
-void ServerSocket::bind (const char* host, int port) throw (SocketException)
-{
-    bind(host, port, SOMAXCONN);
-}
-
-void ServerSocket::bind (const char* host, int port, int backlog) throw (SocketException)
-{
-    SocketHandle listen_socket_handle;
-	int          ret ;
-
-    if( isBound() )
-        throw SocketException ("Socket already bound") ;
-
-	listen_socket_handle = ::socket(AF_INET, SOCK_STREAM, 0) ;
-
-    if( listen_socket_handle < 0 )
-        throw SocketException ("Could not create socket");
-
-    if( port <= 0 || port > 65535 )
-        throw SocketException ("Port out of range");
-
-    sockaddr_in bind_addr;
-	bind_addr.sin_family = AF_INET;
-	bind_addr.sin_port = htons((short)port);
-	bind_addr.sin_addr.s_addr = 0; // To be set later down...
-    memset(&bind_addr.sin_zero, 0, sizeof(bind_addr.sin_zero));
-
-    // Resolve name
-    ::addrinfo hints;
-    memset(&hints, 0, sizeof(addrinfo));
-    hints.ai_family = PF_INET;
-    struct addrinfo *res_ptr = NULL;
-
-    if( ::getaddrinfo(host, NULL, &hints, &res_ptr) != 0 || res_ptr == NULL )
-        throw SocketException ("Could not resolve name");
-    else
-    {
-        assert(res_ptr->ai_addr->sa_family == AF_INET);
-        // Porting: On both 32bit and 64 bit systems that we compile to soo far, sin_addr is a 32 bit value, not an unsigned long.
-        assert(sizeof(((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr) == 4);
-        bind_addr.sin_addr.s_addr = ((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr;
-        freeaddrinfo(res_ptr);
-    }
-
-	ret = ::bind(listen_socket_handle,
-				 (sockaddr *)&bind_addr, sizeof(bind_addr));
-
-	if( ret < 0 )
-    {
-        SOCKETclose (listen_socket_handle);
-		throw SocketException ("Could not bind");
-	}
-    ret = ::listen(listen_socket_handle, backlog);
-    if( ret < 0 )
-    {
-        SOCKETclose (listen_socket_handle);
-        throw SocketException ("Could not listen");
-    }
-    socketHandle = listen_socket_handle;
-}
-
-void ServerSocket::close ()
-{
-    if( isBound() )
-    {
-        SOCKETclose (this->socketHandle);
-        this->socketHandle = Socket::INVALID_SOCKET_HANDLE;
-    }
-}
-
-bool ServerSocket::isBound() const
-{
-    return this->socketHandle != Socket::INVALID_SOCKET_HANDLE;
-}
-
-p<ISocket> ServerSocket::accept () throw (SocketException)
-{
-    struct sockaddr_in temp;
-#ifdef unix
-    socklen_t temp_len = sizeof (sockaddr_in);
-#else
-    int temp_len = sizeof (sockaddr_in);
-#endif
-    SocketHandle ss_socket_handle = Socket::INVALID_SOCKET_HANDLE;
-
-    ss_socket_handle = ::accept(this->socketHandle, (struct sockaddr*)&temp, &temp_len);
-    if (ss_socket_handle < 0) {
-        throw SocketException ("Accept Error");
-    }
-    return new Socket (ss_socket_handle);
-}
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as
+ * applicable.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifdef unix
+#include <unistd.h>
+#include <netdb.h>
+#include <fcntl.h>
+#include <sys/file.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#else
+#include <Winsock2.h>
+#include <Ws2tcpip.h> 
+#include <sys/stat.h>
+#define stat _stat
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <ctype.h>
+#include <errno.h>
+#include <sys/types.h>
+#include "ppr/net/ServerSocket.hpp"
+
+using namespace apache::ppr::net;
+
+inline int SOCKETclose( Socket::SocketHandle sock )
+{
+#ifdef unix
+	return ::close(sock);
+#else
+	return ::closesocket(sock);
+#endif
+}
+
+ServerSocket::ServerSocket() : socketHandle (Socket::INVALID_SOCKET_HANDLE)
+{
+#ifndef unix
+    if( Socket::staticSocketInitializer.getSocketInitError() != NULL )
+        throw *Socket::staticSocketInitializer.getSocketInitError();
+#endif
+}
+
+ServerSocket::~ServerSocket()
+{
+    if( isBound() )
+    {
+        // No shutdown, just close - dont want blocking destructor.
+        SOCKETclose (socketHandle);
+    }
+}
+
+void ServerSocket::bind (const char* host, int port) throw (SocketException)
+{
+    bind(host, port, SOMAXCONN);
+}
+
+void ServerSocket::bind (const char* host, int port, int backlog) throw (SocketException)
+{
+    SocketHandle listen_socket_handle;
+	int          ret ;
+
+    if( isBound() )
+        throw SocketException ("Socket already bound") ;
+
+	listen_socket_handle = ::socket(AF_INET, SOCK_STREAM, 0) ;
+
+    if( listen_socket_handle < 0 )
+        throw SocketException ("Could not create socket");
+
+    if( port <= 0 || port > 65535 )
+        throw SocketException ("Port out of range");
+
+    sockaddr_in bind_addr;
+	bind_addr.sin_family = AF_INET;
+	bind_addr.sin_port = htons((short)port);
+	bind_addr.sin_addr.s_addr = 0; // To be set later down...
+    memset(&bind_addr.sin_zero, 0, sizeof(bind_addr.sin_zero));
+
+    // Resolve name
+    ::addrinfo hints;
+    memset(&hints, 0, sizeof(addrinfo));
+    hints.ai_family = PF_INET;
+    struct addrinfo *res_ptr = NULL;
+
+    if( ::getaddrinfo(host, NULL, &hints, &res_ptr) != 0 || res_ptr == NULL )
+        throw SocketException ("Could not resolve name");
+    else
+    {
+        assert(res_ptr->ai_addr->sa_family == AF_INET);
+        // Porting: On both 32bit and 64 bit systems that we compile to soo far, sin_addr is a 32 bit value, not an unsigned long.
+        assert(sizeof(((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr) == 4);
+        bind_addr.sin_addr.s_addr = ((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr;
+        freeaddrinfo(res_ptr);
+    }
+
+	ret = ::bind(listen_socket_handle,
+				 (sockaddr *)&bind_addr, sizeof(bind_addr));
+
+	if( ret < 0 )
+    {
+        SOCKETclose (listen_socket_handle);
+		throw SocketException ("Could not bind");
+	}
+    ret = ::listen(listen_socket_handle, backlog);
+    if( ret < 0 )
+    {
+        SOCKETclose (listen_socket_handle);
+        throw SocketException ("Could not listen");
+    }
+    socketHandle = listen_socket_handle;
+}
+
+void ServerSocket::close ()
+{
+    if( isBound() )
+    {
+        SOCKETclose (this->socketHandle);
+        this->socketHandle = Socket::INVALID_SOCKET_HANDLE;
+    }
+}
+
+bool ServerSocket::isBound() const
+{
+    return this->socketHandle != Socket::INVALID_SOCKET_HANDLE;
+}
+
+p<ISocket> ServerSocket::accept () throw (SocketException)
+{
+    struct sockaddr_in temp;
+#ifdef unix
+    socklen_t temp_len = sizeof (sockaddr_in);
+#else
+    int temp_len = sizeof (sockaddr_in);
+#endif
+    SocketHandle ss_socket_handle = Socket::INVALID_SOCKET_HANDLE;
+
+    ss_socket_handle = ::accept(this->socketHandle, (struct sockaddr*)&temp, &temp_len);
+    if (ss_socket_handle < 0) {
+        throw SocketException ("Accept Error");
+    }
+    return new Socket (ss_socket_handle);
+}

Propchange: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/ServerSocket.cpp
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/Socket.cpp
URL: http://svn.apache.org/viewvc/incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/Socket.cpp?rev=419422&r1=419421&r2=419422&view=diff
==============================================================================
--- incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/Socket.cpp (original)
+++ incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/Socket.cpp Wed Jul  5 20:17:58 2006
@@ -1,293 +1,293 @@
-/*
- * Copyright 2006 The Apache Software Foundation or its licensors, as
- * applicable.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifdef unix
-#include <unistd.h>
-#include <netdb.h>
-#include <fcntl.h>
-#include <sys/file.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#else
-#include <Winsock2.h>
-#include <Ws2tcpip.h> 
-#include <sys/stat.h>
-#define stat _stat
-#endif
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdarg.h>
-#include <ctype.h>
-#include <errno.h>
-#include <sys/types.h>
-#include "ppr/net/Socket.hpp"
-
-using namespace apache::ppr::net;
-
-inline int
-SOCKETclose( Socket::SocketHandle sock )
-{
-#ifdef unix
-	return ::close(sock);
-#else
-	return ::closesocket(sock);
-#endif
-}
-
-#ifndef unix // Static socket initializer needed for winsock
-Socket::StaticSocketInitializer::StaticSocketInitializer () {
-    const WORD version_needed = MAKEWORD(2,2); // lo-order byte: major version
-    WSAData temp;
-    if (WSAStartup(version_needed, &temp)){
-        socketInitError = new SocketException ("winsock.dll was not found");
-    }
-}
-Socket::StaticSocketInitializer::~StaticSocketInitializer () {
-    WSACleanup();
-}
-
-Socket::StaticSocketInitializer apache::ppr::net::Socket::staticSocketInitializer;
-#endif
-
-Socket::Socket() : socketHandle (INVALID_SOCKET_HANDLE)
-{
-#ifndef unix
-    if (staticSocketInitializer.getSocketInitError() != NULL) {
-        throw *staticSocketInitializer.getSocketInitError();
-    }
-#endif
-}
-
-Socket::Socket(Socket::SocketHandle socketHandle) : socketHandle (socketHandle)
-{
-}
-
-Socket::~Socket()
-{
-    if (isConnected()) {
-        // No shutdown, just close - dont want blocking destructor.
-        SOCKETclose (socketHandle);
-    }
-}
-
-void
-Socket::connect (const char* host, int port) throw (SocketException)
-{
-	int ret;
-    SocketHandle cs_socket_handle;
-    if (isConnected()) {
-        throw SocketException ("Socket already connected");
-    }
-	cs_socket_handle = ::socket(AF_INET, SOCK_STREAM, 0);
-	if (cs_socket_handle < 0) {
-        throw SocketException ("Could not create socket");
-	}
-    if (port <= 0 || port > 65535) {
-        throw SocketException ("Port out of range");
-    }
-    sockaddr_in target_addr;
-	target_addr.sin_family = AF_INET;
-	target_addr.sin_port = htons((short)port);
-	target_addr.sin_addr.s_addr = 0; // To be set later down...
-    memset(&target_addr.sin_zero, 0, sizeof(target_addr.sin_zero));
-
-    // Resolve name
-    ::addrinfo hints;
-    memset(&hints, 0, sizeof(addrinfo));
-    hints.ai_family = PF_INET;
-    struct addrinfo *res_ptr = NULL;
-    if (::getaddrinfo(host, NULL, &hints, &res_ptr) != 0 || res_ptr == NULL) {
-        throw SocketException ("Could not resolve name");
-    } else {
-        assert(res_ptr->ai_addr->sa_family == AF_INET);
-        // Porting: On both 32bit and 64 bit systems that we compile to soo far, sin_addr is a 32 bit value, not an unsigned long.
-        assert(sizeof(((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr) == 4);
-        target_addr.sin_addr.s_addr = ((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr;
-        freeaddrinfo(res_ptr);
-    }
-
-    ret = ::connect(cs_socket_handle, (const sockaddr *) &target_addr, sizeof(target_addr));
-	if (ret < 0) {
-        SOCKETclose (cs_socket_handle);
-		throw SocketException ("Could not connect to host");
-	}
-    socketHandle = cs_socket_handle;
-}
-
-void
-Socket::setSoTimeout (int millisecs) throw (SocketException)
-{
-#ifdef unix
-  timeval timot;
-  timot.tv_sec = millisecs / 1000;
-  timot.tv_usec = (millisecs % 1000) * 1000;
-#else
-  int timot = millisecs;
-#endif
-  ::setsockopt (socketHandle, SOL_SOCKET, SO_RCVTIMEO, (const char*) &timot, sizeof (timot));
-  ::setsockopt (socketHandle, SOL_SOCKET, SO_SNDTIMEO, (const char*) &timot, sizeof (timot));
-}
-
-int
-Socket::getSoTimeout () const
-{
-#ifdef unix
-  timeval timot;
-  timot.tv_sec = 0;
-  timot.tv_usec = 0;
-  socklen_t size = sizeof(timot);
-#else
-  int timot = 0;
-  int size = sizeof(timot);
-#endif
-  
-  ::getsockopt (socketHandle, SOL_SOCKET, SO_RCVTIMEO, (char*) &timot, &size);
-#ifdef unix
-  return (timot.tv_sec * 1000) + (timot.tv_usec / 1000);
-#else
-  return timot;
-#endif
-}
-#include "ppr/util/Hex.hpp"
-
-int Socket::receive (char* buff, int size) throw (SocketException)
-{
-    if (!isConnected()) {
-        throw SocketException ("Socket not connected");
-    }
-#ifdef unix
-	int rc = ::read(this->socketHandle, buff, size);
-    if (rc < 0) {
-        throw SocketException ("Socket::receieve() failed - socket may have been disconnected") ;
-    }
-#else
-	int rc = ::recv(this->socketHandle, buff, size, 0);
-    if (rc < 0) {
-        char errmsg[256];
-        sprintf (errmsg, "Socket::receive() failed. WSAGetLastError() returned %d", WSAGetLastError());
-        throw SocketException (errmsg);
-    }
-    //printf ("----receive---[%s]\n", apache::ppr::util::Hex::toString (array<char> (buff, rc))->c_str());
-#endif
-    return rc;
-}
-
-int
-Socket::send (const char* buff, int size) throw (SocketException)
-{
-    if (!isConnected()) {
-        throw SocketException ("Socket not connected");
-    }
-#ifdef unix
-	int rc = ::write(this->socketHandle, buff, size);
-    if (rc < 0) {
-        throw SocketException ("Socket::send() failed - socket may have been disconnected");
-    }
-#else
-	int rc = ::send(this->socketHandle, buff, size, 0);
-    if (rc < 0) {
-        char errmsg[256];
-        sprintf (errmsg, "Socket::send() failed. WSAGetLastError() returned %d", WSAGetLastError());
-        throw SocketException (errmsg);
-    }
-#endif
-    //printf ("SOCKETSEND[%s]\n", Hex::toString (array<char> (buff, rc))->c_str());
-    return rc;
-}
-
-int
-Socket::send (const unsigned char* buff, int size) throw (SocketException)
-{
-    return send (reinterpret_cast<const char*> (buff), size);
-}
-
-
-void
-Socket::close ()
-{
-    if (isConnected()) {
-        ::shutdown(this->socketHandle, 2);
-        SOCKETclose (this->socketHandle);
-        this->socketHandle = INVALID_SOCKET_HANDLE;
-    }
-}
-
-bool
-Socket::isConnected() const {
-    return this->socketHandle != INVALID_SOCKET_HANDLE;
-}
-
-
-//
-// Unit test
-//
-#ifdef UNITTEST
-
-#include "ppr/util/ifr/array"
-#include <iostream>
-#include <cassert>
-#include "Thread.hpp"
-#include "ServerSocket.hpp"
-
-class TestServer : public Thread
-{
-public:
-    TestServer () {}
-protected:
-    virtual void run () throw (p<exception>) 
-    {
-        p<ServerSocket> serverSocket = new ServerSocket();
-        serverSocket->bind ("127.0.0.1", 19000);
-        cout << "Server bind successful" << endl;
-        p<ISocket> client = serverSocket->accept();
-        cout << "Server has accepted a connection" << endl;
-        array<char> buff (13);
-        int count = client->receive (buff.c_array(), (int)buff.size());
-        cout << "Server has received " << count << " bytes from client" << endl;
-        assert (count == 13);
-        assert (strcmp (buff.c_array(), "Hello Socket") == 0);
-        cout << "Message was as expected" << endl;
-        cout << "Server sending Good Bye to client and closing connection" << endl;
-        client->send ("Good Bye", 9);
-        client->close();
-    }
-};
-
-void testSocket()
-{
-    p<TestServer> server = new TestServer();
-    cout << "Starting up test server" << endl;
-    server->start ();
-    Socket s;
-    cout << "Trying to connect to server" << endl;
-    s.connect ("127.0.0.1", 19000);
-    cout << "Client sending message to server" << endl;
-    s.send ("Hello Socket", 13);
-    cout << "Client has sent message now" << endl;
-    array<char> buff (9);
-    int count = s.receive (buff.c_array(), (int) buff.size());
-    cout << "Client got a response from server of " << count << " bytes." << endl;
-    assert (count == 9);
-    assert (strcmp (buff.c_array(), "Good Bye") == 0);
-    cout << "Client has verified the server's message" << endl;
-    cout << "Client closes the connection" << endl;
-    s.close();
-}
-
-#endif // UNITTEST
-
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as
+ * applicable.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifdef unix
+#include <unistd.h>
+#include <netdb.h>
+#include <fcntl.h>
+#include <sys/file.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#else
+#include <Winsock2.h>
+#include <Ws2tcpip.h> 
+#include <sys/stat.h>
+#define stat _stat
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <ctype.h>
+#include <errno.h>
+#include <sys/types.h>
+#include "ppr/net/Socket.hpp"
+
+using namespace apache::ppr::net;
+
+inline int
+SOCKETclose( Socket::SocketHandle sock )
+{
+#ifdef unix
+	return ::close(sock);
+#else
+	return ::closesocket(sock);
+#endif
+}
+
+#ifndef unix // Static socket initializer needed for winsock
+Socket::StaticSocketInitializer::StaticSocketInitializer () {
+    const WORD version_needed = MAKEWORD(2,2); // lo-order byte: major version
+    WSAData temp;
+    if (WSAStartup(version_needed, &temp)){
+        socketInitError = new SocketException ("winsock.dll was not found");
+    }
+}
+Socket::StaticSocketInitializer::~StaticSocketInitializer () {
+    WSACleanup();
+}
+
+Socket::StaticSocketInitializer apache::ppr::net::Socket::staticSocketInitializer;
+#endif
+
+Socket::Socket() : socketHandle (INVALID_SOCKET_HANDLE)
+{
+#ifndef unix
+    if (staticSocketInitializer.getSocketInitError() != NULL) {
+        throw *staticSocketInitializer.getSocketInitError();
+    }
+#endif
+}
+
+Socket::Socket(Socket::SocketHandle socketHandle) : socketHandle (socketHandle)
+{
+}
+
+Socket::~Socket()
+{
+    if (isConnected()) {
+        // No shutdown, just close - dont want blocking destructor.
+        SOCKETclose (socketHandle);
+    }
+}
+
+void
+Socket::connect (const char* host, int port) throw (SocketException)
+{
+	int ret;
+    SocketHandle cs_socket_handle;
+    if (isConnected()) {
+        throw SocketException ("Socket already connected");
+    }
+	cs_socket_handle = ::socket(AF_INET, SOCK_STREAM, 0);
+	if (cs_socket_handle < 0) {
+        throw SocketException ("Could not create socket");
+	}
+    if (port <= 0 || port > 65535) {
+        throw SocketException ("Port out of range");
+    }
+    sockaddr_in target_addr;
+	target_addr.sin_family = AF_INET;
+	target_addr.sin_port = htons((short)port);
+	target_addr.sin_addr.s_addr = 0; // To be set later down...
+    memset(&target_addr.sin_zero, 0, sizeof(target_addr.sin_zero));
+
+    // Resolve name
+    ::addrinfo hints;
+    memset(&hints, 0, sizeof(addrinfo));
+    hints.ai_family = PF_INET;
+    struct addrinfo *res_ptr = NULL;
+    if (::getaddrinfo(host, NULL, &hints, &res_ptr) != 0 || res_ptr == NULL) {
+        throw SocketException ("Could not resolve name");
+    } else {
+        assert(res_ptr->ai_addr->sa_family == AF_INET);
+        // Porting: On both 32bit and 64 bit systems that we compile to soo far, sin_addr is a 32 bit value, not an unsigned long.
+        assert(sizeof(((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr) == 4);
+        target_addr.sin_addr.s_addr = ((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr;
+        freeaddrinfo(res_ptr);
+    }
+
+    ret = ::connect(cs_socket_handle, (const sockaddr *) &target_addr, sizeof(target_addr));
+	if (ret < 0) {
+        SOCKETclose (cs_socket_handle);
+		throw SocketException ("Could not connect to host");
+	}
+    socketHandle = cs_socket_handle;
+}
+
+void
+Socket::setSoTimeout (int millisecs) throw (SocketException)
+{
+#ifdef unix
+  timeval timot;
+  timot.tv_sec = millisecs / 1000;
+  timot.tv_usec = (millisecs % 1000) * 1000;
+#else
+  int timot = millisecs;
+#endif
+  ::setsockopt (socketHandle, SOL_SOCKET, SO_RCVTIMEO, (const char*) &timot, sizeof (timot));
+  ::setsockopt (socketHandle, SOL_SOCKET, SO_SNDTIMEO, (const char*) &timot, sizeof (timot));
+}
+
+int
+Socket::getSoTimeout () const
+{
+#ifdef unix
+  timeval timot;
+  timot.tv_sec = 0;
+  timot.tv_usec = 0;
+  socklen_t size = sizeof(timot);
+#else
+  int timot = 0;
+  int size = sizeof(timot);
+#endif
+  
+  ::getsockopt (socketHandle, SOL_SOCKET, SO_RCVTIMEO, (char*) &timot, &size);
+#ifdef unix
+  return (timot.tv_sec * 1000) + (timot.tv_usec / 1000);
+#else
+  return timot;
+#endif
+}
+#include "ppr/util/Hex.hpp"
+
+int Socket::receive (char* buff, int size) throw (SocketException)
+{
+    if (!isConnected()) {
+        throw SocketException ("Socket not connected");
+    }
+#ifdef unix
+	int rc = ::read(this->socketHandle, buff, size);
+    if (rc < 0) {
+        throw SocketException ("Socket::receieve() failed - socket may have been disconnected") ;
+    }
+#else
+	int rc = ::recv(this->socketHandle, buff, size, 0);
+    if (rc < 0) {
+        char errmsg[256];
+        sprintf (errmsg, "Socket::receive() failed. WSAGetLastError() returned %d", WSAGetLastError());
+        throw SocketException (errmsg);
+    }
+    //printf ("----receive---[%s]\n", apache::ppr::util::Hex::toString (array<char> (buff, rc))->c_str());
+#endif
+    return rc;
+}
+
+int
+Socket::send (const char* buff, int size) throw (SocketException)
+{
+    if (!isConnected()) {
+        throw SocketException ("Socket not connected");
+    }
+#ifdef unix
+	int rc = ::write(this->socketHandle, buff, size);
+    if (rc < 0) {
+        throw SocketException ("Socket::send() failed - socket may have been disconnected");
+    }
+#else
+	int rc = ::send(this->socketHandle, buff, size, 0);
+    if (rc < 0) {
+        char errmsg[256];
+        sprintf (errmsg, "Socket::send() failed. WSAGetLastError() returned %d", WSAGetLastError());
+        throw SocketException (errmsg);
+    }
+#endif
+    //printf ("SOCKETSEND[%s]\n", Hex::toString (array<char> (buff, rc))->c_str());
+    return rc;
+}
+
+int
+Socket::send (const unsigned char* buff, int size) throw (SocketException)
+{
+    return send (reinterpret_cast<const char*> (buff), size);
+}
+
+
+void
+Socket::close ()
+{
+    if (isConnected()) {
+        ::shutdown(this->socketHandle, 2);
+        SOCKETclose (this->socketHandle);
+        this->socketHandle = INVALID_SOCKET_HANDLE;
+    }
+}
+
+bool
+Socket::isConnected() const {
+    return this->socketHandle != INVALID_SOCKET_HANDLE;
+}
+
+
+//
+// Unit test
+//
+#ifdef UNITTEST
+
+#include "ppr/util/ifr/array"
+#include <iostream>
+#include <cassert>
+#include "Thread.hpp"
+#include "ServerSocket.hpp"
+
+class TestServer : public Thread
+{
+public:
+    TestServer () {}
+protected:
+    virtual void run () throw (p<exception>) 
+    {
+        p<ServerSocket> serverSocket = new ServerSocket();
+        serverSocket->bind ("127.0.0.1", 19000);
+        cout << "Server bind successful" << endl;
+        p<ISocket> client = serverSocket->accept();
+        cout << "Server has accepted a connection" << endl;
+        array<char> buff (13);
+        int count = client->receive (buff.c_array(), (int)buff.size());
+        cout << "Server has received " << count << " bytes from client" << endl;
+        assert (count == 13);
+        assert (strcmp (buff.c_array(), "Hello Socket") == 0);
+        cout << "Message was as expected" << endl;
+        cout << "Server sending Good Bye to client and closing connection" << endl;
+        client->send ("Good Bye", 9);
+        client->close();
+    }
+};
+
+void testSocket()
+{
+    p<TestServer> server = new TestServer();
+    cout << "Starting up test server" << endl;
+    server->start ();
+    Socket s;
+    cout << "Trying to connect to server" << endl;
+    s.connect ("127.0.0.1", 19000);
+    cout << "Client sending message to server" << endl;
+    s.send ("Hello Socket", 13);
+    cout << "Client has sent message now" << endl;
+    array<char> buff (9);
+    int count = s.receive (buff.c_array(), (int) buff.size());
+    cout << "Client got a response from server of " << count << " bytes." << endl;
+    assert (count == 9);
+    assert (strcmp (buff.c_array(), "Good Bye") == 0);
+    cout << "Client has verified the server's message" << endl;
+    cout << "Client closes the connection" << endl;
+    s.close();
+}
+
+#endif // UNITTEST
+

Propchange: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/Socket.cpp
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/Uri.cpp
URL: http://svn.apache.org/viewvc/incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/Uri.cpp?rev=419422&r1=419421&r2=419422&view=diff
==============================================================================
--- incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/Uri.cpp (original)
+++ incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/Uri.cpp Wed Jul  5 20:17:58 2006
@@ -1,226 +1,226 @@
-/*
- * Copyright 2006 The Apache Software Foundation or its licensors, as
- * applicable.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "ppr/net/Uri.hpp"
-
-using namespace apache::ppr::net;
-
-#ifdef unix
-#define _stricmp strcasecmp
-#endif
-
-Uri::Uri (const string& absoluteUri) : port_(0), bits_ (IS_FAIL)
-{
-  if (absoluteUri.empty()) {
-    bits_ = IS_EMPTY;
-    return;
-  }
-  //
-  // scheme
-  //
-  size_t pColonSlashSlash = absoluteUri.find ("://");
-  if (pColonSlashSlash == absoluteUri.npos) return; // must contain "://"
-  scheme_ = absoluteUri.substr (0, pColonSlashSlash);
-  size_t pHost = pColonSlashSlash + 3; // strlen ("://")
-
-  //
-  // host, port, authority_
-  //
-  size_t pColonOrSlash = absoluteUri.find_first_of (":/", pHost);
-  if (pColonOrSlash != absoluteUri.npos && absoluteUri[pColonOrSlash] == ':') {
-    host_ = absoluteUri.substr (pHost, pColonOrSlash - pHost);
-    long port = atol(absoluteUri.substr (pColonOrSlash + 1).c_str());
-    if (port < 0 || port > 65535) return; // If port is present, it must be between 0 and 65535.
-    port_ = (unsigned short) port;
-    pColonOrSlash = absoluteUri.find ('/', pColonOrSlash + 1); // Make pColonOrSlash point to slash.
-    if (pColonOrSlash != absoluteUri.npos) {
-      authority_ = absoluteUri.substr (pHost, pColonOrSlash - pHost);
-    } else {
-      authority_ = absoluteUri.substr (pHost);
-    }
-  } else {
-    port_ = getDefaultPort (scheme_);
-    if (pColonOrSlash == absoluteUri.npos) {
-      host_ = absoluteUri.substr (pHost);
-    } else {
-      host_ = absoluteUri.substr (pHost, pColonOrSlash - pHost);
-    }
-    authority_ = host_;
-  }
-
-  //
-  // path
-  //
-  if (pColonOrSlash == absoluteUri.npos) {
-    path_ = "/";
-  } else {
-    size_t pQuery = absoluteUri.find ('?', pColonOrSlash);
-    if (pQuery == absoluteUri.npos) {
-      path_ = absoluteUri.substr (pColonOrSlash);
-    } else {
-      path_ = absoluteUri.substr (pColonOrSlash, pQuery - pColonOrSlash);
-      //
-      // query
-      //
-      query_ = absoluteUri.substr (pQuery + 1);
-    }
-  }
-
-  // isFail
-  if (!scheme_.empty() && !path_.empty()) {
-    bits_ = 0;
-  }
-}
-
-Uri::Uri (string uri, const Uri& baseUri) : port_(0), bits_ (IS_FAIL)
-{
-  if (uri[0] == '/') {
-    //
-    // uri is absolute path
-    //
-    *this = baseUri;
-    size_t pQuery = uri.find ('?');
-    if (pQuery == uri.npos) {
-      path_ = uri;
-      query_.clear();
-    } else {
-      path_ = uri.substr (0, pQuery);
-      query_ = uri.substr (pQuery + 1);
-    }
-  } else {
-    size_t pColonOrSlash = uri.find_first_of ("/:");
-    if (pColonOrSlash != uri.npos && uri[pColonOrSlash] == ':' && pColonOrSlash == uri.find ("://")) {
-      //
-      // uri is an Uri
-      //
-      *this = uri;
-    } else {
-      //
-      // uri is a relative path
-      //
-
-      // Copy everything from base Uri to this instance.
-      // We will change path and query only...
-      *this = baseUri;
-
-      // Resolve ".." and "." in beginning of uri:
-      // Check for last slash in base Uri (where to insert uri)
-      size_t pLastSlash = path_.rfind ('/');
-      while (uri.length() > 0 && uri[0] == '.') {
-        if (uri.length() == 1) {
-          // uri is exactly "."
-          uri.clear();
-          break;
-        } else if (uri[1] == '/') {
-          // uri begins with "./"
-          uri = uri.substr (2);
-        } else if (uri[1] == '.') {
-          //
-          // Uri begins with ".." but we dont know the next character...
-          //
-          if (uri.length() == 2) {
-            // uri is exactly ".."
-            uri.clear();
-            // Navigate upwards in directory tree (of path_)
-            if (pLastSlash != path_.npos && pLastSlash > 0) {
-              assert (string ("/1/2/").rfind ('/') == 4); // just to make sure how rfind() works...
-              assert (string ("/1/2/").rfind ('/', 4) == 4); // --""--
-              assert (string ("/1/2/").rfind ('/', 3) == 2); // --""--
-              assert (string ("/").rfind ('/', 0) == 0); // --""--
-              pLastSlash = path_.rfind ('/', pLastSlash - 1);
-            }
-            break;
-          } else if (uri[2] == '/') {
-            // uri begins with "../"
-            uri = uri.substr (3);
-            // Navigate upwards in directory tree (of path_)
-            if (pLastSlash != path_.npos && pLastSlash > 0) {
-              assert (string ("/1/2/").rfind ('/') == 4); // just to make sure how rfind() works...
-              assert (string ("/1/2/").rfind ('/', 4) == 4); // --""--
-              assert (string ("/1/2/").rfind ('/', 3) == 2); // --""--
-              assert (string ("/").rfind ('/', 0) == 0); // --""--
-              pLastSlash = path_.rfind ('/', pLastSlash - 1);
-            }
-          }
-        } 
-      }
-
-      // Check for query in given uri (in order to split path from query, as we do in this class)
-      size_t pQuery = uri.find ('?');
-
-      if (pQuery == uri.npos) {
-        // No query in the uri
-        if (pLastSlash != path_.npos) {
-          // Append URI after last slash in base Uri's path
-          path_ = path_.substr (0, pLastSlash + 1) + uri;
-        } else {
-          // No slash found in base Uri's path. Append a slash in beginning.
-          path_ = "/" + uri;
-        }
-        // Clear the query
-        query_.clear();
-      } else {
-        // Query in the uri
-        if (pLastSlash != path_.npos) {
-          // Append URI after last slash in base Uri's path
-          path_ = path_.substr (0, pLastSlash + 1) + uri.substr (0, pQuery);
-        } else {
-          // No slash found in base Uri's path. Append a slash in beginning.
-          path_ = "/" + uri.substr (0, pQuery);
-        }
-        // Get the query from uri.
-        query_ = uri.substr (pQuery + 1);
-      }
-      
-    }
-  }
-}
-
-unsigned short Uri::getDefaultPort (const string& scheme)
-{
-  if (_stricmp (scheme.c_str(), "http") == 0) {
-    return 80;
-  } else if (_stricmp (scheme.c_str(), "https") == 0) {
-    return 443;
-  } else if (_stricmp (scheme.c_str(), "ftp") == 0) {
-    return 21;
-  } else if (_stricmp (scheme.c_str(), "ssh") == 0) {
-    return 22;
-  } else if (_stricmp (scheme.c_str(), "telnet") == 0) {
-    return 23;
-  } else if (_stricmp (scheme.c_str(), "smtp") == 0) {
-    return 25;
-  } else if (_stricmp (scheme.c_str(), "pop3") == 0) {
-    return 110;
-  } else if (_stricmp (scheme.c_str(), "radius") == 0) {
-    return 1812;
-  } else {
-    return 0;
-  }
-}
-
-bool Uri::isSecure() const
-{
-  if (_stricmp (scheme_.c_str(), "https") == 0 ||
-      _stricmp (scheme_.c_str(), "ssh") == 0 ||
-      _stricmp (scheme_.c_str(), "ftps") == 0)
-  {
-    return true;
-  } else {
-    return false;
-  }
-}
-
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as
+ * applicable.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "ppr/net/Uri.hpp"
+
+using namespace apache::ppr::net;
+
+#ifdef unix
+#define _stricmp strcasecmp
+#endif
+
+Uri::Uri (const string& absoluteUri) : port_(0), bits_ (IS_FAIL)
+{
+  if (absoluteUri.empty()) {
+    bits_ = IS_EMPTY;
+    return;
+  }
+  //
+  // scheme
+  //
+  size_t pColonSlashSlash = absoluteUri.find ("://");
+  if (pColonSlashSlash == absoluteUri.npos) return; // must contain "://"
+  scheme_ = absoluteUri.substr (0, pColonSlashSlash);
+  size_t pHost = pColonSlashSlash + 3; // strlen ("://")
+
+  //
+  // host, port, authority_
+  //
+  size_t pColonOrSlash = absoluteUri.find_first_of (":/", pHost);
+  if (pColonOrSlash != absoluteUri.npos && absoluteUri[pColonOrSlash] == ':') {
+    host_ = absoluteUri.substr (pHost, pColonOrSlash - pHost);
+    long port = atol(absoluteUri.substr (pColonOrSlash + 1).c_str());
+    if (port < 0 || port > 65535) return; // If port is present, it must be between 0 and 65535.
+    port_ = (unsigned short) port;
+    pColonOrSlash = absoluteUri.find ('/', pColonOrSlash + 1); // Make pColonOrSlash point to slash.
+    if (pColonOrSlash != absoluteUri.npos) {
+      authority_ = absoluteUri.substr (pHost, pColonOrSlash - pHost);
+    } else {
+      authority_ = absoluteUri.substr (pHost);
+    }
+  } else {
+    port_ = getDefaultPort (scheme_);
+    if (pColonOrSlash == absoluteUri.npos) {
+      host_ = absoluteUri.substr (pHost);
+    } else {
+      host_ = absoluteUri.substr (pHost, pColonOrSlash - pHost);
+    }
+    authority_ = host_;
+  }
+
+  //
+  // path
+  //
+  if (pColonOrSlash == absoluteUri.npos) {
+    path_ = "/";
+  } else {
+    size_t pQuery = absoluteUri.find ('?', pColonOrSlash);
+    if (pQuery == absoluteUri.npos) {
+      path_ = absoluteUri.substr (pColonOrSlash);
+    } else {
+      path_ = absoluteUri.substr (pColonOrSlash, pQuery - pColonOrSlash);
+      //
+      // query
+      //
+      query_ = absoluteUri.substr (pQuery + 1);
+    }
+  }
+
+  // isFail
+  if (!scheme_.empty() && !path_.empty()) {
+    bits_ = 0;
+  }
+}
+
+Uri::Uri (string uri, const Uri& baseUri) : port_(0), bits_ (IS_FAIL)
+{
+  if (uri[0] == '/') {
+    //
+    // uri is absolute path
+    //
+    *this = baseUri;
+    size_t pQuery = uri.find ('?');
+    if (pQuery == uri.npos) {
+      path_ = uri;
+      query_.clear();
+    } else {
+      path_ = uri.substr (0, pQuery);
+      query_ = uri.substr (pQuery + 1);
+    }
+  } else {
+    size_t pColonOrSlash = uri.find_first_of ("/:");
+    if (pColonOrSlash != uri.npos && uri[pColonOrSlash] == ':' && pColonOrSlash == uri.find ("://")) {
+      //
+      // uri is an Uri
+      //
+      *this = uri;
+    } else {
+      //
+      // uri is a relative path
+      //
+
+      // Copy everything from base Uri to this instance.
+      // We will change path and query only...
+      *this = baseUri;
+
+      // Resolve ".." and "." in beginning of uri:
+      // Check for last slash in base Uri (where to insert uri)
+      size_t pLastSlash = path_.rfind ('/');
+      while (uri.length() > 0 && uri[0] == '.') {
+        if (uri.length() == 1) {
+          // uri is exactly "."
+          uri.clear();
+          break;
+        } else if (uri[1] == '/') {
+          // uri begins with "./"
+          uri = uri.substr (2);
+        } else if (uri[1] == '.') {
+          //
+          // Uri begins with ".." but we dont know the next character...
+          //
+          if (uri.length() == 2) {
+            // uri is exactly ".."
+            uri.clear();
+            // Navigate upwards in directory tree (of path_)
+            if (pLastSlash != path_.npos && pLastSlash > 0) {
+              assert (string ("/1/2/").rfind ('/') == 4); // just to make sure how rfind() works...
+              assert (string ("/1/2/").rfind ('/', 4) == 4); // --""--
+              assert (string ("/1/2/").rfind ('/', 3) == 2); // --""--
+              assert (string ("/").rfind ('/', 0) == 0); // --""--
+              pLastSlash = path_.rfind ('/', pLastSlash - 1);
+            }
+            break;
+          } else if (uri[2] == '/') {
+            // uri begins with "../"
+            uri = uri.substr (3);
+            // Navigate upwards in directory tree (of path_)
+            if (pLastSlash != path_.npos && pLastSlash > 0) {
+              assert (string ("/1/2/").rfind ('/') == 4); // just to make sure how rfind() works...
+              assert (string ("/1/2/").rfind ('/', 4) == 4); // --""--
+              assert (string ("/1/2/").rfind ('/', 3) == 2); // --""--
+              assert (string ("/").rfind ('/', 0) == 0); // --""--
+              pLastSlash = path_.rfind ('/', pLastSlash - 1);
+            }
+          }
+        } 
+      }
+
+      // Check for query in given uri (in order to split path from query, as we do in this class)
+      size_t pQuery = uri.find ('?');
+
+      if (pQuery == uri.npos) {
+        // No query in the uri
+        if (pLastSlash != path_.npos) {
+          // Append URI after last slash in base Uri's path
+          path_ = path_.substr (0, pLastSlash + 1) + uri;
+        } else {
+          // No slash found in base Uri's path. Append a slash in beginning.
+          path_ = "/" + uri;
+        }
+        // Clear the query
+        query_.clear();
+      } else {
+        // Query in the uri
+        if (pLastSlash != path_.npos) {
+          // Append URI after last slash in base Uri's path
+          path_ = path_.substr (0, pLastSlash + 1) + uri.substr (0, pQuery);
+        } else {
+          // No slash found in base Uri's path. Append a slash in beginning.
+          path_ = "/" + uri.substr (0, pQuery);
+        }
+        // Get the query from uri.
+        query_ = uri.substr (pQuery + 1);
+      }
+      
+    }
+  }
+}
+
+unsigned short Uri::getDefaultPort (const string& scheme)
+{
+  if (_stricmp (scheme.c_str(), "http") == 0) {
+    return 80;
+  } else if (_stricmp (scheme.c_str(), "https") == 0) {
+    return 443;
+  } else if (_stricmp (scheme.c_str(), "ftp") == 0) {
+    return 21;
+  } else if (_stricmp (scheme.c_str(), "ssh") == 0) {
+    return 22;
+  } else if (_stricmp (scheme.c_str(), "telnet") == 0) {
+    return 23;
+  } else if (_stricmp (scheme.c_str(), "smtp") == 0) {
+    return 25;
+  } else if (_stricmp (scheme.c_str(), "pop3") == 0) {
+    return 110;
+  } else if (_stricmp (scheme.c_str(), "radius") == 0) {
+    return 1812;
+  } else {
+    return 0;
+  }
+}
+
+bool Uri::isSecure() const
+{
+  if (_stricmp (scheme_.c_str(), "https") == 0 ||
+      _stricmp (scheme_.c_str(), "ssh") == 0 ||
+      _stricmp (scheme_.c_str(), "ftps") == 0)
+  {
+    return true;
+  } else {
+    return false;
+  }
+}
+

Propchange: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/net/Uri.cpp
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/thread/Thread.cpp
URL: http://svn.apache.org/viewvc/incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/thread/Thread.cpp?rev=419422&r1=419421&r2=419422&view=diff
==============================================================================
--- incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/thread/Thread.cpp (original)
+++ incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/thread/Thread.cpp Wed Jul  5 20:17:58 2006
@@ -1,188 +1,188 @@
-/*
- * Copyright 2006 The Apache Software Foundation or its licensors, as
- * applicable.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <memory> // auto_ptr
-#ifdef unix
-#include <errno.h> // EINTR
-#else
-#include <process.h> // _endthreadex
-#endif
-#include "ppr/thread/Thread.hpp"
-
-using namespace apache::ppr::thread;
-
-struct InternalThreadParam
-{
-    p<Thread> threadObject ;
-} ;
-
-#ifdef unix
-static struct ThreadStaticInitializer {
-    // Thread Attribute member
-    pthread_attr_t threadAttribute;
-    // Static Initializer:
-    ThreadStaticInitializer() {
-        pthread_attr_init (&threadAttribute);
-        pthread_attr_setdetachstate (&threadAttribute, PTHREAD_CREATE_JOINABLE);
-    }
-} threadStaticInitializer;
-#endif
-
-/*
- *
- */
-Thread::Thread() : started (false), joined (false)
-{
-}
-
-/*
- *
- */
-Thread::~Thread()
-{
-}
-
-/*
- *
- */
-void Thread::start() throw (runtime_error)
-{
-    if( this->started )
-        throw runtime_error ("Thread already started");
-
-    auto_ptr<InternalThreadParam> threadParam (new InternalThreadParam()) ;
-    threadParam->threadObject = smartify(this) ; // smartify() turns this-pointer into a smart pointer.
-#ifdef unix
-    int err = pthread_create(
-                &this->threadHandle,
-                &threadStaticInitializer.threadAttribute,
-                internal_thread_function,
-                threadParam.get() ) ;
-    if( err != 0 )
-        throw runtime_error ("Coud not start thread") ;
-#else
-    this->threadHandle = CreateThread(NULL, 0, internal_thread_function, threadParam.get(), 0, NULL) ;
-    if (this->threadHandle == NULL)
-        throw runtime_error ("Coud not start thread") ;
-#endif
-    started = true ;
-    threadParam.release() ; // (Does not delete threadParam).
-    // threadParam is deleted in internal_thread_function() after when run() has returned.
-}
-
-p<exception> Thread::join()
-{
-    if( !this->started )
-        throw runtime_error ("Thread::join() called without having called Thread::start()");
-
-    if( !this->joined )
-#ifdef unix
-        pthread_join(this->threadHandle, NULL) ;
-#else
-        WaitForSingleObject (this->threadHandle, INFINITE) ;
-#endif
-    this->joined = true ;
-    return threwnException ;
-}
-
-void Thread::sleep(int millisecs)
-{
-#ifdef unix
-    struct timespec rec, rem ;
-    rec.tv_sec = millisecs / 1000 ;
-    rec.tv_nsec = (millisecs % 1000) * 1000000 ;
-    while ( nanosleep( &rec, &rem ) == EINTR ) ;
-#else
-    Sleep (millisecs) ;
-#endif
-}
-
-#ifdef unix
-void* Thread::internal_thread_function (void* param)
-#else
-unsigned long WINAPI Thread::internal_thread_function (void* param)
-#endif
-{
-    InternalThreadParam* itp = (InternalThreadParam*) param ;
-    try
-    {
-        itp->threadObject->run() ;
-    }
-    catch (exception* e)
-    {
-        itp->threadObject->threwnException = newptr (e) ;
-    }
-    catch (exception& e)
-    {
-        itp->threadObject->threwnException = new exception (e) ;
-    }
-    catch (p<exception> e)
-    {
-        itp->threadObject->threwnException = e ;
-    }
-    catch (...)
-    {
-        itp->threadObject->threwnException = new runtime_error ("An unknown exception was thrown") ;
-    }
-    p<Thread> threadObject = itp->threadObject ;
-    delete itp ;
-#ifdef unix
-    return NULL ;
-#else
-    // Return 0 if no exception was threwn. Otherwise -1.
-    unsigned long retval = (threadObject->threwnException == NULL ? 0 : -1) ;
-    _endthreadex(retval) ; // Needed when using threads and CRT in Windows. Otherwise memleak can appear.
-    return retval ;
-#endif
-}
-
-#ifdef UNITTEST
-
-#include <iostream>
-
-class MyThread : public Thread
-{
-public:
-    bool throwException;
-protected:
-    virtual void run () throw (p<exception>) 
-    {
-        cout << "Running thread" << endl;
-        if (throwException) {
-            cout << "Throwing exception" << endl;
-            throw p<exception> (new runtime_error ("Oops, something went wrong"));
-        } else {
-            cout << "Not throwing exception" << endl;
-        }
-    }
-};
-
-void testThread()
-{
-    p<MyThread> t1 = new MyThread();
-    p<MyThread> t2 = new MyThread();
-    t1->throwException = false;
-    t2->throwException = true;
-    t1->start();
-    t2->start();
-    p<exception> e1 = t1->join();
-    p<exception> e2 = t2->join();
-    assert (e1 == NULL);
-    assert (e2 != NULL);
-    assert (strcmp (e2->what(), "Oops, something went wrong") == 0);
-}
-
-#endif // UNITTEST
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as
+ * applicable.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <memory> // auto_ptr
+#ifdef unix
+#include <errno.h> // EINTR
+#else
+#include <process.h> // _endthreadex
+#endif
+#include "ppr/thread/Thread.hpp"
+
+using namespace apache::ppr::thread;
+
+struct InternalThreadParam
+{
+    p<Thread> threadObject ;
+} ;
+
+#ifdef unix
+static struct ThreadStaticInitializer {
+    // Thread Attribute member
+    pthread_attr_t threadAttribute;
+    // Static Initializer:
+    ThreadStaticInitializer() {
+        pthread_attr_init (&threadAttribute);
+        pthread_attr_setdetachstate (&threadAttribute, PTHREAD_CREATE_JOINABLE);
+    }
+} threadStaticInitializer;
+#endif
+
+/*
+ *
+ */
+Thread::Thread() : started (false), joined (false)
+{
+}
+
+/*
+ *
+ */
+Thread::~Thread()
+{
+}
+
+/*
+ *
+ */
+void Thread::start() throw (runtime_error)
+{
+    if( this->started )
+        throw runtime_error ("Thread already started");
+
+    auto_ptr<InternalThreadParam> threadParam (new InternalThreadParam()) ;
+    threadParam->threadObject = smartify(this) ; // smartify() turns this-pointer into a smart pointer.
+#ifdef unix
+    int err = pthread_create(
+                &this->threadHandle,
+                &threadStaticInitializer.threadAttribute,
+                internal_thread_function,
+                threadParam.get() ) ;
+    if( err != 0 )
+        throw runtime_error ("Coud not start thread") ;
+#else
+    this->threadHandle = CreateThread(NULL, 0, internal_thread_function, threadParam.get(), 0, NULL) ;
+    if (this->threadHandle == NULL)
+        throw runtime_error ("Coud not start thread") ;
+#endif
+    started = true ;
+    threadParam.release() ; // (Does not delete threadParam).
+    // threadParam is deleted in internal_thread_function() after when run() has returned.
+}
+
+p<exception> Thread::join()
+{
+    if( !this->started )
+        throw runtime_error ("Thread::join() called without having called Thread::start()");
+
+    if( !this->joined )
+#ifdef unix
+        pthread_join(this->threadHandle, NULL) ;
+#else
+        WaitForSingleObject (this->threadHandle, INFINITE) ;
+#endif
+    this->joined = true ;
+    return threwnException ;
+}
+
+void Thread::sleep(int millisecs)
+{
+#ifdef unix
+    struct timespec rec, rem ;
+    rec.tv_sec = millisecs / 1000 ;
+    rec.tv_nsec = (millisecs % 1000) * 1000000 ;
+    while ( nanosleep( &rec, &rem ) == EINTR ) ;
+#else
+    Sleep (millisecs) ;
+#endif
+}
+
+#ifdef unix
+void* Thread::internal_thread_function (void* param)
+#else
+unsigned long WINAPI Thread::internal_thread_function (void* param)
+#endif
+{
+    InternalThreadParam* itp = (InternalThreadParam*) param ;
+    try
+    {
+        itp->threadObject->run() ;
+    }
+    catch (exception* e)
+    {
+        itp->threadObject->threwnException = newptr (e) ;
+    }
+    catch (exception& e)
+    {
+        itp->threadObject->threwnException = new exception (e) ;
+    }
+    catch (p<exception> e)
+    {
+        itp->threadObject->threwnException = e ;
+    }
+    catch (...)
+    {
+        itp->threadObject->threwnException = new runtime_error ("An unknown exception was thrown") ;
+    }
+    p<Thread> threadObject = itp->threadObject ;
+    delete itp ;
+#ifdef unix
+    return NULL ;
+#else
+    // Return 0 if no exception was threwn. Otherwise -1.
+    unsigned long retval = (threadObject->threwnException == NULL ? 0 : -1) ;
+    _endthreadex(retval) ; // Needed when using threads and CRT in Windows. Otherwise memleak can appear.
+    return retval ;
+#endif
+}
+
+#ifdef UNITTEST
+
+#include <iostream>
+
+class MyThread : public Thread
+{
+public:
+    bool throwException;
+protected:
+    virtual void run () throw (p<exception>) 
+    {
+        cout << "Running thread" << endl;
+        if (throwException) {
+            cout << "Throwing exception" << endl;
+            throw p<exception> (new runtime_error ("Oops, something went wrong"));
+        } else {
+            cout << "Not throwing exception" << endl;
+        }
+    }
+};
+
+void testThread()
+{
+    p<MyThread> t1 = new MyThread();
+    p<MyThread> t2 = new MyThread();
+    t1->throwException = false;
+    t2->throwException = true;
+    t1->start();
+    t2->start();
+    p<exception> e1 = t1->join();
+    p<exception> e2 = t2->join();
+    assert (e1 == NULL);
+    assert (e2 != NULL);
+    assert (strcmp (e2->what(), "Oops, something went wrong") == 0);
+}
+
+#endif // UNITTEST

Propchange: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/thread/Thread.cpp
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/util/Guid.cpp
URL: http://svn.apache.org/viewvc/incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/util/Guid.cpp?rev=419422&r1=419421&r2=419422&view=diff
==============================================================================
--- incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/util/Guid.cpp (original)
+++ incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/util/Guid.cpp Wed Jul  5 20:17:58 2006
@@ -1,86 +1,86 @@
-/*
- * Copyright 2006 The Apache Software Foundation or its licensors, as
- * applicable.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "ppr/util/Guid.hpp"
-
-using namespace apache::ppr::util;
-
-Guid::Guid()
-{
-    // no-op
-}
-
-/*
- * Creates a new UUID string.
- */
-unsigned char* Guid::getGuid()
-{
-    unsigned char* buffer = new unsigned char[16] ;
-
-#if defined(WIN32) || defined(__CYGWIN__)
-    GUID guid = GUID_NULL ;
-
-	// Create GUID
-    CoCreateGuid(&guid) ;
-    if( guid == GUID_NULL )
-    {
-        // TODO: exception
-        //cerr << "Failed to create an UUID" << endl ;
-        return NULL ;
-    }
-	// Store GUID in internal buffer
-    memcpy(buffer, &guid, 16) ;
-
-#else
-    uuid_t uuid ;
-
-	// Create UUID
-    uuid_generate(uuid) ;
-
-	// Store UUID in internal buffer
-	memcpy(buffer, uuid, 16) ;
-#endif
-
-    return buffer ;
-}
-
-/*
- *
- */
-p<string> Guid::getGuidString()
-{
-    unsigned char* buffer = NULL ;
-    char*          result = NULL ;
-    p<string>      guidStr ;
-
-    buffer = getGuid() ;
-    result = new char[40] ;
-
-    // Format into a string
-    sprintf(result, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
-           buffer[0],  buffer[1],  buffer[2],  buffer[3],
-           buffer[4],  buffer[5],  buffer[6],  buffer[7],
-           buffer[8],  buffer[9],  buffer[10], buffer[11],
-           buffer[12], buffer[13], buffer[14], buffer[15]) ;
-
-    guidStr = new string(result) ;
-
-    // Clean up
-    delete result ;
-    delete buffer ;
-
-    return guidStr ;
-}
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as
+ * applicable.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "ppr/util/Guid.hpp"
+
+using namespace apache::ppr::util;
+
+Guid::Guid()
+{
+    // no-op
+}
+
+/*
+ * Creates a new UUID string.
+ */
+unsigned char* Guid::getGuid()
+{
+    unsigned char* buffer = new unsigned char[16] ;
+
+#if defined(WIN32) || defined(__CYGWIN__)
+    GUID guid = GUID_NULL ;
+
+	// Create GUID
+    CoCreateGuid(&guid) ;
+    if( guid == GUID_NULL )
+    {
+        // TODO: exception
+        //cerr << "Failed to create an UUID" << endl ;
+        return NULL ;
+    }
+	// Store GUID in internal buffer
+    memcpy(buffer, &guid, 16) ;
+
+#else
+    uuid_t uuid ;
+
+	// Create UUID
+    uuid_generate(uuid) ;
+
+	// Store UUID in internal buffer
+	memcpy(buffer, uuid, 16) ;
+#endif
+
+    return buffer ;
+}
+
+/*
+ *
+ */
+p<string> Guid::getGuidString()
+{
+    unsigned char* buffer = NULL ;
+    char*          result = NULL ;
+    p<string>      guidStr ;
+
+    buffer = getGuid() ;
+    result = new char[40] ;
+
+    // Format into a string
+    sprintf(result, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+           buffer[0],  buffer[1],  buffer[2],  buffer[3],
+           buffer[4],  buffer[5],  buffer[6],  buffer[7],
+           buffer[8],  buffer[9],  buffer[10], buffer[11],
+           buffer[12], buffer[13], buffer[14], buffer[15]) ;
+
+    guidStr = new string(result) ;
+
+    // Clean up
+    delete result ;
+    delete buffer ;
+
+    return guidStr ;
+}

Propchange: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/util/Guid.cpp
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/util/Hex.cpp
URL: http://svn.apache.org/viewvc/incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/util/Hex.cpp?rev=419422&r1=419421&r2=419422&view=diff
==============================================================================
--- incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/util/Hex.cpp (original)
+++ incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/util/Hex.cpp Wed Jul  5 20:17:58 2006
@@ -1,51 +1,51 @@
-/*
- * Copyright 2006 The Apache Software Foundation or its licensors, as
- * applicable.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "ppr/util/Hex.hpp"
-
-using namespace apache::ppr::util;
-
-/*
- *
- */
-Hex::Hex()
-{
-    // no-op
-}
-
-/*
- *
- */
-Hex::~Hex()
-{
-    // no-op
-}
-
-/*
- * Converts a byte array into a hex string.
- */
-p<string> Hex::toString(array<char> buffer)
-{
-    array<char> result ((buffer.size() * 2) + 1);
-    p<string> hexStr ;
-
-    // Format into a string
-    for( int i = 0 ; i < (int)buffer.size() ; i++ )
-        sprintf(&result[i*2], "%02x", (unsigned char) buffer[i]) ;
-
-    hexStr = new string(result.c_array(), result.size() - 1) ;
-    return hexStr ;
-}
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as
+ * applicable.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "ppr/util/Hex.hpp"
+
+using namespace apache::ppr::util;
+
+/*
+ *
+ */
+Hex::Hex()
+{
+    // no-op
+}
+
+/*
+ *
+ */
+Hex::~Hex()
+{
+    // no-op
+}
+
+/*
+ * Converts a byte array into a hex string.
+ */
+p<string> Hex::toString(array<char> buffer)
+{
+    array<char> result ((buffer.size() * 2) + 1);
+    p<string> hexStr ;
+
+    // Format into a string
+    for( int i = 0 ; i < (int)buffer.size() ; i++ )
+        sprintf(&result[i*2], "%02x", (unsigned char) buffer[i]) ;
+
+    hexStr = new string(result.c_array(), result.size() - 1) ;
+    return hexStr ;
+}

Propchange: incubator/activemq/trunk/openwire-cpp/src/main/cpp/ppr/util/Hex.cpp
------------------------------------------------------------------------------
    svn:eol-style = native



Mime
View raw message