diff --git a/activemq-cpp/ChangeLog.txt b/activemq-cpp/ChangeLog.txt new file mode 100644 index 0000000000..3562418ea1 --- /dev/null +++ b/activemq-cpp/ChangeLog.txt @@ -0,0 +1,31 @@ + +Version 0.0.2 +---------------------- +New Features: + + * Destinations now support the Destination Options shown here: + http://www.activemq.org/site/destination-options.html + +Additional Changes + + * Extensive code cleanup, including expanded Java DOC comments and more + consistant formatting. + * Memory leak checking with Rational Purify was done and several small + leaks were fixed. + * Added additional Unit tests for new functionality, and additional + tests for existing feature correctness + * Fixed a problem on Windows that was causing the socketinputstream + reads to break unexpectedly. + * Fixed the username, password, client-id processing so they get + out in the ConnectCommand Properly. + * Minor bug fixes + +Known Issues + + * Unchanged from version 0.0.1 + + +Version 0.0.1 +---------------------- + + * Initial Release \ No newline at end of file diff --git a/activemq-cpp/makefile b/activemq-cpp/makefile index 3d7638beca..b35b379316 100644 --- a/activemq-cpp/makefile +++ b/activemq-cpp/makefile @@ -1,4 +1,5 @@ SRCDIR = src +OUTDIR = out MAKESUPPORT_HOME = $(PWD) OFILES = \ @@ -31,6 +32,7 @@ OFILES = \ $(OUTDIR)/main/activemq/core/ActiveMQProducer.o \ $(OUTDIR)/main/activemq/core/ActiveMQConsumer.o \ $(OUTDIR)/main/activemq/core/ActiveMQTransaction.o \ + $(OUTDIR)/main/activemq/core/ActiveMQConstants.o \ \ $(OUTDIR)/main/activemq/io/EndianReader.o \ $(OUTDIR)/main/activemq/io/EndianWriter.o \ @@ -62,6 +64,7 @@ OFILES = \ OTESTFILES = \ $(OUTDIR)/test/main.o \ \ + $(OUTDIR)/test/activemq/core/ActiveMQDestinationTest.o \ $(OUTDIR)/test/activemq/core/ActiveMQConnectionFactoryTest.o \ $(OUTDIR)/test/activemq/core/ActiveMQConnectionTest.o \ $(OUTDIR)/test/activemq/core/ActiveMQSessionTest.o \ @@ -130,10 +133,16 @@ OINTEGRATIONFILES = \ $(OUTDIR)/test-integration/integration/simple/SimpleTester.o \ $(OUTDIR)/test-integration/integration/transactional/TransactionTester.o \ $(OUTDIR)/test-integration/integration/common/AbstractTester.o \ - $(OUTDIR)/test-integration/integration/common/IntegrationCommon.o + $(OUTDIR)/test-integration/integration/common/IntegrationCommon.o \ + $(OUTDIR)/test-integration/integration/various/SimpleRollbackTest.o + -LIBFILE = $(OUTDIR)/activemq.a -TESTEXE = $(OUTDIR)/activemqTest +# Increment this to get a build specific library. +VERSION = 0_0_2 + +LIBRARY_NAME = activemq-cpp-$(VERSION) +LIBFILE = $(OUTDIR)/lib$(LIBRARY_NAME).a +TESTEXE = $(OUTDIR)/activemqTest INTEGRATIONEXE = $(OUTDIR)/activemqIntegrationTests DEFINES = diff --git a/activemq-cpp/makefile-linux-debug.cfg b/activemq-cpp/makefile-linux-debug.cfg index 6fd0f20500..6726fa44bd 100644 --- a/activemq-cpp/makefile-linux-debug.cfg +++ b/activemq-cpp/makefile-linux-debug.cfg @@ -2,17 +2,13 @@ # Compiler specific configuration # -OUTDIR = out -LIBRARY_NAME = activemq-cpp -LIBFILE = $(OUTDIR)/lib$(LIBRARY_NAME).a - # # GCC/G++ debug for Linux # -CC = g++ -frtti -g -pthread -DDEBUG -D_DEBUG -D_REENTRANT -LD = g++ -g -frtti -pthread -CCFLAGS = -Wall -LDFLAGS = -L$(OUTDIR) -l$(LIBRARY_NAME) -lcppunit -ldl -luuid -ARFLAGS = +CC = g++ -frtti -g -pthread -DDEBUG -D_DEBUG -D_REENTRANT +LD = g++ -g -frtti -pthread +CCFLAGS = -Wall +LDFLAGS = -L$(OUTDIR) -l$(LIBRARY_NAME) -lcppunit -ldl -luuid +ARFLAGS = diff --git a/activemq-cpp/makefile-linux-release.cfg b/activemq-cpp/makefile-linux-release.cfg index e6d1121274..d1655045df 100644 --- a/activemq-cpp/makefile-linux-release.cfg +++ b/activemq-cpp/makefile-linux-release.cfg @@ -2,18 +2,13 @@ # Compiler specific configuration # -OUTDIR = out -LIBRARY_NAME = activemq-cpp -LIBFILE = $(OUTDIR)/lib$(LIBRARY_NAME).a - # # GCC/G++ release for Linux # -CC = g++ -frtti -pthread -O3 -DNDEBUG -D_REENTRANT -LD = g++ -frtti -pthread -CCFLAGS = -Wall -LDFLAGS = -L$(OUTDIR) -l$(LIBRARY_NAME) -lcppunit -ldl -luuid -OUTDIR = out -ARFLAGS = +CC = g++ -frtti -pthread -O3 -DNDEBUG -D_REENTRANT +LD = g++ -frtti -pthread +CCFLAGS = -Wall +LDFLAGS = -L$(OUTDIR) -l$(LIBRARY_NAME) -lcppunit -ldl -luuid +ARFLAGS = diff --git a/activemq-cpp/makefile-windows-debug.cfg b/activemq-cpp/makefile-windows-debug.cfg index 9200dafd3b..2abe794963 100644 --- a/activemq-cpp/makefile-windows-debug.cfg +++ b/activemq-cpp/makefile-windows-debug.cfg @@ -2,17 +2,12 @@ # Compiler specific configuration # -OUTDIR = out -LIBRARY_NAME = activemq-cpp -LIBFILE = $(OUTDIR)/lib$(LIBRARY_NAME).a - # # GCC/G++ debug for Linux # -CC = g++ -fexceptions -frtti -O0 -g3 -DDEBUG -D_DEBUG -D_REENTRANT -D_WIN32 -DWINVER=0x0502 -DWIN32_LEAN_AND_MEAN -LD = g++ -g3 -frtti -CCFLAGS = -Wall -LDFLAGS = -L$(OUTDIR) -l$(LIBRARY_NAME) -lcppunit -lws2_32 -lrpcrt4 -OUTDIR = out -ARFLAGS = +CC = g++ -fexceptions -frtti -O0 -g3 -DDEBUG -D_DEBUG -D_REENTRANT -D_WIN32 -DWINVER=0x0502 -DWIN32_LEAN_AND_MEAN +LD = g++ -g3 -frtti +CCFLAGS = -Wall +LDFLAGS = -L$(OUTDIR) -l$(LIBRARY_NAME) -lcppunit -lws2_32 -lrpcrt4 +ARFLAGS = diff --git a/activemq-cpp/makefile-windows-release.cfg b/activemq-cpp/makefile-windows-release.cfg index f5a4fb9a1f..b2ab2bff33 100644 --- a/activemq-cpp/makefile-windows-release.cfg +++ b/activemq-cpp/makefile-windows-release.cfg @@ -2,18 +2,13 @@ # Compiler specific configuration # -OUTDIR = out -LIBRARY_NAME = activemq-cpp -LIBFILE = $(OUTDIR)/lib$(LIBRARY_NAME).a - # # GCC/G++ release for Linux # -CC = g++ -fexceptions -frtti -O3 -DNDEBUG -D_REENTRANT -D__WIN32 -DWIN32_LEAN_AND_MEAN -LD = g++ -frtti -CCFLAGS = -Wall -LDFLAGS = -L$(OUTDIR) -l$(LIBRARY_NAME) -lcppunit -lws2_32 -lrpcrt4 -OUTDIR = out -ARFLAGS = +CC = g++ -fexceptions -frtti -O3 -DNDEBUG -D_REENTRANT -D__WIN32 -DWIN32_LEAN_AND_MEAN +LD = g++ -frtti +CCFLAGS = -Wall +LDFLAGS = -L$(OUTDIR) -l$(LIBRARY_NAME) -lcppunit -lws2_32 -lrpcrt4 +ARFLAGS = diff --git a/activemq-cpp/makefile.cfg b/activemq-cpp/makefile.cfg index 9bfab70a8c..35811a23c5 100644 --- a/activemq-cpp/makefile.cfg +++ b/activemq-cpp/makefile.cfg @@ -84,19 +84,13 @@ default: all $(LIBFILE): $(OFILES) $(DEPLIBS) $(ECHO) " - Creating static library file "$@ - $(ECHO) " - $(AR) $(ARFLAGS) $@ $(OFILES)" $(AR) $(ARFLAGS) $@ $(OFILES) - $(ECHO) 'Finished building target: $@' -$(TESTEXE): $(OTESTFILES) $(LIBFILE) - $(ECHO) " - Creating executable "$@ - $(ECHO) " - $(LD) -o $@ $(OTESTFILES) $(LDFLAGS)" +$(TESTEXE): $(OTESTFILES) $(LD) -o $@ $(OTESTFILES) $(LDFLAGS) $(ECHO) 'Finished building target: $@' -$(INTEGRATIONEXE): $(OINTEGRATIONFILES) $(LIBFILE) - $(ECHO) " - Creating executable "$@ - $(ECHO) " - $(LD) -o $@ $(OINTEGRATIONFILES) $(LDFLAGS)" +$(INTEGRATIONEXE): $(OINTEGRATIONFILES) $(LD) -o $@ $(OINTEGRATIONFILES) $(LDFLAGS) $(ECHO) 'Finished building target: $@' @@ -171,6 +165,7 @@ prepare_integration: $(MD) $(OUTDIR)/test-integration/integration/simple; \ $(MD) $(OUTDIR)/test-integration/integration/transactional; \ $(MD) $(OUTDIR)/test-integration/integration/durable; \ + $(MD) $(OUTDIR)/test-integration/integration/various; \ fi done: diff --git a/activemq-cpp/pom.xml b/activemq-cpp/pom.xml index 7be2e5901d..3f13fbb784 100644 --- a/activemq-cpp/pom.xml +++ b/activemq-cpp/pom.xml @@ -91,6 +91,7 @@ ActiveMQProducer.cpp ActiveMQSession.cpp ActiveMQTransaction.cpp + ActiveMQConstants.cpp diff --git a/activemq-cpp/readme.txt b/activemq-cpp/readme.txt index 9efc91a46e..e1fcafa6e6 100644 --- a/activemq-cpp/readme.txt +++ b/activemq-cpp/readme.txt @@ -1,5 +1,5 @@ -------------------------------------------------------------------------- -ActiveMQ CPP Library - Version 0.0.1 +ActiveMQ CPP Library -------------------------------------------------------------------------- This library provides a JMS like interface to an ActiveMQ broker in c++. diff --git a/activemq-cpp/src/examples/main.cpp b/activemq-cpp/src/examples/main.cpp index 3884aa4946..836f34daf2 100644 --- a/activemq-cpp/src/examples/main.cpp +++ b/activemq-cpp/src/examples/main.cpp @@ -42,7 +42,7 @@ public: virtual void run() { try { // Create a ConnectionFactory - ActiveMQConnectionFactory* connectionFactory = new ActiveMQConnectionFactory("127.0.0.1:61613"); + ActiveMQConnectionFactory* connectionFactory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61613"); // Create a Connection connection = connectionFactory->createConnection(); @@ -143,7 +143,7 @@ public: try { // Create a ConnectionFactory - ActiveMQConnectionFactory* connectionFactory = new ActiveMQConnectionFactory("127.0.0.1:61613"); + ActiveMQConnectionFactory* connectionFactory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61613"); // Create a Connection connection = connectionFactory->createConnection(); diff --git a/activemq-cpp/src/main/activemq/concurrent/Concurrent.h b/activemq-cpp/src/main/activemq/concurrent/Concurrent.h index f2fd4775e7..d59f7925d0 100644 --- a/activemq-cpp/src/main/activemq/concurrent/Concurrent.h +++ b/activemq-cpp/src/main/activemq/concurrent/Concurrent.h @@ -51,11 +51,11 @@ namespace concurrent{ #define WAIT_INFINITE 0xFFFFFFFF -#define synchronized(W) \ - if(false){} \ - else \ - for(activemq::concurrent::Lock lock_W(W); \ - lock_W.isLocked(); lock_W.unlock()) +#define synchronized(W) \ + if(false){} \ + else \ + for(activemq::concurrent::Lock lock_W(W); \ + lock_W.isLocked(); lock_W.unlock()) }} diff --git a/activemq-cpp/src/main/activemq/concurrent/Lock.h b/activemq-cpp/src/main/activemq/concurrent/Lock.h index 2d104548dc..d970c410fb 100644 --- a/activemq-cpp/src/main/activemq/concurrent/Lock.h +++ b/activemq-cpp/src/main/activemq/concurrent/Lock.h @@ -18,106 +18,105 @@ #ifndef ACTIVEMQ_CONCURRENT_LOCK_H #define ACTIVEMQ_CONCURRENT_LOCK_H -// Includes. #include namespace activemq{ namespace concurrent{ - /** - * A wrapper class around a given synchronization mechanism that - * provides automatic release upon destruction. - * @author Nathan Mittler - */ - class Lock - { - private: // Data - /** - * Flag to indicate whether or not this object has locked the - * sync object. + * A wrapper class around a given synchronization mechanism that + * provides automatic release upon destruction. + * @author Nathan Mittler */ - bool locked; + class Lock + { + private: // Data - /** - * The synchronizable object to lock/unlock. - */ - Synchronizable* syncObject; + /** + * Flag to indicate whether or not this object has locked the + * sync object. + */ + bool locked; + + /** + * The synchronizable object to lock/unlock. + */ + Synchronizable* syncObject; - public: // Interface + public: // Interface - /** - * Constructor - initializes the object member and locks - * the object if desired. - * @param object The sync object to control - * @param intiallyLocked If true, the object will automatically - * be locked. - */ - Lock( Synchronizable* object, const bool intiallyLocked = true ) - { - try{ - syncObject = object; - locked = false; - - if( intiallyLocked ) - { - lock(); - } + /** + * Constructor - initializes the object member and locks + * the object if desired. + * @param object The sync object to control + * @param intiallyLocked If true, the object will automatically + * be locked. + */ + Lock( Synchronizable* object, const bool intiallyLocked = true ) + { + try{ + syncObject = object; + locked = false; + + if( intiallyLocked ) + { + lock(); + } + } + AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) } - AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) - AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) - } - - /** - * Destructor - Unlocks the object if it is locked. - */ - virtual ~Lock() - { - try{ - if( locked ) - { - syncObject->unlock(); - } + + /** + * Destructor - Unlocks the object if it is locked. + */ + virtual ~Lock() + { + try{ + if( locked ) + { + syncObject->unlock(); + } + } + AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) } - AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) - AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) - } - /** - * Locks the object. - */ - void lock() - { - try{ - syncObject->lock(); - locked = true; + /** + * Locks the object. + */ + void lock() + { + try{ + syncObject->lock(); + locked = true; + } + AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) } - AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) - AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) - } - /** - * Unlocks the object. - */ - void unlock() - { - try{ - if(locked) - { - syncObject->unlock(); - locked = false; - } + /** + * Unlocks the object. + */ + void unlock() + { + try{ + if(locked) + { + syncObject->unlock(); + locked = false; + } + } + AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) } - AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) - AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) - } - /** - * Indicates whether or not the object is locked. - * @return true if the object is locked, otherwise false. - */ - bool isLocked() const{ return locked; } - }; + /** + * Indicates whether or not the object is locked. + * @return true if the object is locked, otherwise false. + */ + bool isLocked() const{ return locked; } + }; }} diff --git a/activemq-cpp/src/main/activemq/concurrent/Mutex.h b/activemq-cpp/src/main/activemq/concurrent/Mutex.h index b9f510be59..f6b3163f5f 100644 --- a/activemq-cpp/src/main/activemq/concurrent/Mutex.h +++ b/activemq-cpp/src/main/activemq/concurrent/Mutex.h @@ -96,7 +96,7 @@ namespace concurrent{ lock_owner = 0; lock_count = 0; } - + /** * Destructor - destroys the mutex object. */ diff --git a/activemq-cpp/src/main/activemq/concurrent/PooledThread.cpp b/activemq-cpp/src/main/activemq/concurrent/PooledThread.cpp index 34a64d5fcc..692bb9d7f2 100644 --- a/activemq-cpp/src/main/activemq/concurrent/PooledThread.cpp +++ b/activemq-cpp/src/main/activemq/concurrent/PooledThread.cpp @@ -30,19 +30,19 @@ LOGCMS_INITIALIZE(logger, PooledThread, "com.activemq.concurrent.PooledThread"); //////////////////////////////////////////////////////////////////////////////// PooledThread::PooledThread(ThreadPool* pool) { - if(pool == NULL) - { - throw exceptions::IllegalArgumentException( __FILE__, __LINE__, - "PooledThread::PooledThread"); - } + if(pool == NULL) + { + throw exceptions::IllegalArgumentException( __FILE__, __LINE__, + "PooledThread::PooledThread"); + } - busy = false; - done = false; + busy = false; + done = false; - listener = NULL; + listener = NULL; - // Store our Pool. - this->pool = pool; + // Store our Pool. + this->pool = pool; } //////////////////////////////////////////////////////////////////////////////// @@ -53,109 +53,109 @@ PooledThread::~PooledThread() //////////////////////////////////////////////////////////////////////////////// void PooledThread::run(void) { - ThreadPool::Task task; + ThreadPool::Task task; - try - { - while(!done) - { - //LOGCMS_DEBUG(logger, "PooledThread::run - Entering deQ"); + try + { + while(!done) + { + //LOGCMS_DEBUG(logger, "PooledThread::run - Entering deQ"); - // Blocks until there something to be done - task = pool->deQueueTask(); + // Blocks until there something to be done + task = pool->deQueueTask(); - //LOGCMS_DEBUG(logger, "PooledThread::run - Exited deQ"); + //LOGCMS_DEBUG(logger, "PooledThread::run - Exited deQ"); - // Check if the Done Flag is set, in case it happened while we - // were waiting for a task - if(done) - { - break; - } + // Check if the Done Flag is set, in case it happened while we + // were waiting for a task + if(done) + { + break; + } - // If we got here and the runnable was null then something - // bad must have happened. Throw an Exception and bail. - if(!task.first) - { - throw exceptions::ActiveMQException( __FILE__, __LINE__, - "PooledThread::run - Retrieive NULL task from Pool."); - } + // If we got here and the runnable was null then something + // bad must have happened. Throw an Exception and bail. + if(!task.first) + { + throw exceptions::ActiveMQException( __FILE__, __LINE__, + "PooledThread::run - Retrieive NULL task from Pool."); + } - // Got some work to do, so set flag to busy - busy = true; + // Got some work to do, so set flag to busy + busy = true; + + // Inform a listener that we are going to start + if(listener) + { + /*LOGCMS_DEBUG(logger, + "PooledThread::run - Inform Listener we are starting");*/ + listener->onTaskStarted(this); + } + + // Perform the work + task.first->run(); - // Inform a listener that we are going to start - if(listener) - { /*LOGCMS_DEBUG(logger, - "PooledThread::run - Inform Listener we are starting");*/ - listener->onTaskStarted(this); - } - - // Perform the work - task.first->run(); - - /*LOGCMS_DEBUG(logger, - "PooledThread::run - Inform Task Listener we are done");*/ + "PooledThread::run - Inform Task Listener we are done");*/ - // Notify the Task listener that we are done - task.second->onTaskComplete(task.first); + // Notify the Task listener that we are done + task.second->onTaskComplete(task.first); - // Inform a listener that we are going to stop and wait - // for a new task - if(listener) - { - /*LOGCMS_DEBUG(logger, - "PooledThread::run - Inform Listener we are done");*/ - listener->onTaskCompleted(this); - } + // Inform a listener that we are going to stop and wait + // for a new task + if(listener) + { + /*LOGCMS_DEBUG(logger, + "PooledThread::run - Inform Listener we are done");*/ + listener->onTaskCompleted(this); + } - // Set flag to inactive, we will wait for work - busy = false; - } - } - catch(exceptions::ActiveMQException& ex) - { - ex.setMark( __FILE__, __LINE__ ); + // Set flag to inactive, we will wait for work + busy = false; + } + } + catch( exceptions::ActiveMQException& ex ) + { + ex.setMark( __FILE__, __LINE__ ); - // Notify the Task owner - if(task.first && task.second) - { - task.second->onTaskException(task.first, ex); - } + // Notify the Task owner + if(task.first && task.second) + { + task.second->onTaskException(task.first, ex); + } - busy = false; + busy = false; - // Notify the PooledThreadListener - if(listener) - { - listener->onTaskException(this, ex); - } - } - catch(...) - { - exceptions::ActiveMQException ex( - __FILE__, __LINE__, - "PooledThread::run - Caught Unknown Exception"); + // Notify the PooledThreadListener + if(listener) + { + listener->onTaskException(this, ex); + } + } + catch(...) + { + exceptions::ActiveMQException ex( + __FILE__, __LINE__, + "PooledThread::run - Caught Unknown Exception"); - // Notify the Task owner - if(task.first && task.second) - { - task.second->onTaskException(task.first, ex); - } + // Notify the Task owner + if(task.first && task.second) + { + task.second->onTaskException(task.first, ex); + } - busy = false; + busy = false; - // Notify the PooledThreadListener - if(listener) - { - listener->onTaskException(this, ex); - } - } + // Notify the PooledThreadListener + if(listener) + { + listener->onTaskException(this, ex); + } + } } //////////////////////////////////////////////////////////////////////////////// void PooledThread::stop(void) throw ( cms::CMSException ) { - done = true; + done = true; } diff --git a/activemq-cpp/src/main/activemq/concurrent/PooledThread.h b/activemq-cpp/src/main/activemq/concurrent/PooledThread.h index fa8507a6c7..51dec8bca4 100644 --- a/activemq-cpp/src/main/activemq/concurrent/PooledThread.h +++ b/activemq-cpp/src/main/activemq/concurrent/PooledThread.h @@ -28,77 +28,77 @@ namespace activemq{ namespace concurrent{ - class ThreadPool; + class ThreadPool; - class PooledThread : public Thread, public cms::Stoppable - { - private: + class PooledThread : public Thread, public cms::Stoppable + { + private: - // Is this thread currently processing something - bool busy; + // Is this thread currently processing something + bool busy; - // Boolean flag indicating thread should stop - bool done; + // Boolean flag indicating thread should stop + bool done; - // Listener for Task related events - PooledThreadListener* listener; + // Listener for Task related events + PooledThreadListener* listener; - // The thread pool this Pooled Thread is Servicing - ThreadPool* pool; + // The thread pool this Pooled Thread is Servicing + ThreadPool* pool; - // Logger Init - LOGCMS_DECLARE(logger); + // Logger Init + LOGCMS_DECLARE(logger); - public: + public: - /** - * Constructor - */ - PooledThread(ThreadPool* pool); + /** + * Constructor + */ + PooledThread(ThreadPool* pool); - /** - * Destructor - */ - virtual ~PooledThread(void); + /** + * Destructor + */ + virtual ~PooledThread(void); - /** - * Run Method for this object waits for something to be - * enqueued on the ThreadPool and then grabs it and calls - * its run method. - */ - virtual void run(void); + /** + * Run Method for this object waits for something to be + * enqueued on the ThreadPool and then grabs it and calls + * its run method. + */ + virtual void run(void); - /** - * Stops the Thread, thread will complete its task if currently - * running one, and then die. Does not block. - */ - virtual void stop(void) throw ( cms::CMSException ); + /** + * Stops the Thread, thread will complete its task if currently + * running one, and then die. Does not block. + */ + virtual void stop(void) throw ( cms::CMSException ); - /** - * Checks to see if the thread is busy, if busy it means - * that this thread has taken a task from the ThreadPool's - * queue and is processing it. - */ - virtual bool isBusy(void) { return busy; } - - /** - * Adds a listener to this PooledThread to be - * notified when this thread starts and completes a task. - */ - virtual void setPooledThreadListener(PooledThreadListener* listener) - { - this->listener = listener; - } + /** + * Checks to see if the thread is busy, if busy it means + * that this thread has taken a task from the ThreadPool's + * queue and is processing it. + */ + virtual bool isBusy(void) { return busy; } - /** - * Removes a listener for this PooledThread to be - * notified when this thread starts and completes a task. - */ - virtual PooledThreadListener* getPooledThreadListener(void) - { - return this->listener; - } - }; + /** + * Adds a listener to this PooledThread to be + * notified when this thread starts and completes a task. + */ + virtual void setPooledThreadListener(PooledThreadListener* listener) + { + this->listener = listener; + } + + /** + * Removes a listener for this PooledThread to be + * notified when this thread starts and completes a task. + */ + virtual PooledThreadListener* getPooledThreadListener(void) + { + return this->listener; + } + }; }} diff --git a/activemq-cpp/src/main/activemq/concurrent/PooledThreadListener.h b/activemq-cpp/src/main/activemq/concurrent/PooledThreadListener.h index f9151b4c59..40a04392aa 100644 --- a/activemq-cpp/src/main/activemq/concurrent/PooledThreadListener.h +++ b/activemq-cpp/src/main/activemq/concurrent/PooledThreadListener.h @@ -22,44 +22,43 @@ namespace activemq{ namespace concurrent{ - //forward declare - class PooledThread; + class PooledThread; - class PooledThreadListener - { - public: + class PooledThreadListener + { + public: - /** - * Destructor - */ - virtual ~PooledThreadListener(void) {} - - /** - * Called by a pooled thread when it is about to begin - * executing a new task. - * @param Pointer to the Pooled Thread that is making this call - */ - virtual void onTaskStarted(PooledThread* thread) = 0; + /** + * Destructor + */ + virtual ~PooledThreadListener(void) {} + + /** + * Called by a pooled thread when it is about to begin + * executing a new task. + * @param Pointer to the Pooled Thread that is making this call + */ + virtual void onTaskStarted(PooledThread* thread) = 0; - /** - * Called by a pooled thread when it has completed a task - * and is going back to waiting for another task to run - * @param Pointer the the Pooled Thread that is making this call. - */ - virtual void onTaskCompleted(PooledThread* thread) = 0; + /** + * Called by a pooled thread when it has completed a task + * and is going back to waiting for another task to run + * @param Pointer the the Pooled Thread that is making this call. + */ + virtual void onTaskCompleted(PooledThread* thread) = 0; - /** - * Called by a pooled thread when it has encountered an exception - * while running a user task, after receiving this notification - * the callee should assume that the PooledThread is now no longer - * running. - * @param Pointer to the Pooled Thread that is making this call - * @param The Exception that occured. - */ - virtual void onTaskException(PooledThread* thread, - exceptions::ActiveMQException& ex) = 0; + /** + * Called by a pooled thread when it has encountered an exception + * while running a user task, after receiving this notification + * the callee should assume that the PooledThread is now no longer + * running. + * @param Pointer to the Pooled Thread that is making this call + * @param The Exception that occured. + */ + virtual void onTaskException( PooledThread* thread, + exceptions::ActiveMQException& ex) = 0; - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/concurrent/Runnable.h b/activemq-cpp/src/main/activemq/concurrent/Runnable.h index ee8f6a624a..f3bf401d71 100644 --- a/activemq-cpp/src/main/activemq/concurrent/Runnable.h +++ b/activemq-cpp/src/main/activemq/concurrent/Runnable.h @@ -19,23 +19,23 @@ namespace activemq{ namespace concurrent{ - - /** - * Interface for a runnable object - defines a task - * that can be run by a thread. - */ - class Runnable{ - public: - - virtual ~Runnable(){} - - /** - * Run method - called by the Thread class in the context - * of the thread. - */ - virtual void run() = 0; - }; - + + /** + * Interface for a runnable object - defines a task + * that can be run by a thread. + */ + class Runnable{ + public: + + virtual ~Runnable(){} + + /** + * Run method - called by the Thread class in the context + * of the thread. + */ + virtual void run() = 0; + }; + }} #endif /*ACTIVEMQ_CONCURRENT_RUNNABLE_H_*/ diff --git a/activemq-cpp/src/main/activemq/concurrent/Synchronizable.h b/activemq-cpp/src/main/activemq/concurrent/Synchronizable.h index 5377f844bc..28c639c253 100644 --- a/activemq-cpp/src/main/activemq/concurrent/Synchronizable.h +++ b/activemq-cpp/src/main/activemq/concurrent/Synchronizable.h @@ -23,64 +23,64 @@ namespace activemq{ namespace concurrent{ - /** - * The interface for all synchronizable objects (that is, objects - * that can be locked and unlocked). - */ - class Synchronizable - { - public: // Abstract Interface + /** + * The interface for all synchronizable objects (that is, objects + * that can be locked and unlocked). + */ + class Synchronizable + { + public: - virtual ~Synchronizable(){} - - /** - * Locks the object. - * @throws ActiveMQException - */ - virtual void lock() throw(exceptions::ActiveMQException) = 0; - - /** - * Unlocks the object. - * @throws ActiveMQException - */ - virtual void unlock() throw(exceptions::ActiveMQException) = 0; + virtual ~Synchronizable(){} - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void wait() throw(exceptions::ActiveMQException) = 0; - - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. This wait will timeout after the specified time - * interval. - * @param time in millisecsonds to wait, or WAIT_INIFINITE - * @throws ActiveMQException - */ - virtual void wait(unsigned long millisecs) - throw(exceptions::ActiveMQException) = 0; + /** + * Locks the object. + * @throws ActiveMQException + */ + virtual void lock() throw(exceptions::ActiveMQException) = 0; - /** - * Signals a waiter on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void notify() throw(exceptions::ActiveMQException) = 0; + /** + * Unlocks the object. + * @throws ActiveMQException + */ + virtual void unlock() throw(exceptions::ActiveMQException) = 0; - /** - * Signals the waiters on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void notifyAll() throw(exceptions::ActiveMQException) = 0; + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void wait() throw(exceptions::ActiveMQException) = 0; + + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. This wait will timeout after the specified time + * interval. + * @param time in millisecsonds to wait, or WAIT_INIFINITE + * @throws ActiveMQException + */ + virtual void wait(unsigned long millisecs) + throw(exceptions::ActiveMQException) = 0; - }; + /** + * Signals a waiter on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void notify() throw( exceptions::ActiveMQException ) = 0; + + /** + * Signals the waiters on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void notifyAll() throw( exceptions::ActiveMQException ) = 0; + + }; }} diff --git a/activemq-cpp/src/main/activemq/concurrent/TaskListener.h b/activemq-cpp/src/main/activemq/concurrent/TaskListener.h index e46a9075e0..8310367984 100644 --- a/activemq-cpp/src/main/activemq/concurrent/TaskListener.h +++ b/activemq-cpp/src/main/activemq/concurrent/TaskListener.h @@ -23,33 +23,30 @@ namespace activemq{ namespace concurrent{ -class TaskListener -{ -public: - - /** - * Destructor - */ - virtual ~TaskListener() {} - - /** - * Called when a queued task has completed, the task that - * finished is passed along for user consumption - * @param Runnable Pointer to the task that finished - */ - virtual void onTaskComplete(Runnable* task) = 0; - - /** - * Called when a queued task has thrown an exception while - * being run. The Callee should assume that this was an - * unrecoverable exeption and that this task is now defunct. - * @param Runnable Pointer to the task - * @param The ActiveMQException that was thrown. - */ - virtual void onTaskException(Runnable* task, - exceptions::ActiveMQException& ex) = 0; - -}; + class TaskListener + { + public: + + virtual ~TaskListener() {} + + /** + * Called when a queued task has completed, the task that + * finished is passed along for user consumption + * @param Runnable Pointer to the task that finished + */ + virtual void onTaskComplete(Runnable* task) = 0; + + /** + * Called when a queued task has thrown an exception while + * being run. The Callee should assume that this was an + * unrecoverable exeption and that this task is now defunct. + * @param Runnable Pointer to the task + * @param The ActiveMQException that was thrown. + */ + virtual void onTaskException( Runnable* task, + exceptions::ActiveMQException& ex) = 0; + + }; }} diff --git a/activemq-cpp/src/main/activemq/concurrent/Thread.cpp b/activemq-cpp/src/main/activemq/concurrent/Thread.cpp index 5057520c5a..85dd153c6a 100644 --- a/activemq-cpp/src/main/activemq/concurrent/Thread.cpp +++ b/activemq-cpp/src/main/activemq/concurrent/Thread.cpp @@ -19,10 +19,10 @@ #include #ifdef unix - #include // EINTR + #include // EINTR extern int errno; #else - #include // _endthreadex + #include // _endthreadex #endif #include @@ -45,17 +45,17 @@ static struct ThreadStaticInitializer { //////////////////////////////////////////////////////////////////////////////// Thread::Thread() { - task = this; - started = false; - joined = false; + task = this; + started = false; + joined = false; } //////////////////////////////////////////////////////////////////////////////// Thread::Thread( Runnable* task ) { - this->task = task; - started = false; - joined = false; + this->task = task; + started = false; + joined = false; } //////////////////////////////////////////////////////////////////////////////// @@ -72,8 +72,8 @@ void Thread::start() throw ( exceptions::ActiveMQException ) } #ifdef unix - - pthread_attr_init (&attributes); + + pthread_attr_init (&attributes); pthread_attr_setdetachstate (&attributes, PTHREAD_CREATE_JOINABLE); int err = pthread_create ( &this->threadHandle, @@ -81,7 +81,7 @@ void Thread::start() throw ( exceptions::ActiveMQException ) runCallback, this); if (err != 0) { - throw exceptions::ActiveMQException( __FILE__, __LINE__, + throw exceptions::ActiveMQException( __FILE__, __LINE__, "Coud not start thread"); } @@ -91,13 +91,13 @@ void Thread::start() throw ( exceptions::ActiveMQException ) this->threadHandle = (HANDLE)_beginthreadex(NULL, 0, runCallback, this, 0, &threadId); if (this->threadHandle == NULL) { - throw exceptions::ActiveMQException( __FILE__, __LINE__, + throw exceptions::ActiveMQException( __FILE__, __LINE__, "Coud not start thread"); } #endif - // Mark the thread as started. + // Mark the thread as started. started = true; } @@ -105,11 +105,11 @@ void Thread::start() throw ( exceptions::ActiveMQException ) void Thread::join() throw( exceptions::ActiveMQException ) { if (!this->started) { - throw exceptions::ActiveMQException( __FILE__, __LINE__, + throw exceptions::ActiveMQException( __FILE__, __LINE__, "Thread::join() called without having called Thread::start()"); } if (!this->joined) { - + #ifdef unix pthread_join(this->threadHandle, NULL); #else @@ -121,16 +121,16 @@ void Thread::join() throw( exceptions::ActiveMQException ) } //////////////////////////////////////////////////////////////////////////////// -void Thread::sleep(int millisecs) +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 ) == -1 ){ - if( errno != EINTR ){ - break; - } + if( errno != EINTR ){ + break; + } } #else @@ -154,9 +154,9 @@ void* #else unsigned int WINAPI #endif -Thread::runCallback (void* param) +Thread::runCallback( void* param ) { - // Get the instance. + // Get the instance. Thread* thread = (Thread*)param; // Invoke run on the task. diff --git a/activemq-cpp/src/main/activemq/concurrent/Thread.h b/activemq-cpp/src/main/activemq/concurrent/Thread.h index a34352fe01..e29fe45998 100644 --- a/activemq-cpp/src/main/activemq/concurrent/Thread.h +++ b/activemq-cpp/src/main/activemq/concurrent/Thread.h @@ -24,107 +24,108 @@ #if (defined(__unix__) || defined(unix) || defined(MACOSX) || defined(__APPLE__)) && !defined(USG) - #ifndef unix - #define unix - #endif + #ifndef unix + #define unix + #endif - #include + #include #else - #include + #include #endif namespace activemq{ namespace concurrent{ - /** - * Basic thread class - mimics the Java Thread. Derived classes may - * implement the run method, or this class can be used as is with - * a provided Runnable delegate. - */ - class Thread : public Runnable - { - private: + /** + * Basic thread class - mimics the Java Thread. Derived classes may + * implement the run method, or this class can be used as is with + * a provided Runnable delegate. + */ + class Thread : public Runnable + { + private: - /** - * The task to be run by this thread, defaults to - * this thread object. - */ - Runnable* task; + /** + * The task to be run by this thread, defaults to + * this thread object. + */ + Runnable* task; - #ifdef unix - pthread_attr_t attributes; - pthread_t threadHandle ; - #else - HANDLE threadHandle ; - #endif + #ifdef unix + pthread_attr_t attributes; + pthread_t threadHandle; + #else + HANDLE threadHandle; + #endif - /** - * Started state of this thread. - */ - bool started; + /** + * Started state of this thread. + */ + bool started; - /** - * Indicates whether the thread has already been - * joined. - */ - bool joined; + /** + * Indicates whether the thread has already been + * joined. + */ + bool joined; - public: + public: - Thread(); - Thread( Runnable* task ); - virtual ~Thread(); + Thread(); + Thread( Runnable* task ); + virtual ~Thread(); - /** - * Creates a system thread and starts it in a joinable mode. - * Upon creation, the - * run() method of either this object or the provided Runnable - * object will be invoked in the context of this thread. - * @exception runtime_error is thrown if the system could - * not start the thread. - */ - virtual void start() throw (exceptions::ActiveMQException); + /** + * Creates a system thread and starts it in a joinable mode. + * Upon creation, the + * run() method of either this object or the provided Runnable + * object will be invoked in the context of this thread. + * @exception runtime_error is thrown if the system could + * not start the thread. + */ + virtual void start() throw ( exceptions::ActiveMQException ); - /** - * Wait til the thread exits. This is when the run() - * method has returned or has thrown an exception. - * If an exception was thrown in the run() method, - * join() will return the thrown exception. Otherwise - * (if run() returned normally), join() will - * return NULL. - */ - virtual void join() throw (exceptions::ActiveMQException); + /** + * Wait til the thread exits. This is when the run() + * method has returned or has thrown an exception. + * If an exception was thrown in the run() method, + * join() will return the thrown exception. Otherwise + * (if run() returned normally), join() will + * return NULL. + */ + virtual void join() throw ( exceptions::ActiveMQException ); - /** - * Default implementation of the run method - does nothing. - */ - virtual void run(){}; + /** + * Default implementation of the run method - does nothing. + */ + virtual void run(){}; - public: + public: - /** - * Halts execution of the calling thread for a specified no of millisec. - * - * Note that this method is a static method that applies to the - * calling thread and not to the thread object. - */ - static void sleep(int millisecs); + /** + * Halts execution of the calling thread for a specified no of millisec. + * + * Note that this method is a static method that applies to the + * calling thread and not to the thread object. + */ + static void sleep( int millisecs ); - /** - * Obtains the Thread Id of the current thread - * @return Thread Id - */ - static unsigned long getId(void); + /** + * Obtains the Thread Id of the current thread + * @return Thread Id + */ + static unsigned long getId(void); - private: + private: - // Internal thread handling - #ifdef unix - static void* runCallback (void* param); - #else - static unsigned int WINAPI runCallback (void* param); - #endif - } ; + // Internal thread handling + #ifdef unix + static void* runCallback (void* param); + #else + static unsigned int WINAPI runCallback (void* param); + #endif + + }; }} diff --git a/activemq-cpp/src/main/activemq/concurrent/ThreadPool.cpp b/activemq-cpp/src/main/activemq/concurrent/ThreadPool.cpp index 4f1d397f99..803f9cda8a 100644 --- a/activemq-cpp/src/main/activemq/concurrent/ThreadPool.cpp +++ b/activemq-cpp/src/main/activemq/concurrent/ThreadPool.cpp @@ -39,273 +39,279 @@ ThreadPool ThreadPool::instance; //////////////////////////////////////////////////////////////////////////////// ThreadPool::ThreadPool(void) { - maxThreads = DEFAULT_MAX_POOL_SIZE; - blockSize = DEFAULT_MAX_BLOCK_SIZE; - freeThreads = 0; + maxThreads = DEFAULT_MAX_POOL_SIZE; + blockSize = DEFAULT_MAX_BLOCK_SIZE; + freeThreads = 0; - shutdown = false; + shutdown = false; } //////////////////////////////////////////////////////////////////////////////// ThreadPool::~ThreadPool(void) { - try - { - std::vector::iterator itr = pool.begin(); + try + { + std::vector::iterator itr = pool.begin(); - // Stop all the threads - for(; itr != pool.end(); ++itr) - { - (*itr)->stop(); - } + // Stop all the threads + for(; itr != pool.end(); ++itr) + { + (*itr)->stop(); + } - // Set the shutdown flag so that the DeQueue methods all quit - // when we interrupt them. - shutdown = true; + // Set the shutdown flag so that the DeQueue methods all quit + // when we interrupt them. + shutdown = true; - synchronized(&queue) - { - // Signal the Queue so that all waiters are notified - queue.notifyAll(); - } + synchronized(&queue) + { + // Signal the Queue so that all waiters are notified + queue.notifyAll(); + } - // Wait for everyone to die - for(itr = pool.begin(); itr != pool.end(); ++itr) - { - (*itr)->join(); - } - } - AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) - AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) + // Wait for everyone to die + for(itr = pool.begin(); itr != pool.end(); ++itr) + { + (*itr)->join(); + + // Destroy the threads + delete *itr; + } + + pool.clear(); + } + AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) } //////////////////////////////////////////////////////////////////////////////// -void ThreadPool::queueTask(ThreadPool::Task task) +void ThreadPool::queueTask( ThreadPool::Task task ) throw ( exceptions::ActiveMQException ) { - try - { - if(!task.first || !task.second) - { - throw exceptions::IllegalArgumentException( __FILE__, __LINE__, - "ThreadPool::QueueTask - Invalid args for Task"); - } - - //LOGCMS_DEBUG(logger, "ThreadPool::QueueTask - syncing on queue"); + try + { + if(!task.first || !task.second) + { + throw exceptions::IllegalArgumentException( __FILE__, __LINE__, + "ThreadPool::QueueTask - Invalid args for Task"); + } + + //LOGCMS_DEBUG(logger, "ThreadPool::QueueTask - syncing on queue"); - synchronized(&queue) - { - //LOGCMS_DEBUG(logger, "ThreadPool::QueueTask - sync'd, synching pool"); + synchronized(&queue) + { + //LOGCMS_DEBUG(logger, "ThreadPool::QueueTask - sync'd, synching pool"); - // If there's nobody open to do work, then create some more - // threads to handle the work. - if(freeThreads == 0) - { - AllocateThreads(blockSize); - } + // If there's nobody open to do work, then create some more + // threads to handle the work. + if(freeThreads == 0) + { + AllocateThreads(blockSize); + } - //LOGCMS_DEBUG(logger, "ThreadPool::QueueTask - pushing task"); + //LOGCMS_DEBUG(logger, "ThreadPool::QueueTask - pushing task"); - // queue the new work. - queue.push(task); + // queue the new work. + queue.push(task); - //LOGCMS_DEBUG(logger, "ThreadPool::QueueTask - calling notify"); + //LOGCMS_DEBUG(logger, "ThreadPool::QueueTask - calling notify"); - // Inform waiters that we put some work on the queue. - queue.notify(); - } - } - AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) - AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) + // Inform waiters that we put some work on the queue. + queue.notify(); + } + } + AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) } //////////////////////////////////////////////////////////////////////////////// ThreadPool::Task ThreadPool::deQueueTask(void) throw ( exceptions::ActiveMQException ) { - try - { - //LOGCMS_DEBUG(logger, "ThreadPool::DeQueueTask - syncing on queue"); + try + { + //LOGCMS_DEBUG(logger, "ThreadPool::DeQueueTask - syncing on queue"); - synchronized(&queue) - { - /*LOGCMS_DEBUG(logger, - "ThreadPool::DeQueueTask - sync'd checking queue empty");*/ + synchronized(&queue) + { + /*LOGCMS_DEBUG(logger, + "ThreadPool::DeQueueTask - sync'd checking queue empty");*/ - // Wait for work, wait in a while loop since another thread could - // be waiting for a lock and get the work before we get woken up - // from our wait. - while(queue.empty() && !shutdown) - { - //LOGCMS_DEBUG(logger, "ThreadPool::DeQueueTask - Q empty, waiting"); + // Wait for work, wait in a while loop since another thread could + // be waiting for a lock and get the work before we get woken up + // from our wait. + while(queue.empty() && !shutdown) + { + //LOGCMS_DEBUG(logger, "ThreadPool::DeQueueTask - Q empty, waiting"); - queue.wait(); + queue.wait(); - //LOGCMS_DEBUG(logger, "ThreadPool::DeQueueTask - done waiting"); - } + //LOGCMS_DEBUG(logger, "ThreadPool::DeQueueTask - done waiting"); + } - // Don't give more work if we are closing down - if(shutdown) - { - return Task(); - } + // Don't give more work if we are closing down + if(shutdown) + { + return Task(); + } - // check size again. - if(queue.empty()) - { - throw exceptions::ActiveMQException( __FILE__, __LINE__, - "ThreadPool::DeQueueUserWorkItem - Empty Taskn, not in shutdown."); - } + // check size again. + if(queue.empty()) + { + throw exceptions::ActiveMQException( __FILE__, __LINE__, + "ThreadPool::DeQueueUserWorkItem - Empty Taskn, not in shutdown."); + } - //LOGCMS_DEBUG(logger, "ThreadPool::DeQueueTask - popping task"); + //LOGCMS_DEBUG(logger, "ThreadPool::DeQueueTask - popping task"); - // not empty so get the new work to do - return queue.pop(); - } + // not empty so get the new work to do + return queue.pop(); + } - return Task(); - } - AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) - AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) + return Task(); + } + AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) } //////////////////////////////////////////////////////////////////////////////// -void ThreadPool::reserve(unsigned long size) +void ThreadPool::reserve( unsigned long size ) { - try{ - synchronized(&poolLock) - { - if(size < pool.size() || pool.size() == maxThreads) - { - return; - } + try + { + synchronized(&poolLock) + { + if(size < pool.size() || pool.size() == maxThreads) + { + return; + } - // How many do we reserve - unsigned long allocCount = size - pool.size(); + // How many do we reserve + unsigned long allocCount = size - pool.size(); - // Allocate the new Threads - AllocateThreads(allocCount); - } - } - AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) - AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) + // Allocate the new Threads + AllocateThreads(allocCount); + } + } + AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) } //////////////////////////////////////////////////////////////////////////////// -void ThreadPool::setMaxThreads(unsigned long maxThreads) +void ThreadPool::setMaxThreads( unsigned long maxThreads ) { - try - { - synchronized(&poolLock) - { - if(maxThreads == 0) - { - // Caller tried to do something stupid, ignore them. + try + { + synchronized(&poolLock) + { + if(maxThreads == 0) + { + // Caller tried to do something stupid, ignore them. + return; + } + + this->maxThreads = maxThreads; + } + } + AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) +} + +//////////////////////////////////////////////////////////////////////////////// +void ThreadPool::setBlockSize( unsigned long blockSize ) +{ + try + { + if(blockSize <= 0) + { + // User tried something dumb, protect them from themselves return; - } - - this->maxThreads = maxThreads; - } - } - AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) - AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) + } + + synchronized(&poolLock) + { + this->blockSize = blockSize; + } + } + AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) } //////////////////////////////////////////////////////////////////////////////// -void ThreadPool::setBlockSize(unsigned long blockSize) +void ThreadPool::AllocateThreads( unsigned long count ) { - try - { - if(blockSize <= 0) - { - // User tried something dumb, protect them from themselves - return; - } + try + { + if(pool.size() >= maxThreads) + { + return; + } - synchronized(&poolLock) - { - this->blockSize = blockSize; - } - } - AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) - AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) -} - -//////////////////////////////////////////////////////////////////////////////// -void ThreadPool::AllocateThreads(unsigned long count) -{ - try - { - if(pool.size() >= maxThreads) - { - return; - } - - synchronized(&poolLock) - { - // Take the min of alloc size of maxThreads since we don't - // want anybody sneaking eaxtra threads in, greedy bastards. - count = std::min(count, maxThreads - pool.size()); + synchronized(&poolLock) + { + // Take the min of alloc size of maxThreads since we don't + // want anybody sneaking eaxtra threads in, greedy bastards. + count = std::min(count, maxThreads - pool.size()); - // Each time we create a thread we increment the free Threads - // counter, but before we call start so that the Thread doesn't - // get ahead of us. - for(unsigned long i = 0; i < count; ++i) - { - pool.push_back(new PooledThread(this)); - pool.back()->setPooledThreadListener(this); - freeThreads++; - pool.back()->start(); - } - } - } - AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) - AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) + // Each time we create a thread we increment the free Threads + // counter, but before we call start so that the Thread doesn't + // get ahead of us. + for(unsigned long i = 0; i < count; ++i) + { + pool.push_back(new PooledThread(this)); + pool.back()->setPooledThreadListener(this); + freeThreads++; + pool.back()->start(); + } + } + } + AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) } //////////////////////////////////////////////////////////////////////////////// -void ThreadPool::onTaskStarted(PooledThread* thread) +void ThreadPool::onTaskStarted( PooledThread* thread ) { - try - { - synchronized(&poolLock) - { - freeThreads--; + try + { + synchronized(&poolLock) + { + freeThreads--; - // Now that this callback has decremented the free threads coutner - // let check if there is any outstanding work to be done and no - // threads to handle it. This could happen if the QueueTask - // method was called successively without any of the PooledThreads - // having a chance to wake up and service the queue. This would - // cause the number of Task to exceed the number of free threads - // once the Threads got a chance to wake up and service the queue - if(freeThreads == 0 && !queue.empty()) - { - // Allocate a new block of threads - AllocateThreads(blockSize); - } - } + // Now that this callback has decremented the free threads coutner + // let check if there is any outstanding work to be done and no + // threads to handle it. This could happen if the QueueTask + // method was called successively without any of the PooledThreads + // having a chance to wake up and service the queue. This would + // cause the number of Task to exceed the number of free threads + // once the Threads got a chance to wake up and service the queue + if(freeThreads == 0 && !queue.empty()) + { + // Allocate a new block of threads + AllocateThreads(blockSize); + } + } - //LOGCMS_DEBUG(logger, "ThreadPool::onTaskStarted:"); - } - AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) - AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) + //LOGCMS_DEBUG(logger, "ThreadPool::onTaskStarted:"); + } + AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) } //////////////////////////////////////////////////////////////////////////////// -void ThreadPool::onTaskCompleted(PooledThread* thread) +void ThreadPool::onTaskCompleted( PooledThread* thread ) { - try - { - synchronized(&poolLock) - { - freeThreads++; - } + try + { + synchronized(&poolLock) + { + freeThreads++; + } - //LOGCMS_DEBUG(logger, "ThreadPool::onTaskCompleted: "); - } - AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) - AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) + //LOGCMS_DEBUG(logger, "ThreadPool::onTaskCompleted: "); + } + AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) } //////////////////////////////////////////////////////////////////////////////// @@ -313,32 +319,32 @@ void ThreadPool::onTaskException( PooledThread* thread, exceptions::ActiveMQException& ex) { - //LOGCMS_DEBUG(logger, "ThreadPool::onTaskException: "); + //LOGCMS_DEBUG(logger, "ThreadPool::onTaskException: "); - try - { - synchronized(&poolLock) - { - // Delete the thread that had the exception and start a new - // one to take its place. - freeThreads--; + try + { + synchronized(&poolLock) + { + // Delete the thread that had the exception and start a new + // one to take its place. + freeThreads--; - std::vector::iterator itr = - std::find(pool.begin(), pool.end(), thread); + std::vector::iterator itr = + std::find(pool.begin(), pool.end(), thread); - if(itr != pool.end()) - { - pool.erase(itr); - } + if(itr != pool.end()) + { + pool.erase(itr); + } - // Bye-Bye Thread Object - delete thread; + // Bye-Bye Thread Object + delete thread; - // Now allocate a replacement - AllocateThreads(1); - } - } - AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) - AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) + // Now allocate a replacement + AllocateThreads(1); + } + } + AMQ_CATCH_RETHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) } diff --git a/activemq-cpp/src/main/activemq/concurrent/ThreadPool.h b/activemq-cpp/src/main/activemq/concurrent/ThreadPool.h index 8743d56a03..1f9c64afba 100644 --- a/activemq-cpp/src/main/activemq/concurrent/ThreadPool.h +++ b/activemq-cpp/src/main/activemq/concurrent/ThreadPool.h @@ -30,209 +30,202 @@ namespace activemq{ namespace concurrent{ - /** - * Defines a Thread Pool object that implements the functionality - * of pooling threads to perform user tasks. The Thread Poll has - * max size that it will grow to. The thread pool allocates threads - * in blocks. When there are no waiting worker threads and a task - * is queued then a new batch is allocated. The user can specify - * the size of the blocks, otherwise a default value is used. - *

- * When the user queues a task they must also queue a listner to - * be notified when the task has completed, this provides the user - * with a mechanism to know when a task object can be freed. - *

- * To have the Thread Pool perform a task, the user enqueue's an - * object that implements the Runnable insterface and - * one of the worker threads will executing it in its thread context. - */ - class ThreadPool : public PooledThreadListener - { - public: + /** + * Defines a Thread Pool object that implements the functionality + * of pooling threads to perform user tasks. The Thread Poll has + * max size that it will grow to. The thread pool allocates threads + * in blocks. When there are no waiting worker threads and a task + * is queued then a new batch is allocated. The user can specify + * the size of the blocks, otherwise a default value is used. + *

+ * When the user queues a task they must also queue a listner to + * be notified when the task has completed, this provides the user + * with a mechanism to know when a task object can be freed. + *

+ * To have the Thread Pool perform a task, the user enqueue's an + * object that implements the Runnable insterface and + * one of the worker threads will executing it in its thread context. + */ + class ThreadPool : public PooledThreadListener + { + public: - // Constants - static const size_t DEFAULT_MAX_POOL_SIZE = 10; - static const size_t DEFAULT_MAX_BLOCK_SIZE = 3; + // Constants + static const size_t DEFAULT_MAX_POOL_SIZE = 10; + static const size_t DEFAULT_MAX_BLOCK_SIZE = 3; - // Types - typedef std::pair Task; + // Types + typedef std::pair Task; - private: + private: - // Vector of threads that this object has created for its pool. - std::vector< PooledThread* > pool; - - // Queue of Task that are in need of completion - util::Queue queue; - - // Max number of Threads this Pool can contian - unsigned long maxThreads; - - // Max number of tasks that can be allocated at a time - unsigned long blockSize; - - // boolean flag use to indocate that this object is shutting down. - bool shutdown; - - // Count of threads that are currently free to perfom some work. - unsigned long freeThreads; - - // Mutex for locking operations that affect the pool. - Mutex poolLock; + // Vector of threads that this object has created for its pool. + std::vector< PooledThread* > pool; - // Logger Init - LOGCMS_DECLARE(logger); - LOGCMS_DECLARE(marker); + // Queue of Task that are in need of completion + util::Queue queue; - private: // Statics + // Max number of Threads this Pool can contian + unsigned long maxThreads; + + // Max number of tasks that can be allocated at a time + unsigned long blockSize; + + // boolean flag use to indocate that this object is shutting down. + bool shutdown; + + // Count of threads that are currently free to perfom some work. + unsigned long freeThreads; + + // Mutex for locking operations that affect the pool. + Mutex poolLock; + + // Logger Init + LOGCMS_DECLARE(logger); + LOGCMS_DECLARE(marker); + + private: // Statics - // The singleton instance of this class - static ThreadPool instance; + // The singleton instance of this class + static ThreadPool instance; - public: + public: - /** - * Constructor - */ - ThreadPool(void); + ThreadPool(void); + virtual ~ThreadPool(void); - /** - * Destructor - */ - virtual ~ThreadPool(void); + /** + * Queue a task to be completed by one of the Pooled Threads. + * tasks are serviced as soon as a PooledThread + * is available to run it. + * @param object that derives from Runnable + * @throws ActiveMQException + */ + virtual void queueTask(Task task) + throw ( exceptions::ActiveMQException ); - /** - * Queue a task to be completed by one of the Pooled Threads. - * tasks are serviced as soon as a PooledThread - * is available to run it. - * @param object that derives from Runnable - * @throws ActiveMQException - */ - virtual void queueTask(Task task) - throw ( exceptions::ActiveMQException ); + /** + * DeQueue a task to be completed by one of the Pooled Threads. + * A caller of this method will block until there is something + * in the tasks queue, therefore care must be taken when calling + * this function. Normally clients of ThreadPool don't use + * this, only the PooledThread objects owned by + * this ThreadPool. + * @return object that derives from Runnable + * @throws ActiveMQException + */ + virtual Task deQueueTask(void) + throw ( exceptions::ActiveMQException ); - /** - * DeQueue a task to be completed by one of the Pooled Threads. - * A caller of this method will block until there is something - * in the tasks queue, therefore care must be taken when calling - * this function. Normally clients of ThreadPool don't use - * this, only the PooledThread objects owned by - * this ThreadPool. - * @return object that derives from Runnable - * @throws ActiveMQException - */ - virtual Task deQueueTask(void) - throw ( exceptions::ActiveMQException ); + /** + * Returns the current number of Threads in the Pool, this is + * how many there are now, not how many are active or the max + * number that might exist. + * @return integer number of threads in existance. + */ + virtual unsigned long getPoolSize(void) const { return pool.size(); } + + /** + * Returns the current backlog of items in the tasks queue, this + * is how much work is still waiting to get done. + * @return number of outstanding tasks. + */ + virtual unsigned long getBacklog(void) const { return queue.size(); } + + /** + * Ensures that there is at least the specified number of Threads + * allocated to the pool. If the size is greater than the MAX + * number of threads in the pool, then only MAX threads are + * reservved. If the size is smaller than the number of threads + * currently in the pool, than nothing is done. + * @param number of threads to reserve. + */ + virtual void reserve( unsigned long size ); + + /** + * Get the Max Number of Threads this Pool can contain + * @return max size + */ + virtual unsigned long getMaxThreads(void) const { return maxThreads; } - /** - * Returns the current number of Threads in the Pool, this is - * how many there are now, not how many are active or the max - * number that might exist. - * @return integer number of threads in existance. - */ - virtual unsigned long getPoolSize(void) const { return pool.size(); } + /** + * Sets the Max number of threads this pool can contian. + * if this value is smaller than the current size of the + * pool nothing is done. + */ + virtual void setMaxThreads( unsigned long maxThreads ); - /** - * Returns the current backlog of items in the tasks queue, this - * is how much work is still waiting to get done. - * @return number of outstanding tasks. - */ - virtual unsigned long getBacklog(void) const { return queue.size(); } + /** + * Gets the Max number of threads that can be allocated at a time + * when new threads are needed. + * @return max Thread Block Size + */ + virtual unsigned long getBlockSize(void) const { return blockSize; } - /** - * Ensures that there is at least the specified number of Threads - * allocated to the pool. If the size is greater than the MAX - * number of threads in the pool, then only MAX threads are - * reservved. If the size is smaller than the number of threads - * currently in the pool, than nothing is done. - * @param number of threads to reserve. - */ - virtual void reserve(unsigned long size); + /** + * Sets the Max number of Threads that can be allocated at a time + * when the Thread Pool determines that more Threads are needed. + * @param Max Thread Block Size + */ + virtual void setBlockSize( unsigned long blockSize ); - /** - * Get the Max Number of Threads this Pool can contain - * @return max size - */ - virtual unsigned long getMaxThreads(void) const { return maxThreads; } - - /** - * Sets the Max number of threads this pool can contian. - * if this value is smaller than the current size of the - * pool nothing is done. - */ - virtual void setMaxThreads(unsigned long maxThreads); - - /** - * Gets the Max number of threads that can be allocated at a time - * when new threads are needed. - * @return max Thread Block Size - */ - virtual unsigned long getBlockSize(void) const { return blockSize; } - - /** - * Sets the Max number of Threads that can be allocated at a time - * when the Thread Pool determines that more Threads are needed. - * @param Max Thread Block Size - */ - virtual void setBlockSize(unsigned long blockSize); - - /** - * Returns the current number of available threads in the pool, threads - * that are performing a user task are considered unavailable. This value - * could change immeadiately after calling as Threads could finish right - * after and be available again. This is informational only. - * @return totoal free threads - */ - virtual unsigned long getFreeThreadCount(void) const { return freeThreads; } + /** + * Returns the current number of available threads in the pool, threads + * that are performing a user task are considered unavailable. This value + * could change immeadiately after calling as Threads could finish right + * after and be available again. This is informational only. + * @return totoal free threads + */ + virtual unsigned long getFreeThreadCount(void) const { return freeThreads; } - public: // PooledThreadListener Callbacks + public: // PooledThreadListener Callbacks - /** - * Called by a pooled thread when it is about to begin - * executing a new task. This will decrement the available - * threads counter so that this object knows when there are - * no more free threads and must create new ones. - * @param Pointer to the Pooled Thread that is making this call - */ - virtual void onTaskStarted(PooledThread* thread); + /** + * Called by a pooled thread when it is about to begin + * executing a new task. This will decrement the available + * threads counter so that this object knows when there are + * no more free threads and must create new ones. + * @param Pointer to the Pooled Thread that is making this call + */ + virtual void onTaskStarted( PooledThread* thread ); - /** - * Called by a pooled thread when it has completed a task - * and is going back to waiting for another task to run, - * this will increment the free threads counter. - * @param Pointer the the Pooled Thread that is making this call. - */ - virtual void onTaskCompleted(PooledThread* thread); + /** + * Called by a pooled thread when it has completed a task + * and is going back to waiting for another task to run, + * this will increment the free threads counter. + * @param Pointer the the Pooled Thread that is making this call. + */ + virtual void onTaskCompleted( PooledThread* thread ); - /** - * Called by a pooled thread when it has encountered an exception - * while running a user task, after receiving this notification - * the callee should assume that the PooledThread is now no longer - * running. - * @param Pointer to the Pooled Thread that is making this call - * @param The Exception that occured. - */ - virtual void onTaskException(PooledThread* thread, - exceptions::ActiveMQException& ex); + /** + * Called by a pooled thread when it has encountered an exception + * while running a user task, after receiving this notification + * the callee should assume that the PooledThread is now no longer + * running. + * @param Pointer to the Pooled Thread that is making this call + * @param The Exception that occured. + */ + virtual void onTaskException( PooledThread* thread, + exceptions::ActiveMQException& ex); - public: // Statics + public: // Statics - /** - * Return the one and only Thread Pool instance. - * @return The Thread Pool Pointer - */ - static ThreadPool* getInstance(void) { return &instance; } + /** + * Return the one and only Thread Pool instance. + * @return The Thread Pool Pointer + */ + static ThreadPool* getInstance(void) { return &instance; } - private: + private: - /** - * Allocates the requested ammount of Threads, won't exceed - * maxThreads. - * @param the number of threads to create - */ - void AllocateThreads(unsigned long count); + /** + * Allocates the requested ammount of Threads, won't exceed + * maxThreads. + * @param the number of threads to create + */ + void AllocateThreads( unsigned long count ); - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/connector/Connector.h b/activemq-cpp/src/main/activemq/connector/Connector.h index 484c2ebaf1..c04675925e 100644 --- a/activemq-cpp/src/main/activemq/connector/Connector.h +++ b/activemq-cpp/src/main/activemq/connector/Connector.h @@ -72,6 +72,20 @@ namespace connector{ */ virtual std::string getClientId(void) const = 0; + /** + * Gets the Username for this connection, if this + * connection has been closed, then this method returns "" + * @return Username String + */ + virtual std::string getUsername(void) const = 0; + + /** + * Gets the Password for this connection, if this + * connection has been closed, then this method returns "" + * @return Password String + */ + virtual std::string getPassword(void) const = 0; + /** * Gets a reference to the Transport that this connection * is using. @@ -88,7 +102,7 @@ namespace connector{ * @throws ConnectorException */ virtual SessionInfo* createSession( - cms::Session::AcknowledgeMode ackMode) + cms::Session::AcknowledgeMode ackMode ) throw( ConnectorException ) = 0; /** @@ -99,9 +113,9 @@ namespace connector{ * @throws ConnectorException */ virtual ConsumerInfo* createConsumer( - cms::Destination* destination, + const cms::Destination* destination, SessionInfo* session, - const std::string& selector = "") + const std::string& selector = "" ) throw ( ConnectorException ) = 0; /** @@ -116,11 +130,11 @@ namespace connector{ * @throws ConnectorException */ virtual ConsumerInfo* createDurableConsumer( - cms::Topic* topic, + const cms::Topic* topic, SessionInfo* session, const std::string& name, const std::string& selector = "", - bool noLocal = false) + bool noLocal = false ) throw ( ConnectorException ) = 0; /** @@ -131,8 +145,8 @@ namespace connector{ * @throws ConnectorException */ virtual ProducerInfo* createProducer( - cms::Destination* destination, - SessionInfo* session) + const cms::Destination* destination, + SessionInfo* session ) throw ( ConnectorException ) = 0; /** @@ -142,8 +156,8 @@ namespace connector{ * @return a newly created Topic Object * @throws ConnectorException */ - virtual cms::Topic* createTopic(const std::string& name, - SessionInfo* session) + virtual cms::Topic* createTopic( const std::string& name, + SessionInfo* session ) throw ( ConnectorException ) = 0; /** @@ -153,8 +167,8 @@ namespace connector{ * @return a newly created Queue Object * @throws ConnectorException */ - virtual cms::Queue* createQueue(const std::string& name, - SessionInfo* session) + virtual cms::Queue* createQueue( const std::string& name, + SessionInfo* session ) throw ( ConnectorException ) = 0; /** @@ -165,7 +179,7 @@ namespace connector{ * @throws ConnectorException */ virtual cms::TemporaryTopic* createTemporaryTopic( - SessionInfo* session) + SessionInfo* session ) throw ( ConnectorException ) = 0; /** @@ -176,7 +190,7 @@ namespace connector{ * @throws ConnectorException */ virtual cms::TemporaryQueue* createTemporaryQueue( - SessionInfo* session) + SessionInfo* session ) throw ( ConnectorException ) = 0; /** @@ -185,7 +199,7 @@ namespace connector{ * @param Producer Info for the sender of this message * @throws ConnectorException */ - virtual void send(cms::Message* message, ProducerInfo* producerInfo) + virtual void send( cms::Message* message, ProducerInfo* producerInfo ) throw ( ConnectorException ) = 0; /** @@ -194,8 +208,8 @@ namespace connector{ * @param Producer Info for the sender of this message * @throws ConnectorException */ - virtual void send(std::list& messages, - ProducerInfo* producerInfo) + virtual void send( std::list& messages, + ProducerInfo* producerInfo) throw ( ConnectorException ) = 0; /** @@ -203,9 +217,9 @@ namespace connector{ * @param An ActiveMQMessage to Ack. * @throws ConnectorException */ - virtual void acknowledge(const SessionInfo* session, - const cms::Message* message, - AckType ackType = ConsumedAck) + virtual void acknowledge( const SessionInfo* session, + const cms::Message* message, + AckType ackType = ConsumedAck) throw ( ConnectorException ) = 0; /** @@ -214,7 +228,7 @@ namespace connector{ * @throws ConnectorException */ virtual TransactionInfo* startTransaction( - SessionInfo* session) + SessionInfo* session ) throw ( ConnectorException ) = 0; /** @@ -223,8 +237,8 @@ namespace connector{ * @param Session Information * @throws ConnectorException */ - virtual void commit(TransactionInfo* transaction, - SessionInfo* session) + virtual void commit( TransactionInfo* transaction, + SessionInfo* session ) throw ( ConnectorException ) = 0; /** @@ -233,8 +247,8 @@ namespace connector{ * @param Session Information * @throws ConnectorException */ - virtual void rollback(TransactionInfo* transaction, - SessionInfo* session) + virtual void rollback( TransactionInfo* transaction, + SessionInfo* session ) throw ( ConnectorException ) = 0; /** @@ -245,7 +259,7 @@ namespace connector{ */ virtual cms::Message* createMessage( SessionInfo* session, - TransactionInfo* transaction) + TransactionInfo* transaction ) throw ( ConnectorException ) = 0; /** @@ -256,7 +270,7 @@ namespace connector{ */ virtual cms::BytesMessage* createBytesMessage( SessionInfo* session, - TransactionInfo* transaction) + TransactionInfo* transaction ) throw ( ConnectorException ) = 0; /** @@ -267,7 +281,7 @@ namespace connector{ */ virtual cms::TextMessage* createTextMessage( SessionInfo* session, - TransactionInfo* transaction) + TransactionInfo* transaction ) throw ( ConnectorException ) = 0; /** @@ -278,7 +292,7 @@ namespace connector{ */ virtual cms::MapMessage* createMapMessage( SessionInfo* session, - TransactionInfo* transaction) + TransactionInfo* transaction ) throw ( ConnectorException ) = 0; /** @@ -286,7 +300,7 @@ namespace connector{ * @param name of the Subscription * @throws ConnectorException */ - virtual void unsubscribe(const std::string& name) + virtual void unsubscribe( const std::string& name ) throw ( ConnectorException ) = 0; /** @@ -302,14 +316,14 @@ namespace connector{ * @param listener the observer. */ virtual void setConsumerMessageListener( - ConsumerMessageListener* listener) = 0; + ConsumerMessageListener* listener ) = 0; /** * Sets the Listner of exceptions for this connector * @param ExceptionListener the observer. */ virtual void setExceptionListener( - cms::ExceptionListener* listener) = 0; + cms::ExceptionListener* listener ) = 0; }; }} diff --git a/activemq-cpp/src/main/activemq/connector/ConnectorException.h b/activemq-cpp/src/main/activemq/connector/ConnectorException.h index cace625584..51359d7f21 100644 --- a/activemq-cpp/src/main/activemq/connector/ConnectorException.h +++ b/activemq-cpp/src/main/activemq/connector/ConnectorException.h @@ -22,42 +22,44 @@ namespace activemq{ namespace connector{ - /* - * Signals that an Connector exception of some sort has occurred. - */ - class ConnectorException : public exceptions::ActiveMQException - { - public: + /* + * Signals that an Connector exception of some sort has occurred. + */ + class ConnectorException : public exceptions::ActiveMQException + { + public: - ConnectorException() {} - ConnectorException( const exceptions::ActiveMQException& ex ){ - *(ActiveMQException*)this = ex; - } - ConnectorException( const ConnectorException& ex ){ - *(exceptions::ActiveMQException*)this = ex; - } - ConnectorException(const char* file, const int lineNumber, - const char* msg, ...) - { - va_list vargs ; - va_start(vargs, msg) ; - buildMessage(msg, vargs) ; + ConnectorException() {} + ConnectorException( const exceptions::ActiveMQException& ex ){ + *(ActiveMQException*)this = ex; + } + ConnectorException( const ConnectorException& ex ){ + *(exceptions::ActiveMQException*)this = ex; + } + ConnectorException( const char* file, + const int lineNumber, + const char* msg, ... ) + { + va_list vargs; + va_start( vargs, msg ); + buildMessage( msg, vargs ); - // Set the first mark for this exception. - setMark( file, lineNumber ); - } + // Set the first mark for this exception. + setMark( file, lineNumber ); + } - /** - * Clones this exception. This is useful for cases where you need - * to preserve the type of the original exception as well as the message. - * All subclasses should override. - */ - virtual exceptions::ActiveMQException* clone() const{ - return new ConnectorException( *this ); - } - virtual ~ConnectorException() {} + /** + * Clones this exception. This is useful for cases where you need + * to preserve the type of the original exception as well as the message. + * All subclasses should override. + */ + virtual exceptions::ActiveMQException* clone() const{ + return new ConnectorException( *this ); + } + + virtual ~ConnectorException() {} - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/connector/ConnectorFactory.h b/activemq-cpp/src/main/activemq/connector/ConnectorFactory.h index aa652d5f47..d80a3e2489 100644 --- a/activemq-cpp/src/main/activemq/connector/ConnectorFactory.h +++ b/activemq-cpp/src/main/activemq/connector/ConnectorFactory.h @@ -36,10 +36,11 @@ namespace connector{ /** * Creates a connector * @param The Properties that the new connector is configured with + * @param the Transport that the connector should use */ virtual Connector* createConnector( const activemq::util::Properties& properties, - activemq::transport::Transport* transport) = 0; + activemq::transport::Transport* transport ) = 0; }; diff --git a/activemq-cpp/src/main/activemq/connector/ConnectorFactoryMap.cpp b/activemq-cpp/src/main/activemq/connector/ConnectorFactoryMap.cpp index b1514413bb..607ed7f463 100644 --- a/activemq-cpp/src/main/activemq/connector/ConnectorFactoryMap.cpp +++ b/activemq-cpp/src/main/activemq/connector/ConnectorFactoryMap.cpp @@ -31,25 +31,25 @@ ConnectorFactoryMap* ConnectorFactoryMap::getInstance(void) } //////////////////////////////////////////////////////////////////////////////// -void ConnectorFactoryMap::registerConnectorFactory(const std::string& name, - ConnectorFactory* factory) +void ConnectorFactoryMap::registerConnectorFactory( const std::string& name, + ConnectorFactory* factory ) { factoryMap[name] = factory; } //////////////////////////////////////////////////////////////////////////////// -void ConnectorFactoryMap::unregisterConnectorFactory(const std::string& name) +void ConnectorFactoryMap::unregisterConnectorFactory( const std::string& name ) { - factoryMap.erase(name); + factoryMap.erase( name ); } //////////////////////////////////////////////////////////////////////////////// -ConnectorFactory* ConnectorFactoryMap::lookup(const std::string& name) +ConnectorFactory* ConnectorFactoryMap::lookup( const std::string& name ) { std::map::const_iterator itr = - factoryMap.find(name); + factoryMap.find( name ); - if(itr != factoryMap.end()) + if( itr != factoryMap.end() ) { return itr->second; } @@ -60,14 +60,14 @@ ConnectorFactory* ConnectorFactoryMap::lookup(const std::string& name) //////////////////////////////////////////////////////////////////////////////// std::size_t ConnectorFactoryMap::getFactoryNames( - std::vector& factoryList) + std::vector& factoryList ) { std::map::const_iterator itr = factoryMap.begin(); - for(; itr != factoryMap.end(); ++itr) + for( ; itr != factoryMap.end(); ++itr ) { - factoryList.insert(factoryList.end(), itr->first); + factoryList.insert( factoryList.end(), itr->first ); } return factoryMap.size(); diff --git a/activemq-cpp/src/main/activemq/connector/ConnectorFactoryMap.h b/activemq-cpp/src/main/activemq/connector/ConnectorFactoryMap.h index 353596d4c5..fa3eb22e0e 100644 --- a/activemq-cpp/src/main/activemq/connector/ConnectorFactoryMap.h +++ b/activemq-cpp/src/main/activemq/connector/ConnectorFactoryMap.h @@ -27,66 +27,66 @@ namespace activemq{ namespace connector{ - /** - * Lookup Map for Connector Factories. Use the Connector name to - * find the associated factory. This class does not take ownership - * of the stored factories, they must be deallocated somewhere. - */ - class ConnectorFactoryMap - { - public: + /** + * Lookup Map for Connector Factories. Use the Connector name to + * find the associated factory. This class does not take ownership + * of the stored factories, they must be deallocated somewhere. + */ + class ConnectorFactoryMap + { + public: - /** - * Gets a singleton instance of this class. - */ - static ConnectorFactoryMap* getInstance(void); + /** + * Gets a singleton instance of this class. + */ + static ConnectorFactoryMap* getInstance(void); - /** - * Registers a new Connector Factory with this map - * @param name to associate the factory with - * @param factory to store. - */ - void registerConnectorFactory(const std::string& name, - ConnectorFactory* factory); + /** + * Registers a new Connector Factory with this map + * @param name to associate the factory with + * @param factory to store. + */ + void registerConnectorFactory( const std::string& name, + ConnectorFactory* factory ); - /** - * Unregisters a Connector Factory with this map - * @param name of the factory to remove - */ - void unregisterConnectorFactory(const std::string& name); + /** + * Unregisters a Connector Factory with this map + * @param name of the factory to remove + */ + void unregisterConnectorFactory( const std::string& name ); - /** - * Lookup the named factory in the Map - * @param the factory name to lookup - * @return the factory assciated with the name, or NULL - */ - ConnectorFactory* lookup(const std::string& name); + /** + * Lookup the named factory in the Map + * @param the factory name to lookup + * @return the factory assciated with the name, or NULL + */ + ConnectorFactory* lookup( const std::string& name ); - /** - * Fetch a list of factory names that this Map contains - * @param vector object to receive the list - * @returns count of factories. - */ - std::size_t getFactoryNames(std::vector& factoryList); + /** + * Fetch a list of factory names that this Map contains + * @param vector object to receive the list + * @returns count of factories. + */ + std::size_t getFactoryNames( std::vector< std::string >& factoryList ); - private: + private: - // Hidden Contrustor, prevents instantiation - ConnectorFactoryMap() {}; + // Hidden Contrustor, prevents instantiation + ConnectorFactoryMap() {}; - // Hidden Destructor. - virtual ~ConnectorFactoryMap() {}; + // Hidden Destructor. + virtual ~ConnectorFactoryMap() {}; - // Hidden Copy Constructore - ConnectorFactoryMap(const ConnectorFactoryMap& factoryMap); + // Hidden Copy Constructore + ConnectorFactoryMap( const ConnectorFactoryMap& factoryMap ); - // Hidden Assignment operator - ConnectorFactoryMap operator=(const ConnectorFactoryMap& factoryMap); + // Hidden Assignment operator + ConnectorFactoryMap operator=( const ConnectorFactoryMap& factoryMap ); - // Map of Factories - std::map factoryMap; + // Map of Factories + std::map< std::string, ConnectorFactory* > factoryMap; - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/connector/ConnectorFactoryMapRegistrar.h b/activemq-cpp/src/main/activemq/connector/ConnectorFactoryMapRegistrar.h index 78e61b8042..62c15dc274 100644 --- a/activemq-cpp/src/main/activemq/connector/ConnectorFactoryMapRegistrar.h +++ b/activemq-cpp/src/main/activemq/connector/ConnectorFactoryMapRegistrar.h @@ -59,9 +59,9 @@ namespace connector{ { // UnRegister it in the map. ConnectorFactoryMap::getInstance()-> - unregisterConnectorFactory(name); + unregisterConnectorFactory( name ); - if(manageLifetime) + if( manageLifetime ) { delete factory; } diff --git a/activemq-cpp/src/main/activemq/connector/ConnectorResource.h b/activemq-cpp/src/main/activemq/connector/ConnectorResource.h index 1278354299..1d064421e9 100644 --- a/activemq-cpp/src/main/activemq/connector/ConnectorResource.h +++ b/activemq-cpp/src/main/activemq/connector/ConnectorResource.h @@ -14,10 +14,8 @@ namespace connector{ { public: - /** - * Destructor - */ virtual ~ConnectorResource() {} + }; }} diff --git a/activemq-cpp/src/main/activemq/connector/ConsumerInfo.h b/activemq-cpp/src/main/activemq/connector/ConsumerInfo.h index f5daf6678a..9d5c4e0926 100644 --- a/activemq-cpp/src/main/activemq/connector/ConsumerInfo.h +++ b/activemq-cpp/src/main/activemq/connector/ConsumerInfo.h @@ -29,9 +29,6 @@ namespace connector{ { public: - /** - * Destructor - */ virtual ~ConsumerInfo(void) {} /** diff --git a/activemq-cpp/src/main/activemq/connector/ConsumerMessageListener.h b/activemq-cpp/src/main/activemq/connector/ConsumerMessageListener.h index 6e534be5d2..9021569552 100644 --- a/activemq-cpp/src/main/activemq/connector/ConsumerMessageListener.h +++ b/activemq-cpp/src/main/activemq/connector/ConsumerMessageListener.h @@ -37,8 +37,10 @@ namespace connector{ * @param consumer the target consumer of the dispatch. * @param msg the message to be dispatched. */ - virtual void onConsumerMessage( ConsumerInfo* consumer, + virtual void onConsumerMessage( + ConsumerInfo* consumer, core::ActiveMQMessage* msg ) = 0; + }; }} diff --git a/activemq-cpp/src/main/activemq/connector/SessionInfo.h b/activemq-cpp/src/main/activemq/connector/SessionInfo.h index fbd1662c6d..d6b45aaff3 100644 --- a/activemq-cpp/src/main/activemq/connector/SessionInfo.h +++ b/activemq-cpp/src/main/activemq/connector/SessionInfo.h @@ -28,9 +28,6 @@ namespace connector{ { public: - /** - * Destructor - */ virtual ~SessionInfo(void) {} /** diff --git a/activemq-cpp/src/main/activemq/connector/TransactionInfo.h b/activemq-cpp/src/main/activemq/connector/TransactionInfo.h index 677674878c..75d75fb2eb 100644 --- a/activemq-cpp/src/main/activemq/connector/TransactionInfo.h +++ b/activemq-cpp/src/main/activemq/connector/TransactionInfo.h @@ -28,9 +28,6 @@ namespace connector{ { public: - /** - * Destructor - */ virtual ~TransactionInfo(void) {} /** diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompCommandListener.h b/activemq-cpp/src/main/activemq/connector/stomp/StompCommandListener.h index e83ba43d13..dc7be426f7 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompCommandListener.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompCommandListener.h @@ -33,7 +33,7 @@ namespace stomp{ { public: - virtual ~StompCommandListener(void) {} + virtual ~StompCommandListener(void) {} /** * Process the Stomp Command diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompCommandReader.cpp b/activemq-cpp/src/main/activemq/connector/stomp/StompCommandReader.cpp index ff73064ebb..2ba0d9b164 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompCommandReader.cpp +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompCommandReader.cpp @@ -35,14 +35,14 @@ StompCommandReader::StompCommandReader(void) } //////////////////////////////////////////////////////////////////////////////// -StompCommandReader::StompCommandReader(InputStream* is) +StompCommandReader::StompCommandReader( InputStream* is ) { inputStream = is; } //////////////////////////////////////////////////////////////////////////////// Command* StompCommandReader::readCommand(void) - throw (CommandIOException) + throw ( CommandIOException ) { try { @@ -70,53 +70,53 @@ Command* StompCommandReader::readCommand(void) void StompCommandReader::readStompCommand( StompFrame& frame ) throw ( StompConnectorException ) { - while( true ) - { - // Clean up the mess. - buffer.clear(); + while( true ) + { + // Clean up the mess. + buffer.clear(); - // Read the command; - readStompHeaderLine(); + // Read the command; + readStompHeaderLine(); // Ignore all white space before the command. int offset=-1; for( size_t ix = 0; ix < buffer.size()-1; ++ix ) { - // Find the first non space character - char b = buffer[ix]; + // Find the first non space character + char b = buffer[ix]; switch ( b ) { - case '\n': - case '\t': - case '\r': - break; - - default: - offset = ix; - break; + case '\n': + case '\t': + case '\r': + break; + + default: + offset = ix; + break; } - if( offset != -1 ) - { - break; - } + if( offset != -1 ) + { + break; + } } - - if( offset >= 0 ) - { - // Set the command in the frame - copy the memory. - frame.setCommand( reinterpret_cast(&buffer[offset]) ); - break; - } - - } + + if( offset >= 0 ) + { + // Set the command in the frame - copy the memory. + frame.setCommand( reinterpret_cast(&buffer[offset]) ); + break; + } + + } // Clean up the mess. buffer.clear(); } //////////////////////////////////////////////////////////////////////////////// void StompCommandReader::readStompHeaders( StompFrame& frame ) - throw (StompConnectorException) + throw ( StompConnectorException ) { // Read the command; bool endOfHeaders = false; @@ -173,7 +173,7 @@ void StompCommandReader::readStompHeaders( StompFrame& frame ) //////////////////////////////////////////////////////////////////////////////// int StompCommandReader::readStompHeaderLine(void) - throw (StompConnectorException) + throw ( StompConnectorException ) { int count = 0; @@ -223,10 +223,10 @@ void StompCommandReader::readStompBody( StompFrame& frame ) content_length = strtoul( length.c_str(), &stopped_string, - 10); + 10 ); } - if(content_length != 0) + if( content_length != 0 ) { // For this case its assumed that content length indicates how // much to read. We reserve space in the buffer for it to @@ -271,7 +271,7 @@ void StompCommandReader::readStompBody( StompFrame& frame ) content_length++; - if(byte != '\0') + if( byte != '\0' ) { continue; } @@ -283,7 +283,7 @@ void StompCommandReader::readStompBody( StompFrame& frame ) if( content_length != 0 ) { char* cpyBody = new char[content_length]; - memcpy(cpyBody, &buffer[0], content_length); + memcpy( cpyBody, &buffer[0], content_length ); // Set the body contents in the frame - copy the memory frame.setBody( cpyBody, content_length ); @@ -294,8 +294,8 @@ void StompCommandReader::readStompBody( StompFrame& frame ) } //////////////////////////////////////////////////////////////////////////////// -int StompCommandReader::read(unsigned char* buffer, int count) - throw(io::IOException) +int StompCommandReader::read( unsigned char* buffer, int count ) + throw( io::IOException ) { if( inputStream == NULL ) { @@ -312,9 +312,9 @@ int StompCommandReader::read(unsigned char* buffer, int count) // pause in hopes that some more data will show up. while( true ) { - head += inputStream->read(&buffer[head], count - head); + head += inputStream->read( &buffer[head], count - head ); - if(head == count) + if( head == count ) { return count; } @@ -325,7 +325,7 @@ int StompCommandReader::read(unsigned char* buffer, int count) } //////////////////////////////////////////////////////////////////////////////// -unsigned char StompCommandReader::readByte(void) throw(io::IOException) +unsigned char StompCommandReader::readByte(void) throw( io::IOException ) { if( inputStream == NULL ) { @@ -335,6 +335,6 @@ unsigned char StompCommandReader::readByte(void) throw(io::IOException) } unsigned char c = 0; - inputStream->read(&c, 1); + inputStream->read( &c, 1 ); return c; } diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompCommandReader.h b/activemq-cpp/src/main/activemq/connector/stomp/StompCommandReader.h index 385ebfe369..e4461e94af 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompCommandReader.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompCommandReader.h @@ -53,7 +53,7 @@ namespace stomp{ /** * Deafult Constructor */ - StompCommandReader( void ); + StompCommandReader( void ); /** * Constructor. @@ -61,24 +61,21 @@ namespace stomp{ */ StompCommandReader( io::InputStream* is ); - /** - * Destructor - */ - virtual ~StompCommandReader(void) {} + virtual ~StompCommandReader(void) {} /** * Reads a command from the given input stream. * @return The next command available on the stream. * @throws CommandIOException if a problem occurs during the read. */ - virtual transport::Command* readCommand( void ) + virtual transport::Command* readCommand(void) throw ( transport::CommandIOException ); /** * Sets the target input stream. * @param Target Input Stream */ - virtual void setInputStream(io::InputStream* is){ + virtual void setInputStream( io::InputStream* is ){ inputStream = is; } @@ -86,7 +83,7 @@ namespace stomp{ * Gets the target input stream. * @return Target Input Stream */ - virtual io::InputStream* getInputStream( void ){ + virtual io::InputStream* getInputStream(void){ return inputStream; } @@ -97,7 +94,7 @@ namespace stomp{ * @return The number of bytes read. * @throws IOException thrown if an error occurs. */ - virtual int read(unsigned char* buffer, int count) + virtual int read( unsigned char* buffer, int count ) throw( io::IOException ); /** @@ -130,7 +127,7 @@ namespace stomp{ * @return number of bytes read, zero if there was a problem. * @throws StompConnectorException */ - int readStompHeaderLine( void ) throw ( StompConnectorException ); + int readStompHeaderLine(void) throw ( StompConnectorException ); /** * Reads the Stomp Body from the Wire and store it in the frame. diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompCommandWriter.cpp b/activemq-cpp/src/main/activemq/connector/stomp/StompCommandWriter.cpp index aa8ec59eee..be832fe6b5 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompCommandWriter.cpp +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompCommandWriter.cpp @@ -35,7 +35,7 @@ StompCommandWriter::StompCommandWriter(void) } //////////////////////////////////////////////////////////////////////////////// -StompCommandWriter::StompCommandWriter(OutputStream* os) +StompCommandWriter::StompCommandWriter( OutputStream* os ) { outputStream = os; } @@ -103,8 +103,8 @@ void StompCommandWriter::writeCommand( const Command* command ) } //////////////////////////////////////////////////////////////////////////////// -void StompCommandWriter::write(const unsigned char* buffer, int count) - throw(IOException) +void StompCommandWriter::write( const unsigned char* buffer, int count ) + throw( IOException ) { if( outputStream == NULL ) { @@ -117,7 +117,7 @@ void StompCommandWriter::write(const unsigned char* buffer, int count) } //////////////////////////////////////////////////////////////////////////////// -void StompCommandWriter::writeByte(unsigned char v) throw(IOException) +void StompCommandWriter::writeByte( unsigned char v ) throw( IOException ) { if( outputStream == NULL ) { @@ -130,8 +130,8 @@ void StompCommandWriter::writeByte(unsigned char v) throw(IOException) } //////////////////////////////////////////////////////////////////////////////// -void StompCommandWriter::write(const char* buffer, int count) - throw(io::IOException) +void StompCommandWriter::write( const char* buffer, int count ) + throw( io::IOException ) { - write(reinterpret_cast(buffer), count); + write( reinterpret_cast( buffer ), count ); } diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompCommandWriter.h b/activemq-cpp/src/main/activemq/connector/stomp/StompCommandWriter.h index e98c827f6b..03f76789e2 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompCommandWriter.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompCommandWriter.h @@ -48,7 +48,7 @@ namespace stomp{ /** * Default Constructor */ - StompCommandWriter(void); + StompCommandWriter(void); /** * Constructor. @@ -56,15 +56,12 @@ namespace stomp{ */ StompCommandWriter( io::OutputStream* os ); - /** - * Destructor - */ - virtual ~StompCommandWriter(void) {} + virtual ~StompCommandWriter(void) {} /** * Sets the target output stream. */ - virtual void setOutputStream(io::OutputStream* os){ + virtual void setOutputStream( io::OutputStream* os ){ outputStream = os; } @@ -90,7 +87,7 @@ namespace stomp{ * @param count the number of bytes in the array to write. * @throws IOException thrown if an error occurs. */ - virtual void write(const unsigned char* buffer, int count) + virtual void write( const unsigned char* buffer, int count ) throw( io::IOException ); /** @@ -98,7 +95,7 @@ namespace stomp{ * @param v The value to be written. * @throws IOException thrown if an error occurs. */ - virtual void writeByte(unsigned char v) throw( io::IOException ); + virtual void writeByte( unsigned char v ) throw( io::IOException ); private: @@ -108,7 +105,7 @@ namespace stomp{ * @param count the number of bytes in the array to write. * @throws IOException thrown if an error occurs. */ - virtual void write(const char* buffer, int count) + virtual void write( const char* buffer, int count ) throw( io::IOException ); }; diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompConnector.cpp b/activemq-cpp/src/main/activemq/connector/stomp/StompConnector.cpp index cbfea839a2..e1102a7abb 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompConnector.cpp +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompConnector.cpp @@ -52,7 +52,7 @@ StompConnector::StompConnector( Transport* transport, const util::Properties& properties ) throw ( IllegalArgumentException ) { - if(transport == NULL) + if( transport == NULL ) { throw IllegalArgumentException( __FILE__, __LINE__, @@ -64,8 +64,8 @@ StompConnector::StompConnector( Transport* transport, this->exceptionListener = NULL; this->messageListener = NULL; this->sessionManager = NULL; - this->nextProducerId = 0; - this->nextTransactionId = 0; + this->nextProducerId = 1; + this->nextTransactionId = 1; this->properties.copy( &properties ); // Observe the transport for events. @@ -96,7 +96,7 @@ StompConnector::~StompConnector(void) //////////////////////////////////////////////////////////////////////////////// unsigned int StompConnector::getNextProducerId(void) { - synchronized(&mutex) + synchronized( &mutex ) { return nextProducerId++; } @@ -107,7 +107,7 @@ unsigned int StompConnector::getNextProducerId(void) //////////////////////////////////////////////////////////////////////////////// unsigned int StompConnector::getNextTransactionId(void) { - synchronized(&mutex) + synchronized( &mutex ) { return nextTransactionId++; } @@ -138,7 +138,7 @@ void StompConnector::addCmdListener( void StompConnector::removeCmdListener( commands::CommandConstants::CommandId commandId ) { - cmdListenerMap.erase(commandId); + cmdListenerMap.erase( commandId ); } //////////////////////////////////////////////////////////////////////////////// @@ -199,7 +199,7 @@ void StompConnector::connect(void) ConnectCommand cmd; // Encode User Name and Password and Client ID - string login = getLogin(); + string login = getUsername(); if( login.length() > 0 ){ cmd.setLogin( login ); } @@ -216,6 +216,8 @@ void StompConnector::connect(void) if( dynamic_cast< ExceptionResponse* >( response ) != NULL ) { + delete response; + throw StompConnectorException( __FILE__, __LINE__, "StompConnector::connect - Failed on Connect Request" ); @@ -226,6 +228,8 @@ void StompConnector::connect(void) if( connected == NULL ) { + delete response; + throw StompConnectorException( __FILE__, __LINE__, "StompConnector::connect - " @@ -281,7 +285,7 @@ void StompConnector::disconnect(void) //////////////////////////////////////////////////////////////////////////////// SessionInfo* StompConnector::createSession( - cms::Session::AcknowledgeMode ackMode) + cms::Session::AcknowledgeMode ackMode ) throw( ConnectorException ) { try @@ -296,9 +300,9 @@ SessionInfo* StompConnector::createSession( //////////////////////////////////////////////////////////////////////////////// ConsumerInfo* StompConnector::createConsumer( - cms::Destination* destination, + const cms::Destination* destination, SessionInfo* session, - const std::string& selector) + const std::string& selector ) throw ( ConnectorException ) { try @@ -314,11 +318,11 @@ ConsumerInfo* StompConnector::createConsumer( //////////////////////////////////////////////////////////////////////////////// ConsumerInfo* StompConnector::createDurableConsumer( - cms::Topic* topic, + const cms::Topic* topic, SessionInfo* session, const std::string& name, const std::string& selector, - bool noLocal) + bool noLocal ) throw ( ConnectorException ) { try @@ -334,8 +338,8 @@ ConsumerInfo* StompConnector::createDurableConsumer( //////////////////////////////////////////////////////////////////////////////// ProducerInfo* StompConnector::createProducer( - cms::Destination* destination, - SessionInfo* session) + const cms::Destination* destination, + SessionInfo* session ) throw ( ConnectorException ) { try @@ -355,30 +359,30 @@ ProducerInfo* StompConnector::createProducer( } //////////////////////////////////////////////////////////////////////////////// -cms::Topic* StompConnector::createTopic(const std::string& name, - SessionInfo* session) +cms::Topic* StompConnector::createTopic( const std::string& name, + SessionInfo* session ) throw ( ConnectorException ) { try { enforceConnected(); - return new StompTopic(name); + return new StompTopic( name ); } AMQ_CATCH_RETHROW( ConnectorException ) AMQ_CATCHALL_THROW( ConnectorException ); } //////////////////////////////////////////////////////////////////////////////// -cms::Queue* StompConnector::createQueue(const std::string& name, - SessionInfo* session) +cms::Queue* StompConnector::createQueue( const std::string& name, + SessionInfo* session ) throw ( ConnectorException ) { try { enforceConnected(); - return new StompQueue(name); + return new StompQueue( name ); } AMQ_CATCH_RETHROW( ConnectorException ) AMQ_CATCHALL_THROW( ConnectorException ); @@ -386,7 +390,7 @@ cms::Queue* StompConnector::createQueue(const std::string& name, //////////////////////////////////////////////////////////////////////////////// cms::TemporaryTopic* StompConnector::createTemporaryTopic( - SessionInfo* session) + SessionInfo* session ) throw ( ConnectorException ) { try @@ -401,7 +405,7 @@ cms::TemporaryTopic* StompConnector::createTemporaryTopic( //////////////////////////////////////////////////////////////////////////////// cms::TemporaryQueue* StompConnector::createTemporaryQueue( - SessionInfo* session) + SessionInfo* session ) throw ( ConnectorException ) { try @@ -416,7 +420,7 @@ cms::TemporaryQueue* StompConnector::createTemporaryQueue( //////////////////////////////////////////////////////////////////////////////// void StompConnector::send(cms::Message* message, - ProducerInfo* producerInfo) + ProducerInfo* producerInfo ) throw ( ConnectorException ) { try @@ -434,7 +438,7 @@ void StompConnector::send(cms::Message* message, "Message is not a valid stomp type."); } - if( session->getAckMode() == cms::Session::Transactional ) + if( session->getAckMode() == cms::Session::SESSION_TRANSACTED ) { StompCommand* stompCommand = dynamic_cast< StompCommand* >( message ); @@ -460,19 +464,19 @@ void StompConnector::send(cms::Message* message, } //////////////////////////////////////////////////////////////////////////////// -void StompConnector::send(std::list& messages, - ProducerInfo* producerInfo) +void StompConnector::send( std::list& messages, + ProducerInfo* producerInfo ) throw ( ConnectorException ) { try { enforceConnected(); - list::const_iterator itr = messages.begin(); + list< cms::Message* >::const_iterator itr = messages.begin(); - for(; itr != messages.end(); ++itr) + for( ; itr != messages.end(); ++itr ) { - this->send(*itr, producerInfo); + this->send( *itr, producerInfo ); } } AMQ_CATCH_RETHROW( ConnectorException ) @@ -491,7 +495,7 @@ void StompConnector::acknowledge( const SessionInfo* session, // Auto to Stomp means don't do anything, so we drop it here // for client acknowledge we have to send and ack. - if( session->getAckMode() == cms::Session::ClientAcknowledge ) + if( session->getAckMode() == cms::Session::CLIENT_ACKNOWLEDGE ) { AckCommand cmd; @@ -505,7 +509,7 @@ void StompConnector::acknowledge( const SessionInfo* session, cmd.setMessageId( message->getCMSMessageId() ); - if( session->getAckMode() == cms::Session::Transactional ) + if( session->getAckMode() == cms::Session::SESSION_TRANSACTED ) { cmd.setTransactionId( Integer::toString( @@ -521,7 +525,7 @@ void StompConnector::acknowledge( const SessionInfo* session, //////////////////////////////////////////////////////////////////////////////// TransactionInfo* StompConnector::startTransaction( - SessionInfo* session) + SessionInfo* session ) throw ( ConnectorException ) { try @@ -548,8 +552,8 @@ TransactionInfo* StompConnector::startTransaction( } //////////////////////////////////////////////////////////////////////////////// -void StompConnector::commit(TransactionInfo* transaction, - SessionInfo* session) +void StompConnector::commit( TransactionInfo* transaction, + SessionInfo* session ) throw ( ConnectorException ) { try @@ -568,8 +572,8 @@ void StompConnector::commit(TransactionInfo* transaction, } //////////////////////////////////////////////////////////////////////////////// -void StompConnector::rollback(TransactionInfo* transaction, - SessionInfo* session) +void StompConnector::rollback( TransactionInfo* transaction, + SessionInfo* session ) throw ( ConnectorException ) { try @@ -590,7 +594,7 @@ void StompConnector::rollback(TransactionInfo* transaction, //////////////////////////////////////////////////////////////////////////////// cms::Message* StompConnector::createMessage( SessionInfo* session, - TransactionInfo* transaction) + TransactionInfo* transaction ) throw ( ConnectorException ) { try @@ -614,7 +618,7 @@ cms::Message* StompConnector::createMessage( //////////////////////////////////////////////////////////////////////////////// cms::BytesMessage* StompConnector::createBytesMessage( SessionInfo* session, - TransactionInfo* transaction) + TransactionInfo* transaction ) throw ( ConnectorException ) { try @@ -638,7 +642,7 @@ cms::BytesMessage* StompConnector::createBytesMessage( //////////////////////////////////////////////////////////////////////////////// cms::TextMessage* StompConnector::createTextMessage( SessionInfo* session, - TransactionInfo* transaction) + TransactionInfo* transaction ) throw ( ConnectorException ) { try @@ -662,7 +666,7 @@ cms::TextMessage* StompConnector::createTextMessage( //////////////////////////////////////////////////////////////////////////////// cms::MapMessage* StompConnector::createMapMessage( SessionInfo* session, - TransactionInfo* transaction) + TransactionInfo* transaction ) throw ( ConnectorException ) { try @@ -676,7 +680,7 @@ cms::MapMessage* StompConnector::createMapMessage( } //////////////////////////////////////////////////////////////////////////////// -void StompConnector::unsubscribe(const std::string& name) +void StompConnector::unsubscribe( const std::string& name ) throw ( ConnectorException ) { try @@ -723,7 +727,7 @@ void StompConnector::onCommand( transport::Command* command ) { StompCommand* stompCommand = dynamic_cast< StompCommand* >(command); - if(stompCommand == NULL) + if( stompCommand == NULL ) { fire( ConnectorException( __FILE__, __LINE__, @@ -777,18 +781,21 @@ void StompConnector::onStompCommand( commands::StompCommand* command ) try { ErrorCommand* error = - dynamic_cast(command); + dynamic_cast( command ); - if(error != NULL) + if( error != NULL ) { fire( StompConnectorException( - __FILE__, __LINE__, - (string( "StompConnector::onStompCommand - " ) + - error->getErrorMessage() ).c_str() ) ); + __FILE__, __LINE__, + ( string( "StompConnector::onStompCommand - " ) + + error->getErrorMessage() ).c_str() ) ); // Shutdown close(); } + + // command is done here, delete it. + delete command; } AMQ_CATCH_RETHROW( StompConnectorException ) AMQ_CATCHALL_THROW( StompConnectorException ); diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompConnector.h b/activemq-cpp/src/main/activemq/connector/stomp/StompConnector.h index a8a2fd5633..a81c3c7ea3 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompConnector.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompConnector.h @@ -29,6 +29,7 @@ #include #include #include +#include #include namespace activemq{ @@ -57,7 +58,7 @@ namespace stomp{ // Maps Command Ids to listener that are interested typedef std::map< commands::CommandConstants::CommandId, - StompCommandListener*> CmdListenerMap; + StompCommandListener* > CmdListenerMap; private: @@ -192,20 +193,30 @@ namespace stomp{ */ virtual std::string getClientId(void) const { return properties.getProperty( - commands::CommandConstants::toString( - commands::CommandConstants::HEADER_CLIENT_ID ), "" ); + core::ActiveMQConstants::toString( + core::ActiveMQConstants::PARAM_CLIENTID ), "" ); } - virtual std::string getLogin(void) const { + /** + * Gets the Username for this connection, if this + * connection has been closed, then this method returns "" + * @return Username String + */ + virtual std::string getUsername(void) const { return properties.getProperty( - commands::CommandConstants::toString( - commands::CommandConstants::HEADER_LOGIN ), "" ); + core::ActiveMQConstants::toString( + core::ActiveMQConstants::PARAM_USERNAME ), "" ); } + /** + * Gets the Password for this connection, if this + * connection has been closed, then this method returns "" + * @return Password String + */ virtual std::string getPassword(void) const { return properties.getProperty( - commands::CommandConstants::toString( - commands::CommandConstants::HEADER_PASSWORD ), "" ); + core::ActiveMQConstants::toString( + core::ActiveMQConstants::PARAM_PASSWORD ), "" ); } /** @@ -215,7 +226,7 @@ namespace stomp{ * @throws InvalidStateException if the Transport is not set */ virtual transport::Transport& getTransport(void) const - throw (exceptions::InvalidStateException ) { + throw ( exceptions::InvalidStateException ) { if( transport == NULL ) { throw exceptions::InvalidStateException( @@ -234,7 +245,7 @@ namespace stomp{ * @throws ConnectorException */ virtual SessionInfo* createSession( - cms::Session::AcknowledgeMode ackMode) + cms::Session::AcknowledgeMode ackMode ) throw( ConnectorException ); /** @@ -245,9 +256,9 @@ namespace stomp{ * @throws ConnectorException */ virtual ConsumerInfo* createConsumer( - cms::Destination* destination, + const cms::Destination* destination, SessionInfo* session, - const std::string& selector = "") + const std::string& selector = "" ) throw ( ConnectorException ); /** @@ -262,11 +273,11 @@ namespace stomp{ * @throws ConnectorException */ virtual ConsumerInfo* createDurableConsumer( - cms::Topic* topic, + const cms::Topic* topic, SessionInfo* session, const std::string& name, const std::string& selector = "", - bool noLocal = false) + bool noLocal = false ) throw ( ConnectorException ); /** @@ -277,7 +288,7 @@ namespace stomp{ * @throws ConnectorException */ virtual ProducerInfo* createProducer( - cms::Destination* destination, + const cms::Destination* destination, SessionInfo* session) throw ( ConnectorException ); @@ -311,7 +322,7 @@ namespace stomp{ * @throws ConnectorException */ virtual cms::TemporaryTopic* createTemporaryTopic( - SessionInfo* session) + SessionInfo* session ) throw ( ConnectorException ); /** @@ -322,7 +333,7 @@ namespace stomp{ * @throws ConnectorException */ virtual cms::TemporaryQueue* createTemporaryQueue( - SessionInfo* session) + SessionInfo* session ) throw ( ConnectorException ); /** @@ -351,7 +362,7 @@ namespace stomp{ */ virtual void acknowledge( const SessionInfo* session, const cms::Message* message, - AckType ackType) + AckType ackType ) throw ( ConnectorException ); /** @@ -360,7 +371,7 @@ namespace stomp{ * @throws ConnectorException */ virtual TransactionInfo* startTransaction( - SessionInfo* session) + SessionInfo* session ) throw ( ConnectorException ); /** @@ -369,8 +380,8 @@ namespace stomp{ * @param Session Information * @throws ConnectorException */ - virtual void commit(TransactionInfo* transaction, - SessionInfo* session) + virtual void commit( TransactionInfo* transaction, + SessionInfo* session ) throw ( ConnectorException ); /** @@ -379,8 +390,8 @@ namespace stomp{ * @param Session Information * @throws ConnectorException */ - virtual void rollback(TransactionInfo* transaction, - SessionInfo* session) + virtual void rollback( TransactionInfo* transaction, + SessionInfo* session ) throw ( ConnectorException ); /** @@ -391,7 +402,7 @@ namespace stomp{ */ virtual cms::Message* createMessage( SessionInfo* session, - TransactionInfo* transaction) + TransactionInfo* transaction ) throw ( ConnectorException ); /** @@ -402,7 +413,7 @@ namespace stomp{ */ virtual cms::BytesMessage* createBytesMessage( SessionInfo* session, - TransactionInfo* transaction) + TransactionInfo* transaction ) throw ( ConnectorException ); /** @@ -413,7 +424,7 @@ namespace stomp{ */ virtual cms::TextMessage* createTextMessage( SessionInfo* session, - TransactionInfo* transaction) + TransactionInfo* transaction ) throw ( ConnectorException ); /** @@ -424,7 +435,7 @@ namespace stomp{ */ virtual cms::MapMessage* createMapMessage( SessionInfo* session, - TransactionInfo* transaction) + TransactionInfo* transaction ) throw ( ConnectorException ); /** @@ -448,7 +459,7 @@ namespace stomp{ * @param listener the observer. */ virtual void setConsumerMessageListener( - ConsumerMessageListener* listener) + ConsumerMessageListener* listener ) { this->messageListener = listener; @@ -463,7 +474,7 @@ namespace stomp{ * @param ExceptionListener the observer. */ virtual void setExceptionListener( - cms::ExceptionListener* listener) + cms::ExceptionListener* listener ) { this->exceptionListener = listener; } @@ -520,8 +531,8 @@ namespace stomp{ private: - unsigned int getNextProducerId( void ); - unsigned int getNextTransactionId( void ); + unsigned int getNextProducerId(void); + unsigned int getNextTransactionId(void); // Check for Connected State and Throw an exception if not. void enforceConnected( void ) throw ( ConnectorException ); diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompConnectorException.h b/activemq-cpp/src/main/activemq/connector/stomp/StompConnectorException.h index 155e0a991b..09a866e87b 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompConnectorException.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompConnectorException.h @@ -40,9 +40,9 @@ namespace stomp{ StompConnectorException(const char* file, const int lineNumber, const char* msg, ...) { - va_list vargs ; - va_start(vargs, msg) ; - buildMessage(msg, vargs) ; + va_list vargs; + va_start( vargs, msg ); + buildMessage( msg, vargs ); // Set the first mark for this exception. setMark( file, lineNumber ); @@ -56,6 +56,7 @@ namespace stomp{ virtual exceptions::ActiveMQException* clone() const{ return new StompConnectorException( *this ); } + virtual ~StompConnectorException() {} }; diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompConnectorFactory.cpp b/activemq-cpp/src/main/activemq/connector/stomp/StompConnectorFactory.cpp index 80b43821be..c293f71864 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompConnectorFactory.cpp +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompConnectorFactory.cpp @@ -31,10 +31,10 @@ using namespace activemq::connector::stomp; //////////////////////////////////////////////////////////////////////////////// Connector* StompConnectorFactory::createConnector( const activemq::util::Properties& properties, - activemq::transport::Transport* transport) + activemq::transport::Transport* transport ) { return dynamic_cast( - new StompConnector(transport, properties)); + new StompConnector( transport, properties ) ); } //////////////////////////////////////////////////////////////////////////////// @@ -43,7 +43,7 @@ ConnectorFactory& StompConnectorFactory::getInstance(void) // Create a static instance of the registrar and return a reference to // its internal instance of this class. static ConnectorFactoryMapRegistrar registrar( - "stomp", new StompConnectorFactory()); + "stomp", new StompConnectorFactory() ); return registrar.getFactory(); } diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompConnectorFactory.h b/activemq-cpp/src/main/activemq/connector/stomp/StompConnectorFactory.h index 0cd6d8a886..091e11d7a9 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompConnectorFactory.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompConnectorFactory.h @@ -26,9 +26,6 @@ namespace stomp{ class StompConnectorFactory : public connector::ConnectorFactory { - private: - - public: virtual ~StompConnectorFactory(void) {} @@ -39,7 +36,7 @@ namespace stomp{ */ virtual Connector* createConnector( const activemq::util::Properties& properties, - activemq::transport::Transport* transport); + activemq::transport::Transport* transport ); /** * Returns an instance of this Factory by reference diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompConsumerInfo.h b/activemq-cpp/src/main/activemq/connector/stomp/StompConsumerInfo.h index b043a4cf14..20a2306aa5 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompConsumerInfo.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompConsumerInfo.h @@ -45,7 +45,8 @@ namespace stomp{ consumerId = 0; destination = NULL; } - virtual ~StompConsumerInfo(void) { delete destination; } + + virtual ~StompConsumerInfo(void) { delete destination; } /** * Gets this message consumer's message selector expression. diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompDestination.h b/activemq-cpp/src/main/activemq/connector/stomp/StompDestination.h index b899cf23b4..ca9fb1dcdf 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompDestination.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompDestination.h @@ -20,7 +20,7 @@ #include -#include +#include namespace activemq{ namespace connector{ @@ -32,26 +32,25 @@ namespace stomp{ * one of Topic, Queue, TemporaryTopic, or TemporaryQueue. */ template - class StompDestination : public T + class StompDestination : public core::ActiveMQDestination { - private: - - // Destination type - cms::Destination::DestinationType destType; - - // Name of the Destination - std::string name; - public: - StompDestination(void) {} + /** + * Copy Consturctor + * @param CMS Dest to Copy, must be a compatible type + */ + StompDestination( const cms::Destination* source ) : + core::ActiveMQDestination( source ) {} + /** + * Custom Constructor + * @param string destination name plus any params + * @param type of destination this represents. + */ StompDestination( const std::string& name, - cms::Destination::DestinationType type ) - { - this->name = name; - this->destType = type; - } + cms::Destination::DestinationType type ) : + core::ActiveMQDestination( name, type ){} virtual ~StompDestination(void) {} @@ -61,15 +60,7 @@ namespace stomp{ * @return name */ virtual std::string toProviderString(void) const { - return getPrefix() + name; - } - - /** - * Retrieve the Destination Type for this Destination - * @return The Destination Type - */ - virtual cms::Destination::DestinationType getDestinationType(void) const { - return destType; + return getPrefix() + core::ActiveMQDestination::getName(); } /** @@ -78,16 +69,7 @@ namespace stomp{ * @return string name */ virtual std::string toString(void) const { - return name; - } - - /** - * Copies the contents of the given Destinastion object to this one. - * @param source The source Destination object. - */ - virtual void copy( const cms::Destination& source ) { - this->destType = source.getDestinationType(); - this->name = source.toString(); + return core::ActiveMQDestination::getName(); } protected: diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompQueue.h b/activemq-cpp/src/main/activemq/connector/stomp/StompQueue.h index ac235856f6..ad4d011d52 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompQueue.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompQueue.h @@ -26,17 +26,27 @@ namespace activemq{ namespace connector{ namespace stomp{ - class StompQueue : public StompDestination + class StompQueue : public StompDestination< cms::Queue > { public: - StompQueue(void) : StompDestination< cms::Queue >() {} + /** + * Copy Consturctor + * @param CMS Dest to Copy, must be a compatible type + */ + StompQueue( const cms::Destination* source ) : + StompDestination< cms::Queue >( source ) {} + /** + * Custom Constructor + * @param string destination name plus any params + * @param type of destination this represents. + */ StompQueue(const std::string& name) : StompDestination< cms::Queue >( name, cms::Destination::QUEUE ) {} - virtual ~StompQueue(void) {} + virtual ~StompQueue(void) {} /** * Gets the name of this queue. diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompSessionInfo.h b/activemq-cpp/src/main/activemq/connector/stomp/StompSessionInfo.h index 3449255acb..f75398f8aa 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompSessionInfo.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompSessionInfo.h @@ -44,18 +44,12 @@ namespace stomp{ public: - /** - * Constructor - */ StompSessionInfo(void) { sessionId = 0; - ackMode = cms::Session::AutoAcknowledge; + ackMode = cms::Session::AUTO_ACKNOWLEDGE; } - /** - * Destructor - */ virtual ~StompSessionInfo(void) {} /** diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompSessionManager.cpp b/activemq-cpp/src/main/activemq/connector/stomp/StompSessionManager.cpp index 7c424584dc..faa6c486a6 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompSessionManager.cpp +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompSessionManager.cpp @@ -18,16 +18,19 @@ #include "StompSessionManager.h" #include +#include #include #include #include #include #include #include +#include using namespace std; using namespace activemq; using namespace activemq::core; +using namespace activemq::util; using namespace activemq::exceptions; using namespace activemq::transport; using namespace activemq::connector; @@ -65,7 +68,7 @@ StompSessionManager::~StompSessionManager(void) //////////////////////////////////////////////////////////////////////////////// unsigned int StompSessionManager::getNextSessionId(void) { - synchronized(&mutex) + synchronized( &mutex ) { return nextSessionId++; } @@ -76,7 +79,7 @@ unsigned int StompSessionManager::getNextSessionId(void) //////////////////////////////////////////////////////////////////////////////// unsigned int StompSessionManager::getNextConsumerId(void) { - synchronized(&mutex) + synchronized( &mutex ) { return nextConsumerId++; } @@ -86,7 +89,7 @@ unsigned int StompSessionManager::getNextConsumerId(void) //////////////////////////////////////////////////////////////////////////////// connector::SessionInfo* StompSessionManager::createSession( - cms::Session::AcknowledgeMode ackMode) + cms::Session::AcknowledgeMode ackMode ) throw ( exceptions::ActiveMQException ) { try @@ -94,7 +97,7 @@ connector::SessionInfo* StompSessionManager::createSession( SessionInfo* session = new StompSessionInfo(); // Init data - session->setAckMode(ackMode); + session->setAckMode( ackMode ); session->setConnectionId( connectionId ); session->setSessionId( getNextSessionId() ); @@ -114,10 +117,10 @@ void StompSessionManager::removeSession( //////////////////////////////////////////////////////////////////////////////// connector::ConsumerInfo* StompSessionManager::createConsumer( - cms::Destination* destination, + const cms::Destination* destination, SessionInfo* session, - const std::string& selector) - throw( ConnectorException ) + const std::string& selector ) + throw( StompConnectorException ) { try { @@ -127,46 +130,54 @@ connector::ConsumerInfo* StompSessionManager::createConsumer( return createDurableConsumer( destination, session, "", selector, false ); } - AMQ_CATCH_RETHROW( ConnectorException ) - AMQ_CATCHALL_THROW( ConnectorException ) + AMQ_CATCH_RETHROW( StompConnectorException ) + AMQ_CATCHALL_THROW( StompConnectorException ) } //////////////////////////////////////////////////////////////////////////////// connector::ConsumerInfo* StompSessionManager::createDurableConsumer( - cms::Destination* destination, + const cms::Destination* destination, SessionInfo* session, const std::string& name, const std::string& selector, bool noLocal ) - throw ( ConnectorException ) + throw ( StompConnectorException ) { try { - synchronized(&mutex) + synchronized( &mutex ) { // Find the right mapping to consumers ConsumerMap& consumerMap = destinationMap[ destination->toString() ]; - + // We only need to send a sub request if there are no active // consumers on this destination. if( consumerMap.empty() ) { // Send the request to the Broker SubscribeCommand cmd; - - if( session->getAckMode() == cms::Session::ClientAcknowledge ) + + if( session->getAckMode() == cms::Session::CLIENT_ACKNOWLEDGE ) { cmd.setAckMode( CommandConstants::ACK_CLIENT ); } cmd.setDestination( destination->toProviderString() ); - cmd.setNoLocal( noLocal ); + + if( noLocal == true ) + { + cmd.setNoLocal( noLocal ); + } if( name != "" ) { cmd.setSubscriptionName( name ); } + // Grab any options from the destination and set them + // for this subscription. + setSubscribeOptions( destination, cmd ); + // The Selector is set on the first subscribe on this dest, // and if another consumer is created on this destination // that specifies a selector it will be ignored. While @@ -198,18 +209,18 @@ connector::ConsumerInfo* StompSessionManager::createDurableConsumer( return NULL; } - AMQ_CATCH_RETHROW( ConnectorException ) - AMQ_CATCHALL_THROW( ConnectorException ) + AMQ_CATCH_RETHROW( StompConnectorException ) + AMQ_CATCHALL_THROW( StompConnectorException ) } //////////////////////////////////////////////////////////////////////////////// void StompSessionManager::removeConsumer( - connector::ConsumerInfo* consumer) - throw( ConnectorException ) + connector::ConsumerInfo* consumer ) + throw( StompConnectorException ) { try { - synchronized(&mutex) + synchronized( &mutex ) { DestinationMap::iterator itr = destinationMap.find( consumer->getDestination().toString() ); @@ -238,8 +249,8 @@ void StompSessionManager::removeConsumer( } } } - AMQ_CATCH_RETHROW( ConnectorException ) - AMQ_CATCHALL_THROW( ConnectorException ) + AMQ_CATCH_RETHROW( StompConnectorException ) + AMQ_CATCHALL_THROW( StompConnectorException ) } //////////////////////////////////////////////////////////////////////////////// @@ -265,10 +276,10 @@ void StompSessionManager::onStompCommand( commands::StompCommand* command ) "No Message Listener Registered." ); } - synchronized(&mutex) + synchronized( &mutex ) { DestinationMap::iterator itr = - destinationMap.find( message->getCMSDestination().toString() ); + destinationMap.find( message->getCMSDestination()->toString() ); if( itr == destinationMap.end() ) { @@ -280,7 +291,7 @@ void StompSessionManager::onStompCommand( commands::StompCommand* command ) // If we only have 1 consumer, we don't need to clone the original // message. - if(itr->second.size() == 1) + if( itr->second.size() == 1 ) { ConsumerInfo* consumerInfo = itr->second.begin()->second; @@ -301,7 +312,7 @@ void StompSessionManager::onStompCommand( commands::StompCommand* command ) // message. ConsumerMap::iterator c_itr = itr->second.begin(); - for(; c_itr != itr->second.end(); ++c_itr ) + for( ; c_itr != itr->second.end(); ++c_itr ) { ConsumerInfo* consumerInfo = c_itr->second; @@ -324,3 +335,110 @@ void StompSessionManager::onStompCommand( commands::StompCommand* command ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, StompConnectorException ) AMQ_CATCHALL_THROW( StompConnectorException ) } + +void StompSessionManager::setSubscribeOptions( const cms::Destination* dest, + SubscribeCommand& command ) + throw ( StompConnectorException ) +{ + try + { + // Get the properties of this destination + const Properties& destProperties = dest->getProperties(); + + if( destProperties.isEmpty() ) + { + // Nothing to do, so save some work and quit now. + return; + } + + std::string noLocalStr = + ActiveMQConstants::toString( + ActiveMQConstants::CONSUMER_NOLOCAL ); + + if( destProperties.getProperty( noLocalStr, "false" ) == "true" ) + { + command.setNoLocal( + Boolean::parseBoolean( + destProperties.getProperty( noLocalStr ) ) ); + } + + std::string selectorStr = + ActiveMQConstants::toString( + ActiveMQConstants::CONSUMER_SELECTOR ); + + if( destProperties.hasProperty( selectorStr ) ) + { + command.setMessageSelector( + destProperties.getProperty( selectorStr ) ); + } + + std::string priorityStr = + ActiveMQConstants::toString( + ActiveMQConstants::CONSUMER_PRIORITY ); + + if( destProperties.hasProperty( priorityStr ) ) + { + command.setPriority( + Integer::parseInt( + destProperties.getProperty( priorityStr ) ) ); + } + + std::string dispatchAsyncStr = + ActiveMQConstants::toString( + ActiveMQConstants::CONSUMER_DISPATCHASYNC ); + + if( destProperties.hasProperty( dispatchAsyncStr ) ) + { + command.setDispatchAsync( + Boolean::parseBoolean( + destProperties.getProperty( dispatchAsyncStr ) ) ); + } + + std::string exclusiveStr = + ActiveMQConstants::toString( + ActiveMQConstants::CONSUMER_EXCLUSIVE ); + + if( destProperties.hasProperty( exclusiveStr ) ) + { + command.setExclusive( + Boolean::parseBoolean( + destProperties.getProperty( exclusiveStr ) ) ); + } + + std::string maxPendingMsgLimitStr = + ActiveMQConstants::toString( + ActiveMQConstants::CUNSUMER_MAXPENDINGMSGLIMIT ); + + if( destProperties.hasProperty( maxPendingMsgLimitStr ) ) + { + command.setMaxPendingMsgLimit( + Integer::parseInt( + destProperties.getProperty( maxPendingMsgLimitStr ) ) ); + } + + std::string prefetchSizeStr = + ActiveMQConstants::toString( + ActiveMQConstants::CONSUMER_PREFECTCHSIZE ); + + if( destProperties.hasProperty( prefetchSizeStr ) ) + { + command.setPrefetchSize( + Integer::parseInt( + destProperties.getProperty( prefetchSizeStr ) ) ); + } + + std::string retroactiveStr = + ActiveMQConstants::toString( + ActiveMQConstants::CONSUMER_RETROACTIVE ); + + if( destProperties.hasProperty( retroactiveStr ) ) + { + command.setRetroactive( + Boolean::parseBoolean( + destProperties.getProperty( retroactiveStr ) ) ); + } + } + AMQ_CATCH_RETHROW( StompConnectorException ) + AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, StompConnectorException ) + AMQ_CATCHALL_THROW( StompConnectorException ) +} diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompSessionManager.h b/activemq-cpp/src/main/activemq/connector/stomp/StompSessionManager.h index 725be89ebf..c015183cea 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompSessionManager.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompSessionManager.h @@ -25,6 +25,7 @@ #include #include #include +#include namespace activemq{ namespace connector{ @@ -44,8 +45,8 @@ namespace stomp{ private: // Map Types - typedef std::map ConsumerMap; - typedef std::map DestinationMap; + typedef std::map< unsigned int, ConsumerInfo* > ConsumerMap; + typedef std::map< std::string, ConsumerMap > DestinationMap; private: @@ -85,7 +86,7 @@ namespace stomp{ * @return new SessionInfo object */ virtual connector::SessionInfo* createSession( - cms::Session::AcknowledgeMode ackMode) + cms::Session::AcknowledgeMode ackMode ) throw ( exceptions::ActiveMQException ); /** @@ -108,10 +109,10 @@ namespace stomp{ * @return new ConsumerInfo object. */ virtual connector::ConsumerInfo* createConsumer( - cms::Destination* destination, + const cms::Destination* destination, SessionInfo* session, - const std::string& selector) - throw( ConnectorException ); + const std::string& selector ) + throw( StompConnectorException ); /** * Creates a new durable consumer to the specified session, will @@ -126,12 +127,12 @@ namespace stomp{ * @return new ConsumerInfo object. */ virtual connector::ConsumerInfo* createDurableConsumer( - cms::Destination* destination, + const cms::Destination* destination, SessionInfo* session, const std::string& name, const std::string& selector, bool noLocal ) - throw ( ConnectorException ); + throw ( StompConnectorException ); /** * Removes the Consumer from the session, will unsubscrive if the @@ -142,7 +143,7 @@ namespace stomp{ * @throws ConnectorException */ virtual void removeConsumer( connector::ConsumerInfo* consumer ) - throw( ConnectorException ); + throw( StompConnectorException ); /** * Sets the listener of consumer messages. @@ -162,7 +163,19 @@ namespace stomp{ * @throw ConnterException */ virtual void onStompCommand( commands::StompCommand* command ) - throw ( StompConnectorException ); + throw ( StompConnectorException ); + + protected: + + /** + * Sets Subscribe Command options from the properties of a + * destination object. + * @param The destination that we are subscribing to. + * @param The pending Subscribe command + */ + virtual void setSubscribeOptions( const cms::Destination* dest, + commands::SubscribeCommand& command ) + throw ( StompConnectorException ); protected: diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompTopic.h b/activemq-cpp/src/main/activemq/connector/stomp/StompTopic.h index d9a0f64cd9..488183ea20 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompTopic.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompTopic.h @@ -30,8 +30,18 @@ namespace stomp{ { public: - StompTopic(void) : StompDestination() {} + /** + * Copy Consturctor + * @param CMS Dest to Copy, must be a compatible type + */ + StompTopic( const cms::Destination* source ) : + StompDestination< cms::Topic >( source ) {} + /** + * Custom Constructor + * @param string destination name plus any params + * @param type of destination this represents. + */ StompTopic(const std::string& name) : StompDestination< cms::Topic >( name, cms::Destination::TOPIC ) {} diff --git a/activemq-cpp/src/main/activemq/connector/stomp/StompTransactionInfo.h b/activemq-cpp/src/main/activemq/connector/stomp/StompTransactionInfo.h index 9c05b03e55..4f44b674cb 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/StompTransactionInfo.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/StompTransactionInfo.h @@ -37,16 +37,13 @@ namespace stomp{ public: /** - * TransactionInfo Constructor + * Default Constructor */ StompTransactionInfo(void) { transactionId = 0; session = NULL; } - /** - * Destructor - */ virtual ~StompTransactionInfo(void) {} /** diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/AbstractCommand.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/AbstractCommand.h index 855bf98040..8d7cd79177 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/AbstractCommand.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/AbstractCommand.h @@ -113,13 +113,24 @@ namespace commands{ AbstractCommand(void){ frame = new StompFrame; } - AbstractCommand(StompFrame* frame){ + AbstractCommand( StompFrame* frame ){ this->frame = frame; } virtual ~AbstractCommand(void){ destroyFrame(); } + /** + * Gets the properties map for this command. + * @return Reference to a Properties object + */ + virtual util::Properties& getProperties(void){ + return getFrame().getProperties(); + } + virtual const util::Properties& getProperties(void) const{ + return getFrame().getProperties(); + } + /** * Sets the Command Id of this Message * @param Command Id diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/AckCommand.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/AckCommand.h index 370caa0b65..fbf6269770 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/AckCommand.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/AckCommand.h @@ -44,7 +44,7 @@ namespace commands{ initialize( getFrame() ); } AckCommand( StompFrame* frame ) : - AbstractCommand(frame) { + AbstractCommand( frame ) { validate( getFrame() ); } virtual ~AckCommand(void) {} diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/BeginCommand.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/BeginCommand.h index 3deb4465eb..06db5dca64 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/BeginCommand.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/BeginCommand.h @@ -45,7 +45,7 @@ namespace commands{ initialize( getFrame() ); } BeginCommand( StompFrame* frame ) : - AbstractCommand(frame) { + AbstractCommand( frame ) { validate( getFrame() ); } virtual ~BeginCommand(void) {} diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/BytesMessageCommand.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/BytesMessageCommand.h index 4a24c9c9da..3058e1ae98 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/BytesMessageCommand.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/BytesMessageCommand.h @@ -41,7 +41,7 @@ namespace commands{ initialize( getFrame() ); } BytesMessageCommand( StompFrame* frame ) : - StompMessage< cms::BytesMessage >(frame) { + StompMessage< cms::BytesMessage >( frame ) { validate( getFrame() ); } virtual ~BytesMessageCommand(void) {} diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/CommandConstants.cpp b/activemq-cpp/src/main/activemq/connector/stomp/commands/CommandConstants.cpp index baa45bee5c..d5b27d62cd 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/CommandConstants.cpp +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/CommandConstants.cpp @@ -62,7 +62,8 @@ CommandConstants::StaticInitializer::StaticInitializer(){ stompHeaders[HEADER_RESPONSEID] = "response-id"; stompHeaders[HEADER_EXPIRES] = "expires"; stompHeaders[HEADER_PERSISTANT] = "persistent"; - stompHeaders[HEADER_PRIORITY] = "priority"; + stompHeaders[HEADER_JMSPRIORITY] = "priority"; + stompHeaders[HEADER_CONSUMERPRIORITY] = "activemq.priority"; stompHeaders[HEADER_REPLYTO] = "reply-to"; stompHeaders[HEADER_TYPE] = "type"; stompHeaders[HEADER_AMQMSGTYPE] = "amq-msg-type"; @@ -74,7 +75,7 @@ CommandConstants::StaticInitializer::StaticInitializer(){ stompHeaders[HEADER_MAXPENDINGMSGLIMIT] = "activemq.maximumPendingMessageLimit"; stompHeaders[HEADER_NOLOCAL] = "activemq.noLocal"; stompHeaders[HEADER_PREFETCHSIZE] = "activemq.prefetchSize"; - stompHeaders[HEADER_PRIORITY] = "activemq.priority"; + stompHeaders[HEADER_CONSUMERPRIORITY] = "activemq.priority"; stompHeaders[HEADER_RETROACTIVE] = "activemq.retroactive"; stompHeaders[HEADER_SUBSCRIPTIONNAME] = "activemq.subscriptionName"; stompHeaders[HEADER_TIMESTAMP] = "timestamp"; diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/CommandConstants.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/CommandConstants.h index 5a6ee768c1..a96cca4bf0 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/CommandConstants.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/CommandConstants.h @@ -76,7 +76,8 @@ namespace commands{ HEADER_MAXPENDINGMSGLIMIT, HEADER_NOLOCAL, HEADER_PREFETCHSIZE, - HEADER_PRIORITY, + HEADER_JMSPRIORITY, + HEADER_CONSUMERPRIORITY, HEADER_RETROACTIVE, HEADER_SUBSCRIPTIONNAME, HEADER_TIMESTAMP, diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/CommitCommand.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/CommitCommand.h index 5f1bc64885..df184fa37a 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/CommitCommand.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/CommitCommand.h @@ -40,7 +40,7 @@ namespace commands{ initialize( getFrame() ); } CommitCommand( StompFrame* frame ) : - AbstractCommand(frame) { + AbstractCommand( frame ) { validate( getFrame() ); } virtual ~CommitCommand(void) {} diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/ConnectCommand.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/ConnectCommand.h index a0ef70b905..c8afa2ffc5 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/ConnectCommand.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/ConnectCommand.h @@ -39,7 +39,7 @@ namespace commands{ initialize( getFrame() ); } ConnectCommand( StompFrame* frame ) : - AbstractCommand(frame) { + AbstractCommand( frame ) { validate( getFrame() ); } virtual ~ConnectCommand(void) {}; diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/DisconnectCommand.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/DisconnectCommand.h index 3423dc2052..f9fe4ba2c4 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/DisconnectCommand.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/DisconnectCommand.h @@ -40,7 +40,7 @@ namespace commands{ initialize( getFrame() ); } DisconnectCommand( StompFrame* frame ) : - AbstractCommand(frame) { + AbstractCommand( frame ) { validate( getFrame() ); } virtual ~DisconnectCommand(void){}; diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/ErrorCommand.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/ErrorCommand.h index f17671a9e8..0b3cc4c1b5 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/ErrorCommand.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/ErrorCommand.h @@ -40,7 +40,7 @@ namespace commands{ initialize( getFrame() ); } ErrorCommand( StompFrame* frame ) : - AbstractCommand(frame) { + AbstractCommand( frame ) { validate( getFrame() ); } virtual ~ErrorCommand(void) {}; diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/ReceiptCommand.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/ReceiptCommand.h index 053191010f..f3a1b47fbd 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/ReceiptCommand.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/ReceiptCommand.h @@ -40,7 +40,7 @@ namespace commands{ initialize( getFrame() ); } ReceiptCommand( StompFrame* frame ) : - AbstractCommand(frame) { + AbstractCommand( frame ) { validate( getFrame() ); } virtual ~ReceiptCommand(void) {} @@ -60,7 +60,7 @@ namespace commands{ virtual void setReceiptId( const std::string& id ){ setPropertyValue( CommandConstants::toString( - CommandConstants::HEADER_RECEIPTID), + CommandConstants::HEADER_RECEIPTID ), id ); } diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/StompCommand.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/StompCommand.h index b56a6b1a13..c31a0880ca 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/StompCommand.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/StompCommand.h @@ -103,6 +103,13 @@ namespace commands{ * @return Stomp CommandId enum */ virtual CommandConstants::CommandId getStompCommandId(void) const = 0; + + /** + * Retrieves the Properties that are part of this command + * @return const reference to a properties object + */ + virtual util::Properties& getProperties(void) = 0; + virtual const util::Properties& getProperties(void) const = 0; }; diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/StompMessage.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/StompMessage.h index 9d38fb9d78..f0d3761796 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/StompMessage.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/StompMessage.h @@ -62,7 +62,7 @@ namespace commands{ StompMessage(void) : AbstractCommand< transport::Command >(), - ackHandler( NULL ) { dest = new StompTopic(); } + ackHandler( NULL ) { dest = NULL; } StompMessage( StompFrame* frame ) : AbstractCommand< transport::Command >( frame ), ackHandler( NULL ) @@ -112,55 +112,57 @@ namespace commands{ * of this consumed message. */ virtual void acknowledge(void) const throw( cms::CMSException ) { - if(ackHandler != NULL) ackHandler->acknowledgeMessage(this); + if(ackHandler != NULL) ackHandler->acknowledgeMessage( this ); } /** * Sets the DeliveryMode for this message * @return DeliveryMode enumerated value. */ - virtual cms::Message::DeliveryMode getCMSDeliveryMode(void) const { + virtual int getCMSDeliveryMode(void) const { if(!getFrame().getProperties().hasProperty( CommandConstants::toString( CommandConstants::HEADER_PERSISTANT ) ) ) { - return cms::Message::PERSISTANT; + return cms::DeliveryMode::PERSISTANT; } - return (cms::Message::DeliveryMode)( - util::Integer::parseInt( getPropertyValue( - CommandConstants::toString( - CommandConstants::HEADER_PERSISTANT ) ) ) ); + return util::Integer::parseInt( getPropertyValue( + CommandConstants::toString( + CommandConstants::HEADER_PERSISTANT ) ) ); } /** * Sets the DeliveryMode for this message * @param DeliveryMode enumerated value. */ - virtual void setCMSDeliveryMode(cms::Message::DeliveryMode mode) { + virtual void setCMSDeliveryMode( int mode ) { setPropertyValue( CommandConstants::toString( CommandConstants::HEADER_PERSISTANT ) , - util::Integer::toString((int)mode) ); + util::Integer::toString( mode ) ); } /** * Gets the Destination for this Message - * @return Destination object + * @return Destination object can be NULL */ - virtual const cms::Destination& getCMSDestination(void) const{ - return *dest; + virtual const cms::Destination* getCMSDestination(void) const{ + return dest; } /** * Sets the Destination for this message * @param Destination Object */ - virtual void setCMSDestination(const cms::Destination& destination) { - dest->copy( destination ); - setPropertyValue( - CommandConstants::toString( - CommandConstants::HEADER_DESTINATION ), - dest->toProviderString() ); + virtual void setCMSDestination( const cms::Destination* destination ) { + if( destination != NULL ) + { + dest = destination->clone(); + setPropertyValue( + CommandConstants::toString( + CommandConstants::HEADER_DESTINATION ), + dest->toProviderString() ); + } } /** @@ -177,7 +179,7 @@ namespace commands{ * Sets the Expiration Time for this message * @param time value */ - virtual void setCMSExpiration(long expireTime) { + virtual void setCMSExpiration( long expireTime ) { setPropertyValue( CommandConstants::toString( CommandConstants::HEADER_EXPIRES) , @@ -198,7 +200,7 @@ namespace commands{ * Sets the CMS Message Id for this message * @param time value */ - virtual void setCMSMessageId(const std::string& id) { + virtual void setCMSMessageId( const std::string& id ) { setPropertyValue( CommandConstants::toString( CommandConstants::HEADER_MESSAGEID ), @@ -212,17 +214,17 @@ namespace commands{ virtual int getCMSPriority(void) const { return util::Integer::parseInt( getPropertyValue( CommandConstants::toString( - CommandConstants::HEADER_PRIORITY ), "0" ) ); + CommandConstants::HEADER_JMSPRIORITY ), "0" ) ); } /** * Sets the Priority Value for this message * @param priority value */ - virtual void setCMSPriority(int priority) { + virtual void setCMSPriority( int priority ) { setPropertyValue( CommandConstants::toString( - CommandConstants::HEADER_PRIORITY), + CommandConstants::HEADER_JMSPRIORITY), util::Integer::toString( priority ) ); } @@ -241,7 +243,7 @@ namespace commands{ * Sets the Redelivered Flag for this message * @param redelivered value */ - virtual void setCMSRedelivered(bool redelivered) { + virtual void setCMSRedelivered( bool redelivered ) { setPropertyValue( CommandConstants::toString( CommandConstants::HEADER_REDELIVERED ), @@ -262,7 +264,7 @@ namespace commands{ * Sets the CMS Reply To Address for this message * @param Reply To value */ - virtual void setCMSReplyTo(const std::string& id) { + virtual void setCMSReplyTo( const std::string& id ) { setPropertyValue( CommandConstants::toString( CommandConstants::HEADER_REPLYTO ), @@ -283,7 +285,7 @@ namespace commands{ * Sets the Time Stamp for this message * @param time stamp value */ - virtual void setCMSTimeStamp(long timeStamp) { + virtual void setCMSTimeStamp( long timeStamp ) { setPropertyValue( CommandConstants::toString( CommandConstants::HEADER_TIMESTAMP ), @@ -304,7 +306,7 @@ namespace commands{ * Sets the CMS Message Type for this message * @param type value */ - virtual void setCMSMessageType(const std::string& type) { + virtual void setCMSMessageType( const std::string& type ) { setPropertyValue( CommandConstants::toString( CommandConstants::HEADER_TYPE ), @@ -318,7 +320,7 @@ namespace commands{ * when the Acknowledge method is called. * @param ActiveMQAckHandler */ - virtual void setAckHandler(core::ActiveMQAckHandler* handler) { + virtual void setAckHandler( core::ActiveMQAckHandler* handler ) { this->ackHandler = handler; } @@ -338,7 +340,7 @@ namespace commands{ * redelivered * @param redelivery count */ - virtual void setRedeliveryCount(int count) { + virtual void setRedeliveryCount( int count ) { setPropertyValue( CommandConstants::toString( CommandConstants::HEADER_REDELIVERYCOUNT ), diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/SubscribeCommand.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/SubscribeCommand.h index d23e9a0d21..918d2860a7 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/SubscribeCommand.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/SubscribeCommand.h @@ -53,7 +53,7 @@ namespace commands{ virtual const char* getDestination(void) const{ return getPropertyValue( CommandConstants::toString( - CommandConstants::HEADER_DESTINATION) ); + CommandConstants::HEADER_DESTINATION ) ); } /** @@ -63,7 +63,7 @@ namespace commands{ virtual void setDestination( const std::string& dest ){ setPropertyValue( CommandConstants::toString( - CommandConstants::HEADER_DESTINATION), + CommandConstants::HEADER_DESTINATION ), dest ); } @@ -74,7 +74,7 @@ namespace commands{ virtual void setAckMode( const CommandConstants::AckMode mode ){ setPropertyValue( CommandConstants::toString( - CommandConstants::HEADER_ACK), + CommandConstants::HEADER_ACK ), CommandConstants::toString( mode ) ); } @@ -86,7 +86,7 @@ namespace commands{ return CommandConstants::toAckMode( getPropertyValue( CommandConstants::toString( - CommandConstants::HEADER_ACK) ) ); + CommandConstants::HEADER_ACK ) ) ); } /** @@ -97,7 +97,7 @@ namespace commands{ virtual void setMessageSelector( const std::string& selector ) { setPropertyValue( CommandConstants::toString( - CommandConstants::HEADER_SELECTOR), + CommandConstants::HEADER_SELECTOR ), selector ); } @@ -109,7 +109,7 @@ namespace commands{ virtual const char* getMessageSelector(void) const{ return getPropertyValue( CommandConstants::toString( - CommandConstants::HEADER_SELECTOR) ); + CommandConstants::HEADER_SELECTOR ) ); } /** @@ -120,7 +120,7 @@ namespace commands{ virtual void setSubscriptionName( const std::string& name ) { setPropertyValue( CommandConstants::toString( - CommandConstants::HEADER_SUBSCRIPTIONNAME), + CommandConstants::HEADER_SUBSCRIPTIONNAME ), name ); } @@ -132,11 +132,11 @@ namespace commands{ virtual const char* getSubscriptionName(void) const{ return getPropertyValue( CommandConstants::toString( - CommandConstants::HEADER_SUBSCRIPTIONNAME) ); + CommandConstants::HEADER_SUBSCRIPTIONNAME ) ); } /** - * Gets hether or not locally sent messages should be ignored for + * Gets whether or not locally sent messages should be ignored for * subscriptions. Set to true to filter out locally sent messages * @return NoLocal value */ @@ -148,7 +148,7 @@ namespace commands{ } /** - * Gets hether or not locally sent messages should be ignored for + * Sets whether or not locally sent messages should be ignored for * subscriptions. Set to true to filter out locally sent messages * @param NoLocal value */ @@ -159,6 +159,162 @@ namespace commands{ util::Boolean::toString( noLocal ) ); } + /** + * Sets whether or not the broker is to dispatch messages in an + * asynchronous manner. Set to true if you want Async. + * @return true if in dispatch async mode + */ + virtual bool getDispatchAsync(void) const { + return util::Boolean::parseBoolean( getPropertyValue( + CommandConstants::toString( + CommandConstants::HEADER_DISPATCH_ASYNC ), + "false" ) ); + } + + /** + * Sets whether or not the broker is to dispatch messages in an + * asynchronous manner. Set to true if you want Async. + * @param true for async dispatch mode + */ + virtual void setDispatchAsync( bool dispatchAsync ) { + setPropertyValue( + CommandConstants::toString( + CommandConstants::HEADER_DISPATCH_ASYNC ), + util::Boolean::toString( dispatchAsync ) ); + } + + /** + * Gets whether or not this consumer is an exclusive consumer for + * this destination. + * @return true for exclusive mode + */ + virtual bool getExclusive(void) const { + return util::Boolean::parseBoolean( getPropertyValue( + CommandConstants::toString( + CommandConstants::HEADER_EXCLUSIVE ), + "false" ) ); + } + + /** + * Sets whether or not this consumer is an exclusive consumer for + * this destination. + * @param true if in exclusive mode + */ + virtual void setExclusive( bool exclusive ) { + setPropertyValue( + CommandConstants::toString( + CommandConstants::HEADER_EXCLUSIVE ), + util::Boolean::toString( exclusive ) ); + } + + /** + * Get the max number of pending messages on a destination + * For Slow Consumer Handlingon non-durable topics by dropping old + * messages - we can set a maximum pending limit which once a slow + * consumer backs up to this high water mark we begin to discard + * old messages + * @return Max value + */ + virtual int getMaxPendingMsgLimit(void) const { + return util::Integer::parseInt( getPropertyValue( + CommandConstants::toString( + CommandConstants::HEADER_MAXPENDINGMSGLIMIT ), + "0" ) ); + } + + /** + * Set the max number of pending messages on a destination + * For Slow Consumer Handlingon non-durable topics by dropping old + * messages - we can set a maximum pending limit which once a slow + * consumer backs up to this high water mark we begin to discard + * old messages + * @param Max value + */ + virtual void setMaxPendingMsgLimit( int limit ) { + setPropertyValue( + CommandConstants::toString( + CommandConstants::HEADER_MAXPENDINGMSGLIMIT ), + util::Integer::toString( limit ) ); + } + + /** + * Get the maximum number of pending messages that will be + * dispatched to the client. Once this maximum is reached no more + * messages are dispatched until the client acknowledges a message. + * Set to 1 for very fair distribution of messages across consumers + * where processing messages can be slow + * @return prefetch size value + */ + virtual int getPrefetchSize(void) const { + return util::Integer::parseInt( getPropertyValue( + CommandConstants::toString( + CommandConstants::HEADER_PREFETCHSIZE ), + "1000" ) ); + } + + /** + * Set the maximum number of pending messages that will be + * dispatched to the client. Once this maximum is reached no more + * messages are dispatched until the client acknowledges a message. + * Set to 1 for very fair distribution of messages across consumers + * where processing messages can be slow + * @param prefetch size value + */ + virtual void setPrefetchSize( int size ) { + setPropertyValue( + CommandConstants::toString( + CommandConstants::HEADER_PREFETCHSIZE ), + util::Integer::toString( size ) ); + } + + /** + * Gets the priority of the consumer so that dispatching can be + * weighted in priority order + * @return priority level + */ + virtual int getPriority(void) const { + return util::Integer::parseInt( getPropertyValue( + CommandConstants::toString( + CommandConstants::HEADER_CONSUMERPRIORITY ), + "0" ) ); + } + + /** + * Sets the priority of the consumer so that dispatching can be + * weighted in priority order + * @param prioirty level + */ + virtual void setPriority( int priority ) { + setPropertyValue( + CommandConstants::toString( + CommandConstants::HEADER_CONSUMERPRIORITY ), + util::Integer::toString( priority ) ); + } + + /** + * Get For non-durable topics if this subscription is set to be + * retroactive + * @return true for retroactive mode + */ + virtual bool getRetroactive(void) const { + return util::Boolean::parseBoolean( getPropertyValue( + CommandConstants::toString( + CommandConstants::HEADER_RETROACTIVE ), + "false" ) ); + } + + /** + * Set For non-durable topics if this subscription is set to be + * retroactive + * @param true if in retroactive mode + */ + virtual void setRetroactive( bool retroactive ) { + setPropertyValue( + CommandConstants::toString( + CommandConstants::HEADER_RETROACTIVE ), + util::Boolean::toString( retroactive ) ); + } + protected: /** @@ -173,7 +329,7 @@ namespace commands{ setPropertyValue( CommandConstants::toString( - CommandConstants::HEADER_ACK), + CommandConstants::HEADER_ACK ), CommandConstants::toString( CommandConstants::ACK_AUTO ) ); } diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/TextMessageCommand.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/TextMessageCommand.h index e354558b8f..2a11e9ec27 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/TextMessageCommand.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/TextMessageCommand.h @@ -68,6 +68,14 @@ namespace commands{ setBytes( msg, strlen(msg) + 1, false ); } + /** + * Sets the message contents. + * @param msg The message buffer. + */ + virtual void setText( const std::string& msg ) throw( cms::CMSException ) { + setBytes( msg.c_str(), msg.length() + 1, false ); + } + }; }}}} diff --git a/activemq-cpp/src/main/activemq/connector/stomp/commands/UnsubscribeCommand.h b/activemq-cpp/src/main/activemq/connector/stomp/commands/UnsubscribeCommand.h index 2a9a4a7528..65cd1aec2b 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/commands/UnsubscribeCommand.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/commands/UnsubscribeCommand.h @@ -51,7 +51,7 @@ namespace commands{ virtual const char* getDestination(void) const{ return getPropertyValue( CommandConstants::toString( - CommandConstants::HEADER_DESTINATION) ); + CommandConstants::HEADER_DESTINATION ) ); } /** @@ -60,7 +60,7 @@ namespace commands{ virtual void setDestination( const std::string& dest ){ setPropertyValue( CommandConstants::toString( - CommandConstants::HEADER_DESTINATION) , + CommandConstants::HEADER_DESTINATION ), dest ); } diff --git a/activemq-cpp/src/main/activemq/connector/stomp/marshal/Marshalable.h b/activemq-cpp/src/main/activemq/connector/stomp/marshal/Marshalable.h index b2b8cc7a52..f7270ffeab 100644 --- a/activemq-cpp/src/main/activemq/connector/stomp/marshal/Marshalable.h +++ b/activemq-cpp/src/main/activemq/connector/stomp/marshal/Marshalable.h @@ -30,7 +30,7 @@ namespace marshal{ { public: - virtual ~Marshalable(void) {} + virtual ~Marshalable(void) {} /** * Marshals the command to a stomp frame. diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQAckHandler.h b/activemq-cpp/src/main/activemq/core/ActiveMQAckHandler.h index 529c66b61c..9b8f2f0fab 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQAckHandler.h +++ b/activemq-cpp/src/main/activemq/core/ActiveMQAckHandler.h @@ -32,7 +32,7 @@ namespace core{ { public: - virtual ~ActiveMQAckHandler(void) {}; + virtual ~ActiveMQAckHandler(void) {}; /** * Method called to acknowledge the message passed diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQConnection.cpp b/activemq-cpp/src/main/activemq/core/ActiveMQConnection.cpp index 8d25c7bc78..05c11f677e 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQConnection.cpp +++ b/activemq-cpp/src/main/activemq/core/ActiveMQConnection.cpp @@ -34,6 +34,7 @@ ActiveMQConnection::ActiveMQConnection(ActiveMQConnectionData* connectionData) { this->connectionData = connectionData; this->started = false; + this->closed = false; this->exceptionListener = NULL; // We want to be the sink for all messages from the Connector @@ -57,7 +58,7 @@ cms::Session* ActiveMQConnection::createSession(void) { try { - return this->createSession( Session::AutoAcknowledge ); + return this->createSession( Session::AUTO_ACKNOWLEDGE ); } AMQ_CATCH_RETHROW( ActiveMQException ) AMQ_CATCHALL_THROW( ActiveMQException ) @@ -90,10 +91,20 @@ void ActiveMQConnection::close(void) throw ( cms::CMSException ) { try { + if( closed ) + { + return; + } + // Once current deliveries are done this stops the delivery // of any new messages. started = false; - + closed = true; + + // Shutdown connector and transport + connectionData->getConnector()->close(); + connectionData->getTransport()->close(); + // Destroy the connection data delete connectionData; connectionData = NULL; @@ -124,7 +135,7 @@ void ActiveMQConnection::addMessageListener( const unsigned int consumerId, ActiveMQMessageListener* listener ) { // Place in Map - synchronized(&mutex) + synchronized( &mutex ) { consumers[consumerId] = listener; } @@ -134,7 +145,7 @@ void ActiveMQConnection::addMessageListener( const unsigned int consumerId, void ActiveMQConnection::removeMessageListener( const unsigned int consumerId ) { // Remove from Map - synchronized(&mutex) + synchronized( &mutex ) { consumers.erase( consumerId ); } @@ -175,9 +186,9 @@ void ActiveMQConnection::onConsumerMessage( connector::ConsumerInfo* consumer, } // Started, so lock map and dispatch the message. - synchronized(&mutex) + synchronized( &mutex ) { - if(consumers.find(consumer->getConsumerId()) != consumers.end()) + if(consumers.find( consumer->getConsumerId()) != consumers.end() ) { consumers[consumer->getConsumerId()]-> onActiveMQMessage( message ); diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQConnection.h b/activemq-cpp/src/main/activemq/core/ActiveMQConnection.h index 516179dde2..56ea1327cb 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQConnection.h +++ b/activemq-cpp/src/main/activemq/core/ActiveMQConnection.h @@ -32,147 +32,149 @@ namespace activemq{ namespace core{ - class cms::Session; - class ActiveMQConsumer; + class cms::Session; + class ActiveMQConsumer; - class ActiveMQConnection : - public cms::Connection, - public connector::ConsumerMessageListener - { - private: + class ActiveMQConnection : + public cms::Connection, + public connector::ConsumerMessageListener + { + private: - // the registered exception listener - cms::ExceptionListener* exceptionListener; + // the registered exception listener + cms::ExceptionListener* exceptionListener; - // All the data that is used to connect this Connection - ActiveMQConnectionData* connectionData; + // All the data that is used to connect this Connection + ActiveMQConnectionData* connectionData; - // Indicates if this Connection is started - bool started; - - // Map of Consumer Ids to ActiveMQMessageListeners - std::map consumers; - - // Mutex to lock the Consumers Map - concurrent::Mutex mutex; - - public: + // Indicates if this Connection is started + bool started; - /** - * Constructor - */ - ActiveMQConnection(ActiveMQConnectionData* connectionData); - - /** - * Destructor - */ - virtual ~ActiveMQConnection(void); - - public: // Connection Interface Methods - - /** - * Creates a new Session to work for this Connection - */ - virtual cms::Session* createSession(void) throw ( cms::CMSException ); + // Indicates that this connection has been closed, it is no longer + // usable after this becomes true + bool closed; - /** - * Creates a new Session to work for this Connection using the - * specified acknowledgment mode - * @param the Acknowledgement Mode to use. - */ - virtual cms::Session* createSession(cms::Session::AcknowledgeMode ackMode) - throw ( cms::CMSException ); + // Map of Consumer Ids to ActiveMQMessageListeners + std::map< unsigned int, ActiveMQMessageListener* > consumers; + + // Mutex to lock the Consumers Map + concurrent::Mutex mutex; + + public: + + /** + * Constructor + * @param Pointer to an ActiveMQConnectionData object, owned here + */ + ActiveMQConnection( ActiveMQConnectionData* connectionData ); + + virtual ~ActiveMQConnection(void); + + public: // Connection Interface Methods + + /** + * Creates a new Session to work for this Connection + */ + virtual cms::Session* createSession(void) throw ( cms::CMSException ); + + /** + * Creates a new Session to work for this Connection using the + * specified acknowledgment mode + * @param the Acknowledgement Mode to use. + */ + virtual cms::Session* createSession( cms::Session::AcknowledgeMode ackMode ) + throw ( cms::CMSException ); - /** - * Get the Client Id for this session - * @return string version of Client Id - */ - virtual std::string getClientId(void) const; + /** + * Get the Client Id for this session + * @return string version of Client Id + */ + virtual std::string getClientId(void) const; - /** - * Retrieves the Connection Data object for this object. - * @return pointer to a connection data object. - */ - virtual ActiveMQConnectionData* getConnectionData(void){ - return connectionData; - } + /** + * Retrieves the Connection Data object for this object. + * @return pointer to a connection data object. + */ + virtual ActiveMQConnectionData* getConnectionData(void){ + return connectionData; + } - /** - * Gets the registered Exception Listener for this connection - * @return pointer to an exception listnener or NULL - */ - virtual cms::ExceptionListener* getExceptionListener(void) const{ - return exceptionListener; }; + /** + * Gets the registered Exception Listener for this connection + * @return pointer to an exception listnener or NULL + */ + virtual cms::ExceptionListener* getExceptionListener(void) const{ + return exceptionListener; }; - /** - * Sets the registed Exception Listener for this connection - * @param pointer to and ExceptionListener - */ - virtual void setExceptionListener(cms::ExceptionListener* listener){ - exceptionListener = listener; }; + /** + * Sets the registed Exception Listener for this connection + * @param pointer to and ExceptionListener + */ + virtual void setExceptionListener( cms::ExceptionListener* listener ){ + exceptionListener = listener; }; - /** - * Close the currently open connection - * @throws CMSException - */ - virtual void close(void) throw ( cms::CMSException ); + /** + * Close the currently open connection + * @throws CMSException + */ + virtual void close(void) throw ( cms::CMSException ); - /** - * Starts or (restarts) a connections delivery of incoming messages - * @throws CMSException - */ - virtual void start(void) throw ( cms::CMSException ); + /** + * Starts or (restarts) a connections delivery of incoming messages + * @throws CMSException + */ + virtual void start(void) throw ( cms::CMSException ); - /** - * Stop the flow of incoming messages - * @throws CMSException - */ - virtual void stop(void) throw ( cms::CMSException ); + /** + * Stop the flow of incoming messages + * @throws CMSException + */ + virtual void stop(void) throw ( cms::CMSException ); - public: // ActiveMQConnection Methods + public: // ActiveMQConnection Methods - /** - * Adds the ActiveMQMessageListener to the Mapping of Consumer Id's - * to listeners, all message to that id will be routed to the given - * listener - * @param Consumer Id String - * @param ActiveMQMessageListener Pointer - */ - virtual void addMessageListener(const unsigned int consumerId, - ActiveMQMessageListener* listener); + /** + * Adds the ActiveMQMessageListener to the Mapping of Consumer Id's + * to listeners, all message to that id will be routed to the given + * listener + * @param Consumer Id String + * @param ActiveMQMessageListener Pointer + */ + virtual void addMessageListener( const unsigned int consumerId, + ActiveMQMessageListener* listener ); - /** - * Remove the Listener for the specified Consumer Id - * @param Consumer Id string - */ - virtual void removeMessageListener(const unsigned int consumerId); + /** + * Remove the Listener for the specified Consumer Id + * @param Consumer Id string + */ + virtual void removeMessageListener( const unsigned int consumerId ); - private: + private: - /** - * Notify the excpetion listener - */ - void fire( exceptions::ActiveMQException& ex ) - { - if( exceptionListener != NULL ) - { - try + /** + * Notify the excpetion listener + */ + void fire( exceptions::ActiveMQException& ex ) + { + if( exceptionListener != NULL ) { - exceptionListener->onException( ex ); + try + { + exceptionListener->onException( ex ); + } + catch(...){} } - catch(...){} - } - } + } - /** - * Called to dispatch a message to a particular consumer. - * @param consumer the target consumer of the dispatch. - * @param msg the message to be dispatched. - */ - virtual void onConsumerMessage( connector::ConsumerInfo* consumer, - core::ActiveMQMessage* message ); + /** + * Called to dispatch a message to a particular consumer. + * @param consumer the target consumer of the dispatch. + * @param msg the message to be dispatched. + */ + virtual void onConsumerMessage( connector::ConsumerInfo* consumer, + core::ActiveMQMessage* message ); - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQConnectionFactory.cpp b/activemq-cpp/src/main/activemq/core/ActiveMQConnectionFactory.cpp index a3ed6e8bd5..9219866f28 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQConnectionFactory.cpp +++ b/activemq-cpp/src/main/activemq/core/ActiveMQConnectionFactory.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include @@ -48,10 +49,11 @@ ActiveMQConnectionFactory::ActiveMQConnectionFactory(void) } //////////////////////////////////////////////////////////////////////////////// -ActiveMQConnectionFactory::ActiveMQConnectionFactory(const std::string& url, - const std::string& username, - const std::string& password, - const std::string& clientId) +ActiveMQConnectionFactory::ActiveMQConnectionFactory( + const std::string& url, + const std::string& username, + const std::string& password, + const std::string& clientId ) { brokerURL = url; @@ -64,7 +66,7 @@ ActiveMQConnectionFactory::ActiveMQConnectionFactory(const std::string& url, cms::Connection* ActiveMQConnectionFactory::createConnection(void) throw ( cms::CMSException ) { - return createConnection(username, password); + return createConnection( username, password, clientId ); } //////////////////////////////////////////////////////////////////////////////// @@ -96,9 +98,18 @@ cms::Connection* ActiveMQConnectionFactory::createConnection( } // Store login data in the properties - properties->setProperty( "username", this->username ); - properties->setProperty( "password", this->password ); - properties->setProperty( "clientId", this->clientId ); + properties->setProperty( + ActiveMQConstants::toString( + ActiveMQConstants::PARAM_USERNAME ), + this->username ); + properties->setProperty( + ActiveMQConstants::toString( + ActiveMQConstants::PARAM_PASSWORD ), + this->password ); + properties->setProperty( + ActiveMQConstants::toString( + ActiveMQConstants::PARAM_CLIENTID ), + this->clientId ); // Parse out the properties from the URI parseURL( brokerURL, *properties ); @@ -112,7 +123,7 @@ cms::Connection* ActiveMQConnectionFactory::createConnection( throw ActiveMQException( __FILE__, __LINE__, "ActiveMQConnectionFactory::createConnection - " - "unknown transport factory"); + "unknown transport factory" ); } // Create the transport. @@ -121,7 +132,7 @@ cms::Connection* ActiveMQConnectionFactory::createConnection( throw ActiveMQException( __FILE__, __LINE__, "ActiveMQConnectionFactory::createConnection - " - "failed creating new Transport"); + "failed creating new Transport" ); } // What wire format are we using, defaults to Stomp @@ -137,18 +148,18 @@ cms::Connection* ActiveMQConnectionFactory::createConnection( throw NullPointerException( __FILE__, __LINE__, "ActiveMQConnectionFactory::createConnection - " - "Connector for Wire Format not registered in Map"); + "Connector for Wire Format not registered in Map" ); } // Create the Connector. connector = connectorfactory->createConnector( *properties, transport ); - if(connector == NULL) + if( connector == NULL ) { throw NullPointerException( __FILE__, __LINE__, "ActiveMQConnectionFactory::createConnection - " - "Failed to Create the Connector"); + "Failed to Create the Connector" ); } // Start the Connector @@ -177,9 +188,9 @@ cms::Connection* ActiveMQConnectionFactory::createConnection( catch( ... ) { exceptions::ActiveMQException ex( - __FILE__, __LINE__, - "ActiveMQConnectionFactory::create - " - "caught unknown exception" ); + __FILE__, __LINE__, + "ActiveMQConnectionFactory::create - " + "caught unknown exception" ); delete connection; delete connector; @@ -191,8 +202,8 @@ cms::Connection* ActiveMQConnectionFactory::createConnection( } //////////////////////////////////////////////////////////////////////////////// -void ActiveMQConnectionFactory::parseURL(const std::string& URI, - Properties& properties) +void ActiveMQConnectionFactory::parseURL( const std::string& URI, + Properties& properties ) throw ( exceptions::IllegalArgumentException ) { try @@ -203,14 +214,14 @@ void ActiveMQConnectionFactory::parseURL(const std::string& URI, // Require that there be three tokens at the least, these are // transport, url, port. - if(tokenizer.countTokens() < 3) + if( tokenizer.countTokens() < 3 ) { throw exceptions::IllegalArgumentException( __FILE__, __LINE__, (string("ActiveMQConnectionFactory::parseURL - " "Marlformed URI: ") + URI).c_str()); } - + // First element should be the Transport Type, following that is the // URL and any params. properties.setProperty( "transport", tokenizer.nextToken() ); @@ -219,24 +230,29 @@ void ActiveMQConnectionFactory::parseURL(const std::string& URI, // and then each param set is delimited with & we extract first // three chars as they are the left over :// properties.setProperty( "uri", tokenizer.nextToken("&?").substr(3) ); - + // Now get all the optional parameters and store them as properties int count = tokenizer.toArray(tokens); - for(int i = 0; i < count; ++i) + for( int i = 0; i < count; ++i ) { - tokenizer.reset(tokens[i], "="); + tokenizer.reset( tokens[i], "=" ); - if(tokenizer.countTokens() != 2) + if( tokenizer.countTokens() != 2 ) { throw exceptions::IllegalArgumentException( __FILE__, __LINE__, - (string("ActiveMQConnectionFactory::parseURL - " - "Marlformed Parameter = ") + tokens[i]).c_str()); + ( string( "ActiveMQConnectionFactory::parseURL - " + "Marlformed Parameter = " ) + tokens[i] ).c_str() ); } + + // Get them in order, passing both as nextToken calls in the + // set Property can cause reversed order. + string key = tokenizer.nextToken(); + string value = tokenizer.nextToken(); // Store this param as a property - properties.setProperty(tokenizer.nextToken(), tokenizer.nextToken()); + properties.setProperty( key, value ); } } AMQ_CATCH_RETHROW( IllegalArgumentException ) diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQConnectionFactory.h b/activemq-cpp/src/main/activemq/core/ActiveMQConnectionFactory.h index 47b22fb2f3..b64336de34 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQConnectionFactory.h +++ b/activemq-cpp/src/main/activemq/core/ActiveMQConnectionFactory.h @@ -25,153 +25,150 @@ namespace activemq{ namespace core{ - class util::Properties; + class util::Properties; - class ActiveMQConnectionFactory : public cms::ConnectionFactory - { - private: + class ActiveMQConnectionFactory : public cms::ConnectionFactory + { + private: - // The user name this factory will use to connect - std::string username; + // The user name this factory will use to connect + std::string username; - // The password this factory will use to connect - std::string password; + // The password this factory will use to connect + std::string password; - // The client id to assign to the connection created - std::string clientId; + // The client id to assign to the connection created + std::string clientId; - // The URL of the Broker, the default is: - // "tcp://localhost:61616" - std::string brokerURL; + // The URL of the Broker, the default is: + // "tcp://localhost:61616" + std::string brokerURL; - public: + public: - /** - * Constructor - */ - ActiveMQConnectionFactory(void); + /** + * Constructor + */ + ActiveMQConnectionFactory(void); - /** - * Constructor - * @param the URL of the Broker we are connecting to. - * @param username to authenticate with, defaults to "" - * @param password to authenticate with, defaults to "" - * @param client Id to assign to connection, defaults to "" - */ - ActiveMQConnectionFactory(const std::string& url, - const std::string& username = "", - const std::string& password = "", - const std::string& clientId = ""); + /** + * Constructor + * @param the URL of the Broker we are connecting to. + * @param username to authenticate with, defaults to "" + * @param password to authenticate with, defaults to "" + * @param client Id to assign to connection, defaults to "" + */ + ActiveMQConnectionFactory( const std::string& url, + const std::string& username = "", + const std::string& password = "", + const std::string& clientId = "" ); - /** - * Destructor - */ - virtual ~ActiveMQConnectionFactory(void) {} + virtual ~ActiveMQConnectionFactory(void) {} - /** - * Creates a connection with the default user identity. The - * connection is created in stopped mode. No messages will be - * delivered until the Connection.start method is explicitly - * called. - * @throws CMSException - */ - virtual cms::Connection* createConnection(void) throw ( cms::CMSException ); + /** + * Creates a connection with the default user identity. The + * connection is created in stopped mode. No messages will be + * delivered until the Connection.start method is explicitly + * called. + * @throws CMSException + */ + virtual cms::Connection* createConnection(void) throw ( cms::CMSException ); - /** - * Creates a connection with the specified user identity. The - * connection is created in stopped mode. No messages will be - * delivered until the Connection.start method is explicitly called. - * @throw CMSException. - */ - virtual cms::Connection* createConnection(const std::string& username, - const std::string& password, - const std::string& clientId = "") - throw ( cms::CMSException ); + /** + * Creates a connection with the specified user identity. The + * connection is created in stopped mode. No messages will be + * delivered until the Connection.start method is explicitly called. + * @throw CMSException. + */ + virtual cms::Connection* createConnection( const std::string& username, + const std::string& password, + const std::string& clientId = "" ) + throw ( cms::CMSException ); - /** - * Sets the username that should be used when creating a new connection - * @param username string - */ - virtual void setUsername(const std::string& username){ - this->username = username; - } + /** + * Sets the username that should be used when creating a new connection + * @param username string + */ + virtual void setUsername( const std::string& username ){ + this->username = username; + } - /** - * Gets the username that this factory will use when creating a new - * connection instance. - * @return username string, "" for default credentials - */ - virtual const std::string& getUsername(void) const { - return username; - } + /** + * Gets the username that this factory will use when creating a new + * connection instance. + * @return username string, "" for default credentials + */ + virtual const std::string& getUsername(void) const { + return username; + } - /** - * Sets the password that should be used when creating a new connection - * @param password string - */ - virtual void setPassword(const std::string& password){ - this->password = password; - } + /** + * Sets the password that should be used when creating a new connection + * @param password string + */ + virtual void setPassword( const std::string& password ){ + this->password = password; + } - /** - * Gets the password that this factory will use when creating a new - * connection instance. - * @return password string, "" for default credentials - */ - virtual const std::string& getPassword(void) const { - return password; - } + /** + * Gets the password that this factory will use when creating a new + * connection instance. + * @return password string, "" for default credentials + */ + virtual const std::string& getPassword(void) const { + return password; + } - /** - * Sets the Broker URL that should be used when creating a new - * connection instance - * @param brokerURL string - */ - virtual void setBrokerURL(const std::string& brokerURL){ - this->brokerURL = brokerURL; - } + /** + * Sets the Broker URL that should be used when creating a new + * connection instance + * @param brokerURL string + */ + virtual void setBrokerURL( const std::string& brokerURL ){ + this->brokerURL = brokerURL; + } - /** - * Gets the Broker URL that this factory will use when creating a new - * connection instance. - * @return brokerURL string - */ - virtual const std::string& getBrokerURL(void) const { - return brokerURL; - } + /** + * Gets the Broker URL that this factory will use when creating a new + * connection instance. + * @return brokerURL string + */ + virtual const std::string& getBrokerURL(void) const { + return brokerURL; + } - /** - * Sets the Client Id that should be used when creating a new - * connection instance - * @param clientId string - */ - virtual void setClientId(const std::string& clientId){ - this->clientId = clientId; - } + /** + * Sets the Client Id that should be used when creating a new + * connection instance + * @param clientId string + */ + virtual void setClientId( const std::string& clientId ){ + this->clientId = clientId; + } - /** - * Gets the Client Id that this factory will use when creating a new - * connection instance. - * @return clientId string - */ - virtual const std::string& getClientId(void) const { - return clientId; - } + /** + * Gets the Client Id that this factory will use when creating a new + * connection instance. + * @return clientId string + */ + virtual const std::string& getClientId(void) const { + return clientId; + } - protected: + protected: - /** - * Parses the properties out of the provided Broker URI and sets - * them in the passed Properties Object. - * @param a Broker URI to parse - * @param a Properties object to set the parsed values in - * @throws IllegalArgumentException if the passed URI is invalid - */ - virtual void parseURL(const std::string& URI, - util::Properties& properties) - throw ( exceptions::IllegalArgumentException ); + /** + * Parses the properties out of the provided Broker URI and sets + * them in the passed Properties Object. + * @param a Broker URI to parse + * @param a Properties object to set the parsed values in + * @throws IllegalArgumentException if the passed URI is invalid + */ + virtual void parseURL( const std::string& URI, + util::Properties& properties ) + throw ( exceptions::IllegalArgumentException ); - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQConstants.cpp b/activemq-cpp/src/main/activemq/core/ActiveMQConstants.cpp new file mode 100644 index 0000000000..b11e479918 --- /dev/null +++ b/activemq-cpp/src/main/activemq/core/ActiveMQConstants.cpp @@ -0,0 +1,58 @@ +/* + * 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 "ActiveMQConstants.h" +#include + +using namespace std; +using namespace activemq; +using namespace activemq::core; + +//////////////////////////////////////////////////////////////////////////////// +string ActiveMQConstants::StaticInitializer::destOptions[NUM_OPTIONS]; +string ActiveMQConstants::StaticInitializer::uriParams[NUM_PARAMS]; + +map< std::string, ActiveMQConstants::DestinationOption > + ActiveMQConstants::StaticInitializer::destOptionMap; +map< std::string, ActiveMQConstants::URIParam > + ActiveMQConstants::StaticInitializer::uriParamsMap; + +ActiveMQConstants::StaticInitializer ActiveMQConstants::staticInits; + +//////////////////////////////////////////////////////////////////////////////// +ActiveMQConstants::StaticInitializer::StaticInitializer(){ + + destOptions[CONSUMER_PREFECTCHSIZE] = "consumer.prefetchSize"; + destOptions[CUNSUMER_MAXPENDINGMSGLIMIT] = "consumer.maximumPendingMessageLimit"; + destOptions[CONSUMER_NOLOCAL] = "consumer.noLocal"; + destOptions[CONSUMER_DISPATCHASYNC] = "consumer.dispatchAsync"; + destOptions[CONSUMER_RETROACTIVE] = "consumer.retroactive"; + destOptions[CONSUMER_SELECTOR] = "consumer.selector"; + destOptions[CONSUMER_EXCLUSIVE] = "consumer.exclusive"; + destOptions[CONSUMER_PRIORITY] = "consumer.priority"; + + uriParams[PARAM_USERNAME] = "username"; + uriParams[PARAM_PASSWORD] = "password"; + uriParams[PARAM_CLIENTID] = "client-id"; + + for( int ix=0; ix + +#include +#include + +namespace activemq{ +namespace core{ + + /** + * Class holding constant values for various ActiveMQ specific things + * Each constant is defined as an enumeration and has functions that + * convert back an forth between string and enum values. + */ + class ActiveMQConstants{ + public: + + /** + * These values represent the options that can be appended to an + * Destination name, i.e. /topic/foo?consumer.exclusive=true + */ + enum DestinationOption{ + CONSUMER_PREFECTCHSIZE, + CUNSUMER_MAXPENDINGMSGLIMIT, + CONSUMER_NOLOCAL, + CONSUMER_DISPATCHASYNC, + CONSUMER_RETROACTIVE, + CONSUMER_SELECTOR, + CONSUMER_EXCLUSIVE, + CONSUMER_PRIORITY, + NUM_OPTIONS + }; + + /** + * These values represent the parameters that can be added to the + * connection URI that affect the ActiveMQ Core API + */ + enum URIParam + { + PARAM_USERNAME, + PARAM_PASSWORD, + PARAM_CLIENTID, + NUM_PARAMS + }; + + static const std::string& toString( const DestinationOption option ){ + return StaticInitializer::destOptions[option]; + } + + static DestinationOption toDestinationOption( const std::string& option ){ + std::map< std::string, DestinationOption >::iterator iter = + StaticInitializer::destOptionMap.find( option ); + + if( iter == StaticInitializer::destOptionMap.end() ){ + return NUM_OPTIONS; + } + + return iter->second; + } + + static const std::string& toString( const URIParam option ){ + return StaticInitializer::uriParams[option]; + } + + static URIParam toURIOption( const std::string& option ){ + std::map< std::string, URIParam >::iterator iter = + StaticInitializer::uriParamsMap.find( option ); + + if( iter == StaticInitializer::uriParamsMap.end() ){ + return NUM_PARAMS; + } + + return iter->second; + } + + class StaticInitializer{ + public: + StaticInitializer(); + virtual ~StaticInitializer(){} + + static std::string destOptions[NUM_OPTIONS]; + static std::string uriParams[NUM_PARAMS]; + static std::map destOptionMap; + static std::map uriParamsMap; + }; + + private: + + static StaticInitializer staticInits; + + }; + +}} + +#endif /*ACTIVEMQ_CORE_ACTIVEMQCONSTANTS_H_*/ diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQConsumer.cpp b/activemq-cpp/src/main/activemq/core/ActiveMQConsumer.cpp index 638effb568..e11ae377bb 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQConsumer.cpp +++ b/activemq-cpp/src/main/activemq/core/ActiveMQConsumer.cpp @@ -29,10 +29,10 @@ using namespace activemq::exceptions; using namespace activemq::concurrent; //////////////////////////////////////////////////////////////////////////////// -ActiveMQConsumer::ActiveMQConsumer(connector::ConsumerInfo* consumerInfo, - ActiveMQSession* session) +ActiveMQConsumer::ActiveMQConsumer( connector::ConsumerInfo* consumerInfo, + ActiveMQSession* session ) { - if(session == NULL || consumerInfo == NULL) + if( session == NULL || consumerInfo == NULL ) { throw NullPointerException( __FILE__, __LINE__, @@ -54,7 +54,7 @@ ActiveMQConsumer::~ActiveMQConsumer(void) { // Dispose of the Consumer Info, this should stop us from getting // any more messages. - session->onDestroySessionResource(this); + session->onDestroySessionResource( this ); // Stop the asynchronous message processin thread if it's // running. @@ -85,11 +85,11 @@ cms::Message* ActiveMQConsumer::receive(void) throw ( cms::CMSException ) { try { - synchronized(&msgQueue) + synchronized( &msgQueue ) { // Check for empty in case of spurious wakeup, or race to // queue lock. - while(!shutdown && msgQueue.empty()) + while( !shutdown && msgQueue.empty() ) { msgQueue.wait(); } @@ -123,12 +123,12 @@ cms::Message* ActiveMQConsumer::receive(void) throw ( cms::CMSException ) } //////////////////////////////////////////////////////////////////////////////// -cms::Message* ActiveMQConsumer::receive(int millisecs) +cms::Message* ActiveMQConsumer::receive( int millisecs ) throw ( cms::CMSException ) { try { - synchronized(&msgQueue) + synchronized( &msgQueue ) { // Check for empty, and wait if its not if( msgQueue.empty() ){ @@ -166,9 +166,9 @@ cms::Message* ActiveMQConsumer::receiveNoWait(void) { try { - synchronized(&msgQueue) + synchronized( &msgQueue ) { - if(!msgQueue.empty()) + if( !msgQueue.empty() ) { // Fetch the Message then copy it so it can be handed off // to the user. @@ -192,11 +192,11 @@ cms::Message* ActiveMQConsumer::receiveNoWait(void) } //////////////////////////////////////////////////////////////////////////////// -void ActiveMQConsumer::setMessageListener(cms::MessageListener* listener) +void ActiveMQConsumer::setMessageListener( cms::MessageListener* listener ) { try { - synchronized(&listenerLock) + synchronized( &listenerLock ) { this->listener = listener; } @@ -220,7 +220,7 @@ void ActiveMQConsumer::acknowledgeMessage( const ActiveMQMessage* message ) // Delegate the Ack to the Session, we cast away copnstness since // in a transactional session we might need to redeliver this // message and update its data. - session->acknowledge(this, const_cast< ActiveMQMessage*>( message ) ); + session->acknowledge( this, const_cast< ActiveMQMessage*>( message ) ); } AMQ_CATCH_RETHROW( ActiveMQException ) AMQ_CATCHALL_THROW( ActiveMQException ) @@ -231,18 +231,18 @@ void ActiveMQConsumer::run(void) { try { - while(!shutdown) + while( !shutdown ) { Message* message = NULL; - synchronized(&msgQueue) + synchronized( &msgQueue ) { // Gaurd against spurious wakeup or race to sync lock // also if the listner has been unregistered we don't // have anyone to notify, so we wait till a new one is // registered, and then we will deliver the backlog - while(msgQueue.empty() || listener == NULL) + while( msgQueue.empty() || listener == NULL ) { if( shutdown ) { @@ -252,7 +252,7 @@ void ActiveMQConsumer::run(void) } // don't want to process messages if we are shutting down. - if(shutdown) + if( shutdown ) { return; } @@ -275,18 +275,18 @@ void ActiveMQConsumer::run(void) { cms::ExceptionListener* listener = session->getExceptionListener(); - if(listener != NULL) + if( listener != NULL ) { listener->onException( ActiveMQException( __FILE__, __LINE__, "ActiveMQConsumer::run - " - "MessageListener threw an unknown Exception, recovering...")); + "MessageListener threw an unknown Exception, recovering..." ) ); } } } //////////////////////////////////////////////////////////////////////////////// -void ActiveMQConsumer::dispatch(ActiveMQMessage* message) +void ActiveMQConsumer::dispatch( ActiveMQMessage* message ) throw ( cms::CMSException ) { try @@ -294,19 +294,19 @@ void ActiveMQConsumer::dispatch(ActiveMQMessage* message) // If the Session is in ClientAcknowledge mode, then we set the // handler in the message to this object and send it out. Otherwise // we ack it here for all the other Modes. - if(session->getAcknowledgeMode() == Session::ClientAcknowledge) + if( session->getAcknowledgeMode() == Session::CLIENT_ACKNOWLEDGE ) { // Register ourself so that we can handle the Message's // acknowledge method. - message->setAckHandler(this); + message->setAckHandler( this ); } else { - session->acknowledge(this, message); + session->acknowledge( this, message ); } // No listener, so we queue it - synchronized(&msgQueue) + synchronized( &msgQueue ) { msgQueue.push( dynamic_cast< cms::Message* >( message ) ); msgQueue.notifyAll(); @@ -321,9 +321,9 @@ void ActiveMQConsumer::purgeMessages(void) { try { - synchronized(&msgQueue) + synchronized( &msgQueue ) { - while(!msgQueue.empty()) + while( !msgQueue.empty() ) { // destroy these messages if this is not a transacted // session, if it is then the tranasction will clean @@ -361,13 +361,13 @@ void ActiveMQConsumer::notifyListener( Message* message ){ try { MessageListener* listener = NULL; - synchronized(&listenerLock) + synchronized( &listenerLock ) { listener = getMessageListener(); } if(listener != NULL) { - listener->onMessage(*message); + listener->onMessage( message ); } } AMQ_CATCH_RETHROW( ActiveMQException ) @@ -398,14 +398,14 @@ void ActiveMQConsumer::startThread(){ try { // Start the thread, if it's not already started. - if(listenerThread == NULL) + if( listenerThread == NULL ) { - listenerThread = new Thread(this); + listenerThread = new Thread( this ); listenerThread->start(); } // notify the Queue so that any pending messages get delivered - synchronized(&msgQueue) + synchronized( &msgQueue ) { msgQueue.notifyAll(); } @@ -423,7 +423,7 @@ void ActiveMQConsumer::stopThread(){ // if the thread is running signal it to quit and then // wait for run to return so thread can die - if(listenerThread != NULL) + if( listenerThread != NULL ) { synchronized( &msgQueue ) { diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQConsumer.h b/activemq-cpp/src/main/activemq/core/ActiveMQConsumer.h index 05e76a0c05..f7f2f1d305 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQConsumer.h +++ b/activemq-cpp/src/main/activemq/core/ActiveMQConsumer.h @@ -57,7 +57,7 @@ namespace core{ concurrent::Mutex listenerLock; // Message Queue - util::Queue msgQueue; + util::Queue< cms::Message* > msgQueue; // Thread to notif a listener if one is added concurrent::Thread* listenerThread; @@ -71,12 +71,9 @@ namespace core{ /** * Constructor */ - ActiveMQConsumer(connector::ConsumerInfo* consumerInfo, - ActiveMQSession* session); + ActiveMQConsumer( connector::ConsumerInfo* consumerInfo, + ActiveMQSession* session ); - /** - * Destructor - */ virtual ~ActiveMQConsumer(void); public: // Interface Implementation @@ -94,7 +91,7 @@ namespace core{ * @return new message * @throws CMSException */ - virtual cms::Message* receive(int millisecs) throw ( cms::CMSException ); + virtual cms::Message* receive( int millisecs ) throw ( cms::CMSException ); /** * Receive a Message, does not wait if there isn't a new message @@ -108,7 +105,7 @@ namespace core{ * Sets the MessageListener that this class will send notifs on * @param MessageListener interface pointer */ - virtual void setMessageListener(cms::MessageListener* listener); + virtual void setMessageListener( cms::MessageListener* listener ); /** * Gets the MessageListener that this class will send notifs on @@ -178,7 +175,7 @@ namespace core{ * @param cms::Message pointer to the message to dispatch * @throw cms::CMSException */ - virtual void dispatch(ActiveMQMessage* message) + virtual void dispatch( ActiveMQMessage* message ) throw ( cms::CMSException ); /** @@ -220,6 +217,7 @@ namespace core{ * Stops the asynchronous message processing thread if it's started. */ void stopThread(); + }; }} diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQDestination.h b/activemq-cpp/src/main/activemq/core/ActiveMQDestination.h new file mode 100644 index 0000000000..5c2a51fd52 --- /dev/null +++ b/activemq-cpp/src/main/activemq/core/ActiveMQDestination.h @@ -0,0 +1,192 @@ +/* + * 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. + */ + +#ifndef _ACTIVEMQ_CORE_ACTIVEMQDESTINATION_H_ +#define _ACTIVEMQ_CORE_ACTIVEMQDESTINATION_H_ + +#include +#include +#include + +#include + +namespace activemq{ +namespace core{ + + template< typename T > + class ActiveMQDestination : public T + { + private: + + // Params that are optional on the destination + util::SimpleProperties properties; + + // Destination type + cms::Destination::DestinationType destType; + + // Name of the Destination + std::string name; + + public: + + /** + * Copy Consturctor + * @param CMS Dest to Copy, must be a compatible type + */ + ActiveMQDestination( const cms::Destination* source ){ + this->copy( *source ); + } + + /** + * Custom Constructor + * @param string destination name plus any params + * @param type of destination this represents. + */ + ActiveMQDestination( const std::string& dest, + cms::Destination::DestinationType destType ) + { + try + { + util::StringTokenizer tokenizer(dest, "?&"); + std::vector tokens; + + // Set the type, we know that much anyway + this->destType = destType; + + // Require that there at least one token, the dest + if( tokenizer.countTokens() < 1 ) + { + throw exceptions::IllegalArgumentException( + __FILE__, __LINE__, + ( std::string( + "ActiveMQDestination::ActiveMQDestination - " + "Marlformed Dest: " ) + dest ).c_str() ); + } + + // Grab the name, that's always first. + this->name = tokenizer.nextToken(); + + // Now get all the optional parameters and store them as properties + int count = tokenizer.toArray( tokens ); + + for( int i = 0; i < count; ++i ) + { + tokenizer.reset( tokens[i], "=" ); + + if( tokenizer.countTokens() != 2 ) + { + throw exceptions::IllegalArgumentException( + __FILE__, __LINE__, + ( std::string( + "ActiveMQDestination::ActiveMQDestination - " + "Marlformed Parameter = ") + tokens[i] ).c_str() ); + } + + // Get the out in the right order + std::string key = tokenizer.nextToken(); + std::string value = tokenizer.nextToken(); + + // Store this param as a property + properties.setProperty( key, value ); + } + } + AMQ_CATCH_RETHROW( exceptions::IllegalArgumentException ) + AMQ_CATCH_EXCEPTION_CONVERT( exceptions::ActiveMQException, exceptions::IllegalArgumentException ) + AMQ_CATCHALL_THROW( exceptions::IllegalArgumentException ) + } + + virtual ~ActiveMQDestination() {} + + /** + * Get the properties of this Destination, these are the optional + * params that can be specified on a destination name i.e/ + * TEST.QUEUE?consumer.dispatchAsync=false&consumer.prefetchSize=10 + * @returns const reference to a properties object + */ + virtual const util::Properties& getProperties() const { + return properties; + } + + /** + * Copy the contents of the given properties object to this + * objects Properties object. Existing values are erased. + * @param Properties to copy to this object. + */ + virtual void setProperties( const util::Properties& properties ){ + this->properties.copy( &properties ); + } + + /** + * Gets the Destination Name minus any optional params that can + * be appended to the destination with an ? + * @returns destination name minus params + */ + virtual const std::string& getName() const { + return name; + } + + /** + * Sets the Destination Name minus any optional params that can + * be appended to the destination with an ? + * @param destination name minus params + */ + virtual void setName( const std::string& ) { + this->name = name; + } + + /** + * Retrieve the Destination Type for this Destination + * @return The Destination Type + */ + virtual cms::Destination::DestinationType getDestinationType() const { + return destType; + } + + /** + * Set the Destination Type for this Destination + * @param The Destination Type + */ + virtual void setDestinationType( cms::Destination::DestinationType destType ) { + this->destType = destType; + } + + /** + * Copies the contents of the given Destinastion object to this one. + * @param source The source Destination object. + */ + virtual void copy( const cms::Destination& source ) { + + try + { + // This will throw an Bad Cast Exception if the destination + // isn't a compatible type + const ActiveMQDestination& destination = + dynamic_cast< const ActiveMQDestination& >( source ); + + this->name = destination.getName(); + this->destType = destination.getDestinationType(); + + this->properties.copy( &destination.getProperties() ); + } + AMQ_CATCHALL_THROW( exceptions::ActiveMQException ) + } + + }; + +}} + +#endif /*_ACTIVEMQ_CORE_ACTIVEMQDESTINATION_H_*/ diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQMessage.h b/activemq-cpp/src/main/activemq/core/ActiveMQMessage.h index 79488093f4..d325bb1755 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQMessage.h +++ b/activemq-cpp/src/main/activemq/core/ActiveMQMessage.h @@ -36,17 +36,14 @@ namespace core{ { public: - /** - * Destructor - */ - virtual ~ActiveMQMessage(void) {} + virtual ~ActiveMQMessage(void) {} /** * Sets the Acknowledgement Handler that this Message will use * when the Acknowledge method is called. * @param ActiveMQAckHandler */ - virtual void setAckHandler(ActiveMQAckHandler* handler) = 0; + virtual void setAckHandler( ActiveMQAckHandler* handler ) = 0; /** * Gets the number of times this message has been redelivered. @@ -59,7 +56,7 @@ namespace core{ * redelivered * @param redelivery count */ - virtual void setRedeliveryCount(int count) = 0; + virtual void setRedeliveryCount( int count ) = 0; }; diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQMessageListener.h b/activemq-cpp/src/main/activemq/core/ActiveMQMessageListener.h index 8462e818d9..9f38e93f00 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQMessageListener.h +++ b/activemq-cpp/src/main/activemq/core/ActiveMQMessageListener.h @@ -29,7 +29,7 @@ namespace core{ { public: - virtual ~ActiveMQMessageListener(void) {} + virtual ~ActiveMQMessageListener(void) {} /** * Called asynchronously when a new message is received, the message diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQProducer.cpp b/activemq-cpp/src/main/activemq/core/ActiveMQProducer.cpp index f598a73519..902d4fa529 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQProducer.cpp +++ b/activemq-cpp/src/main/activemq/core/ActiveMQProducer.cpp @@ -26,14 +26,14 @@ using namespace activemq::connector; using namespace activemq::exceptions; //////////////////////////////////////////////////////////////////////////////// -ActiveMQProducer::ActiveMQProducer(connector::ProducerInfo* producerInfo, - ActiveMQSession* session) +ActiveMQProducer::ActiveMQProducer( connector::ProducerInfo* producerInfo, + ActiveMQSession* session ) { - if(session == NULL || producerInfo == NULL) + if( session == NULL || producerInfo == NULL ) { throw NullPointerException( __FILE__, __LINE__, - "ActiveMQProducer::ActiveMQProducer - Init with NULL Session"); + "ActiveMQProducer::ActiveMQProducer - Init with NULL Session" ); } // Init Producer Data @@ -41,7 +41,7 @@ ActiveMQProducer::ActiveMQProducer(connector::ProducerInfo* producerInfo, this->producerInfo = producerInfo; // Default the Delivery options - deliveryMode = cms::Message::PERSISTANT; + deliveryMode = cms::DeliveryMode::PERSISTANT; disableMsgId = false; disableTimestamps = false; priority = 4; @@ -54,37 +54,37 @@ ActiveMQProducer::~ActiveMQProducer(void) try { // Dispose of the ProducerInfo - session->onDestroySessionResource(this); + session->onDestroySessionResource( this ); } AMQ_CATCH_NOTHROW( ActiveMQException ) AMQ_CATCHALL_NOTHROW( ) } //////////////////////////////////////////////////////////////////////////////// -void ActiveMQProducer::send(cms::Message& message) +void ActiveMQProducer::send( cms::Message* message ) throw ( cms::CMSException ) { try { - send(producerInfo->getDestination(), message); + send( &producerInfo->getDestination(), message ); } AMQ_CATCH_RETHROW( ActiveMQException ) AMQ_CATCHALL_THROW( ActiveMQException ) } //////////////////////////////////////////////////////////////////////////////// -void ActiveMQProducer::send(const cms::Destination& destination, - cms::Message& message) throw ( cms::CMSException ) +void ActiveMQProducer::send( const cms::Destination* destination, + cms::Message* message) throw ( cms::CMSException ) { try { // configure the message - message.setCMSDestination(destination); - message.setCMSDeliveryMode(deliveryMode); - message.setCMSPriority(priority); - message.setCMSExpiration(timeToLive); + message->setCMSDestination( destination ); + message->setCMSDeliveryMode( deliveryMode ); + message->setCMSPriority( priority ); + message->setCMSExpiration( timeToLive ); - session->send(&message, this); + session->send( message, this ); } AMQ_CATCH_RETHROW( ActiveMQException ) AMQ_CATCHALL_THROW( ActiveMQException ) diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQProducer.h b/activemq-cpp/src/main/activemq/core/ActiveMQProducer.h index 02a7228077..aebd05c92b 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQProducer.h +++ b/activemq-cpp/src/main/activemq/core/ActiveMQProducer.h @@ -20,6 +20,7 @@ #include #include #include +#include #include #include @@ -35,7 +36,7 @@ namespace core{ private: // Delivery Mode of this Producer - cms::Message::DeliveryMode deliveryMode; + int deliveryMode; // Disable the Message Id bool disableMsgId; @@ -63,9 +64,6 @@ namespace core{ ActiveMQProducer( connector::ProducerInfo* producerInfo, ActiveMQSession* session ); - /** - * Destructor - */ virtual ~ActiveMQProducer(void); /** @@ -73,21 +71,21 @@ namespace core{ * @param a Message Object Pointer * @throws CMSException */ - virtual void send( cms::Message& message ) throw ( cms::CMSException ); + virtual void send( cms::Message* message ) throw ( cms::CMSException ); /** * Sends the message to the designated destination. * @param a Message Object Pointer * @throws CMSException */ - virtual void send( const cms::Destination& destination, - cms::Message& message) throw ( cms::CMSException ); + virtual void send( const cms::Destination* destination, + cms::Message* message ) throw ( cms::CMSException ); /** * Sets the delivery mode for this Producer * @param The DeliveryMode */ - virtual void setDeliveryMode(cms::Message::DeliveryMode mode) { + virtual void setDeliveryMode( int mode ) { deliveryMode = mode; } @@ -95,7 +93,7 @@ namespace core{ * Gets the delivery mode for this Producer * @return The DeliveryMode */ - virtual cms::Message::DeliveryMode getDeliveryMode(void) const { + virtual int getDeliveryMode(void) const { return deliveryMode; } diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQSession.cpp b/activemq-cpp/src/main/activemq/core/ActiveMQSession.cpp index 17dbb8cd57..f99136aa60 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQSession.cpp +++ b/activemq-cpp/src/main/activemq/core/ActiveMQSession.cpp @@ -40,7 +40,7 @@ ActiveMQSession::ActiveMQSession( SessionInfo* sessionInfo, const Properties& properties, ActiveMQConnection* connection) { - if(sessionInfo == NULL || connection == NULL) + if( sessionInfo == NULL || connection == NULL ) { throw NullPointerException( __FILE__, __LINE__, @@ -53,7 +53,7 @@ ActiveMQSession::ActiveMQSession( SessionInfo* sessionInfo, this->closed = false; // Create a Transaction object only if the session is transactional - if(isTransacted()) + if( isTransacted() ) { transaction = new ActiveMQTransaction(connection, this, properties ); @@ -87,7 +87,7 @@ void ActiveMQSession::close(void) throw ( cms::CMSException ) // Destroy this sessions resources connection->getConnectionData()-> - getConnector()->destroyResource(sessionInfo); + getConnector()->destroyResource( sessionInfo ); // mark as done closed = true; @@ -101,7 +101,7 @@ void ActiveMQSession::commit(void) throw ( cms::CMSException ) { try { - if(closed || !isTransacted()) + if( closed || !isTransacted() ) { throw InvalidStateException( __FILE__, __LINE__, @@ -120,11 +120,11 @@ void ActiveMQSession::rollback(void) throw ( cms::CMSException ) { try { - if(closed || !isTransacted()) + if( closed || !isTransacted() ) { throw InvalidStateException( __FILE__, __LINE__, - "ActiveMQSession::rollback - This Session Can't Rollback"); + "ActiveMQSession::rollback - This Session Can't Rollback" ); } // Rollback the Transaction @@ -136,19 +136,19 @@ void ActiveMQSession::rollback(void) throw ( cms::CMSException ) //////////////////////////////////////////////////////////////////////////////// cms::MessageConsumer* ActiveMQSession::createConsumer( - cms::Destination& destination) + const cms::Destination* destination ) throw ( cms::CMSException ) { try { - if(closed) + if( closed ) { throw InvalidStateException( __FILE__, __LINE__, - "ActiveMQSession::createConsumer - Session Already Closed"); + "ActiveMQSession::createConsumer - Session Already Closed" ); } - return createConsumer(destination, ""); + return createConsumer( destination, "" ); } AMQ_CATCH_RETHROW( ActiveMQException ) AMQ_CATCHALL_THROW( ActiveMQException ) @@ -156,22 +156,22 @@ cms::MessageConsumer* ActiveMQSession::createConsumer( //////////////////////////////////////////////////////////////////////////////// cms::MessageConsumer* ActiveMQSession::createConsumer( - cms::Destination& destination, - const std::string& selector) + const cms::Destination* destination, + const std::string& selector ) throw ( cms::CMSException ) { try { - if(closed) + if( closed ) { throw InvalidStateException( __FILE__, __LINE__, - "ActiveMQSession::createConsumer - Session Already Closed"); + "ActiveMQSession::createConsumer - Session Already Closed" ); } ActiveMQConsumer* consumer = new ActiveMQConsumer( connection->getConnectionData()->getConnector()-> - createConsumer(&destination, sessionInfo, selector), this); + createConsumer( destination, sessionInfo, selector), this ); connection->addMessageListener( consumer->getConsumerInfo()->getConsumerId(), consumer ); @@ -184,7 +184,7 @@ cms::MessageConsumer* ActiveMQSession::createConsumer( //////////////////////////////////////////////////////////////////////////////// cms::MessageConsumer* ActiveMQSession::createDurableConsumer( - cms::Topic& destination, + const cms::Topic* destination, const std::string& name, const std::string& selector, bool noLocal ) @@ -192,16 +192,16 @@ cms::MessageConsumer* ActiveMQSession::createDurableConsumer( { try { - if(closed) + if( closed ) { throw InvalidStateException( __FILE__, __LINE__, - "ActiveMQSession::createProducer - Session Already Closed"); + "ActiveMQSession::createProducer - Session Already Closed" ); } ActiveMQConsumer* consumer = new ActiveMQConsumer( connection->getConnectionData()->getConnector()-> - createDurableConsumer( &destination, sessionInfo, name, selector, noLocal ), this); + createDurableConsumer( destination, sessionInfo, name, selector, noLocal ), this ); connection->addMessageListener( consumer->getConsumerInfo()->getConsumerId(), consumer ); @@ -214,53 +214,53 @@ cms::MessageConsumer* ActiveMQSession::createDurableConsumer( //////////////////////////////////////////////////////////////////////////////// cms::MessageProducer* ActiveMQSession::createProducer( - cms::Destination& destination) + const cms::Destination* destination ) throw ( cms::CMSException ) { try { - if(closed) + if( closed ) { throw InvalidStateException( __FILE__, __LINE__, - "ActiveMQSession::createProducer - Session Already Closed"); + "ActiveMQSession::createProducer - Session Already Closed" ); } return new ActiveMQProducer( connection->getConnectionData()->getConnector()-> - createProducer(&destination, sessionInfo), this); + createProducer( destination, sessionInfo ), this ); } AMQ_CATCH_RETHROW( ActiveMQException ) AMQ_CATCHALL_THROW( ActiveMQException ) } //////////////////////////////////////////////////////////////////////////////// -cms::Queue* ActiveMQSession::createQueue(const std::string& queueName) +cms::Queue* ActiveMQSession::createQueue( const std::string& queueName ) throw ( cms::CMSException ) { try { - if(closed) + if( closed ) { throw InvalidStateException( __FILE__, __LINE__, - "ActiveMQSession::createQueue - Session Already Closed"); + "ActiveMQSession::createQueue - Session Already Closed" ); } return connection->getConnectionData()-> - getConnector()->createQueue(queueName, sessionInfo); + getConnector()->createQueue( queueName, sessionInfo ); } AMQ_CATCH_RETHROW( ActiveMQException ) AMQ_CATCHALL_THROW( ActiveMQException ) } //////////////////////////////////////////////////////////////////////////////// -cms::Topic* ActiveMQSession::createTopic(const std::string& topicName) +cms::Topic* ActiveMQSession::createTopic( const std::string& topicName ) throw ( cms::CMSException ) { try { - if(closed) + if( closed ) { throw InvalidStateException( __FILE__, __LINE__, @@ -268,7 +268,7 @@ cms::Topic* ActiveMQSession::createTopic(const std::string& topicName) } return connection->getConnectionData()-> - getConnector()->createTopic(topicName, sessionInfo); + getConnector()->createTopic( topicName, sessionInfo ); } AMQ_CATCH_RETHROW( ActiveMQException ) AMQ_CATCHALL_THROW( ActiveMQException ) @@ -280,15 +280,16 @@ cms::TemporaryQueue* ActiveMQSession::createTemporaryQueue(void) { try { - if(closed) + if( closed ) { throw InvalidStateException( __FILE__, __LINE__, - "ActiveMQSession::createTemporaryQueue - Session Already Closed"); + "ActiveMQSession::createTemporaryQueue - " + "Session Already Closed" ); } return connection->getConnectionData()-> - getConnector()->createTemporaryQueue(sessionInfo); + getConnector()->createTemporaryQueue( sessionInfo ); } AMQ_CATCH_RETHROW( ActiveMQException ) AMQ_CATCHALL_THROW( ActiveMQException ) @@ -300,15 +301,16 @@ cms::TemporaryTopic* ActiveMQSession::createTemporaryTopic(void) { try { - if(closed) + if( closed ) { throw InvalidStateException( __FILE__, __LINE__, - "ActiveMQSession::createTemporaryTopic - Session Already Closed"); + "ActiveMQSession::createTemporaryTopic - " + "Session Already Closed" ); } return connection->getConnectionData()-> - getConnector()->createTemporaryTopic(sessionInfo); + getConnector()->createTemporaryTopic( sessionInfo ); } AMQ_CATCH_RETHROW( ActiveMQException ) AMQ_CATCHALL_THROW( ActiveMQException ) @@ -320,11 +322,11 @@ cms::Message* ActiveMQSession::createMessage(void) { try { - if(closed) + if( closed ) { throw InvalidStateException( __FILE__, __LINE__, - "ActiveMQSession::createMessage - Session Already Closed"); + "ActiveMQSession::createMessage - Session Already Closed" ); } return connection->getConnectionData()-> @@ -336,15 +338,15 @@ cms::Message* ActiveMQSession::createMessage(void) //////////////////////////////////////////////////////////////////////////////// cms::BytesMessage* ActiveMQSession::createBytesMessage(void) - throw ( cms::CMSException) + throw ( cms::CMSException ) { try { - if(closed) + if( closed ) { throw InvalidStateException( __FILE__, __LINE__, - "ActiveMQSession::createBytesMessage - Session Already Closed"); + "ActiveMQSession::createBytesMessage - Session Already Closed" ); } return connection->getConnectionData()-> @@ -357,14 +359,14 @@ cms::BytesMessage* ActiveMQSession::createBytesMessage(void) //////////////////////////////////////////////////////////////////////////////// cms::BytesMessage* ActiveMQSession::createBytesMessage( const unsigned char* bytes, - unsigned long bytesSize) - throw ( cms::CMSException) + unsigned long bytesSize ) + throw ( cms::CMSException ) { try { BytesMessage* msg = createBytesMessage(); - msg->setBodyBytes(bytes, bytesSize); + msg->setBodyBytes( bytes, bytesSize ); return msg; } @@ -378,11 +380,11 @@ cms::TextMessage* ActiveMQSession::createTextMessage(void) { try { - if(closed) + if( closed ) { throw InvalidStateException( __FILE__, __LINE__, - "ActiveMQSession::createTextMessage - Session Already Closed"); + "ActiveMQSession::createTextMessage - Session Already Closed" ); } return connection->getConnectionData()-> @@ -393,14 +395,14 @@ cms::TextMessage* ActiveMQSession::createTextMessage(void) } //////////////////////////////////////////////////////////////////////////////// -cms::TextMessage* ActiveMQSession::createTextMessage(const std::string& text) +cms::TextMessage* ActiveMQSession::createTextMessage( const std::string& text ) throw ( cms::CMSException ) { try { TextMessage* msg = createTextMessage(); - msg->setText(text.c_str()); + msg->setText( text.c_str() ); return msg; } @@ -414,11 +416,11 @@ cms::MapMessage* ActiveMQSession::createMapMessage(void) { try { - if(closed) + if( closed ) { throw InvalidStateException( __FILE__, __LINE__, - "ActiveMQSession::createMapMessage - Session Already Closed"); + "ActiveMQSession::createMapMessage - Session Already Closed" ); } return connection-> @@ -433,19 +435,19 @@ cms::MapMessage* ActiveMQSession::createMapMessage(void) cms::Session::AcknowledgeMode ActiveMQSession::getAcknowledgeMode(void) const { return sessionInfo != NULL ? - sessionInfo->getAckMode() : Session::AutoAcknowledge; + sessionInfo->getAckMode() : Session::AUTO_ACKNOWLEDGE; } //////////////////////////////////////////////////////////////////////////////// bool ActiveMQSession::isTransacted(void) const { return sessionInfo != NULL ? - sessionInfo->getAckMode() == Session::Transactional : false; + sessionInfo->getAckMode() == Session::SESSION_TRANSACTED : false; } //////////////////////////////////////////////////////////////////////////////// -void ActiveMQSession::acknowledge(ActiveMQConsumer* consumer, - ActiveMQMessage* message) +void ActiveMQSession::acknowledge( ActiveMQConsumer* consumer, + ActiveMQMessage* message ) throw ( cms::CMSException ) { try @@ -454,12 +456,12 @@ void ActiveMQSession::acknowledge(ActiveMQConsumer* consumer, { throw InvalidStateException( __FILE__, __LINE__, - "ActiveMQSession::acknowledgeMessage - Session Already Closed"); + "ActiveMQSession::acknowledgeMessage - Session Already Closed" ); } // Stores the Message and its consumer in the tranasction, if the // session is a transactional one. - if(isTransacted()) + if( isTransacted() ) { transaction->addToTransaction( message, consumer ); } @@ -474,16 +476,16 @@ void ActiveMQSession::acknowledge(ActiveMQConsumer* consumer, } //////////////////////////////////////////////////////////////////////////////// -void ActiveMQSession::send(cms::Message* message, ActiveMQProducer* producer) +void ActiveMQSession::send( cms::Message* message, ActiveMQProducer* producer ) throw ( cms::CMSException ) { try { - if(closed) + if( closed ) { throw InvalidStateException( __FILE__, __LINE__, - "ActiveMQSession::onProducerClose - Session Already Closed"); + "ActiveMQSession::onProducerClose - Session Already Closed" ); } // Send via the connection @@ -501,7 +503,7 @@ void ActiveMQSession::onDestroySessionResource( { try { - if(closed) + if( closed ) { throw InvalidStateException( __FILE__, __LINE__, @@ -515,13 +517,13 @@ void ActiveMQSession::onDestroySessionResource( { // Remove this Consumer from the Connection connection->removeMessageListener( - consumer->getConsumerInfo()->getConsumerId()); + consumer->getConsumerInfo()->getConsumerId() ); // Remove this consumer from the Transaction if we are // transactional if( transaction != NULL ) { - transaction->removeFromTransaction(consumer); + transaction->removeFromTransaction( consumer ); } } @@ -536,7 +538,7 @@ void ActiveMQSession::onDestroySessionResource( //////////////////////////////////////////////////////////////////////////////// cms::ExceptionListener* ActiveMQSession::getExceptionListener(void) { - if(connection != NULL) + if( connection != NULL ) { return connection->getExceptionListener(); } diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQSession.h b/activemq-cpp/src/main/activemq/core/ActiveMQSession.h index 3963ca34c8..eb9a8376b4 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQSession.h +++ b/activemq-cpp/src/main/activemq/core/ActiveMQSession.h @@ -25,244 +25,242 @@ namespace activemq{ namespace core{ - class ActiveMQTransaction; - class ActiveMQConnection; - class ActiveMQConsumer; - class ActiveMQMessage; - class ActiveMQProducer; - class ActiveMQConsumer; + class ActiveMQTransaction; + class ActiveMQConnection; + class ActiveMQConsumer; + class ActiveMQMessage; + class ActiveMQProducer; + class ActiveMQConsumer; - class ActiveMQSession : public cms::Session - { - private: + class ActiveMQSession : public cms::Session + { + private: - // SessionInfo for this Session - connector::SessionInfo* sessionInfo; + // SessionInfo for this Session + connector::SessionInfo* sessionInfo; - // Transaction Management object - ActiveMQTransaction* transaction; + // Transaction Management object + ActiveMQTransaction* transaction; - // Connection - ActiveMQConnection* connection; + // Connection + ActiveMQConnection* connection; - // Bool to indicate if this session was closed. - bool closed; + // Bool to indicate if this session was closed. + bool closed; - public: + public: - /** - * Constructor - */ - ActiveMQSession( connector::SessionInfo* sessionInfo, - const util::Properties& properties, - ActiveMQConnection* connection); + ActiveMQSession( connector::SessionInfo* sessionInfo, + const util::Properties& properties, + ActiveMQConnection* connection ); - /** - * Destructor - */ - virtual ~ActiveMQSession(void); + virtual ~ActiveMQSession(void); - public: // Implements Mehtods + public: // Implements Mehtods - /** - * Closes the Session - * @throw CMSException - */ - virtual void close(void) throw ( cms::CMSException ); + /** + * Closes the Session + * @throw CMSException + */ + virtual void close(void) throw ( cms::CMSException ); - /** - * Commits all messages done in this transaction and releases any - * locks currently held. - * @throws CMSException - */ - virtual void commit(void) throw ( cms::CMSException ); + /** + * Commits all messages done in this transaction and releases any + * locks currently held. + * @throws CMSException + */ + virtual void commit(void) throw ( cms::CMSException ); - /** - * Rollsback all messages done in this transaction and releases any - * locks currently held. - * @throws CMSException - */ - virtual void rollback(void) throw ( cms::CMSException ); + /** + * Rollsback all messages done in this transaction and releases any + * locks currently held. + * @throws CMSException + */ + virtual void rollback(void) throw ( cms::CMSException ); - /** - * Creates a MessageConsumer for the specified destination. - * @param the Destination that this consumer receiving messages for. - * @throws CMSException - */ - virtual cms::MessageConsumer* createConsumer(cms::Destination& destination) - throw ( cms::CMSException ); + /** + * Creates a MessageConsumer for the specified destination. + * @param the Destination that this consumer receiving messages for. + * @throws CMSException + */ + virtual cms::MessageConsumer* createConsumer( + const cms::Destination* destination ) + throw ( cms::CMSException ); - /** - * Creates a MessageConsumer for the specified destination, using a - * message selector. - * @param the Destination that this consumer receiving messages for. - * @throws CMSException - */ - virtual cms::MessageConsumer* createConsumer(cms::Destination& destination, - const std::string& selector) - throw ( cms::CMSException ); + /** + * Creates a MessageConsumer for the specified destination, using a + * message selector. + * @param the Destination that this consumer receiving messages for. + * @throws CMSException + */ + virtual cms::MessageConsumer* createConsumer( + const cms::Destination* destination, + const std::string& selector ) + throw ( cms::CMSException ); - /** - * Creates a durable subscriber to the specified topic, using a - * message selector - * @param the topic to subscribe to - * @param name used to identify the subscription - * @param only messages matching the selector are received - * @throws CMSException - */ - virtual cms::MessageConsumer* createDurableConsumer( - cms::Topic& destination, - const std::string& name, - const std::string& selector, - bool noLocal = false) + /** + * Creates a durable subscriber to the specified topic, using a + * message selector + * @param the topic to subscribe to + * @param name used to identify the subscription + * @param only messages matching the selector are received + * @throws CMSException + */ + virtual cms::MessageConsumer* createDurableConsumer( + const cms::Topic* destination, + const std::string& name, + const std::string& selector, + bool noLocal = false ) + throw ( cms::CMSException ); + + /** + * Creates a MessageProducer to send messages to the specified + * destination. + * @param the Destination to publish on + * @throws CMSException + */ + virtual cms::MessageProducer* createProducer( + const cms::Destination* destination ) + throw ( cms::CMSException ); + + /** + * Creates a queue identity given a Queue name. + * @param the name of the new Queue + * @throws CMSException + */ + virtual cms::Queue* createQueue( const std::string& queueName ) + throw ( cms::CMSException ); + + /** + * Creates a topic identity given a Queue name. + * @param the name of the new Topic + * @throws CMSException + */ + virtual cms::Topic* createTopic( const std::string& topicName ) throw ( cms::CMSException ); - /** - * Creates a MessageProducer to send messages to the specified - * destination. - * @param the Destination to publish on - * @throws CMSException - */ - virtual cms::MessageProducer* createProducer(cms::Destination& destination) - throw ( cms::CMSException ); + /** + * Creates a TemporaryQueue object. + * @throws CMSException + */ + virtual cms::TemporaryQueue* createTemporaryQueue(void) + throw ( cms::CMSException ); + + /** + * Creates a TemporaryTopic object. + * @throws CMSException + */ + virtual cms::TemporaryTopic* createTemporaryTopic(void) + throw ( cms::CMSException ); - /** - * Creates a queue identity given a Queue name. - * @param the name of the new Queue - * @throws CMSException - */ - virtual cms::Queue* createQueue(const std::string& queueName) - throw ( cms::CMSException ); + /** + * Creates a new Message + * @throws CMSException + */ + virtual cms::Message* createMessage(void) + throw ( cms::CMSException ); + + /** + * Creates a BytesMessage + * @throws CMSException + */ + virtual cms::BytesMessage* createBytesMessage(void) + throw ( cms::CMSException ); + + /** + * Creates a BytesMessage and sets the paylod to the passed value + * @param an array of bytes to set in the message + * @param the size of the bytes array, or number of bytes to use + * @throws CMSException + */ + virtual cms::BytesMessage* createBytesMessage( + const unsigned char* bytes, + unsigned long bytesSize ) + throw ( cms::CMSException ); + + /** + * Creates a new TextMessage + * @throws CMSException + */ + virtual cms::TextMessage* createTextMessage(void) + throw ( cms::CMSException ); - /** - * Creates a topic identity given a Queue name. - * @param the name of the new Topic - * @throws CMSException - */ - virtual cms::Topic* createTopic(const std::string& topicName) - throw ( cms::CMSException ); + /** + * Creates a new TextMessage and set the text to the value given + * @param the initial text for the message + * @throws CMSException + */ + virtual cms::TextMessage* createTextMessage( const std::string& text ) + throw ( cms::CMSException ); - /** - * Creates a TemporaryQueue object. - * @throws CMSException - */ - virtual cms::TemporaryQueue* createTemporaryQueue(void) - throw ( cms::CMSException ); + /** + * Creates a new TextMessage + * @throws CMSException + */ + virtual cms::MapMessage* createMapMessage(void) + throw ( cms::CMSException ); - /** - * Creates a TemporaryTopic object. - * @throws CMSException - */ - virtual cms::TemporaryTopic* createTemporaryTopic(void) - throw ( cms::CMSException ); - - /** - * Creates a new Message - * @throws CMSException - */ - virtual cms::Message* createMessage(void) - throw ( cms::CMSException ); - - /** - * Creates a BytesMessage - * @throws CMSException - */ - virtual cms::BytesMessage* createBytesMessage(void) - throw ( cms::CMSException); - - /** - * Creates a BytesMessage and sets the paylod to the passed value - * @param an array of bytes to set in the message - * @param the size of the bytes array, or number of bytes to use - * @throws CMSException - */ - virtual cms::BytesMessage* createBytesMessage(const unsigned char* bytes, - unsigned long bytesSize) - throw ( cms::CMSException); - - /** - * Creates a new TextMessage - * @throws CMSException - */ - virtual cms::TextMessage* createTextMessage(void) - throw ( cms::CMSException ); + /** + * Returns the acknowledgement mode of the session. + * @return the Sessions Acknowledge Mode + */ + virtual cms::Session::AcknowledgeMode getAcknowledgeMode(void) const; - /** - * Creates a new TextMessage and set the text to the value given - * @param the initial text for the message - * @throws CMSException - */ - virtual cms::TextMessage* createTextMessage(const std::string& text) - throw ( cms::CMSException ); - - /** - * Creates a new TextMessage - * @throws CMSException - */ - virtual cms::MapMessage* createMapMessage(void) - throw ( cms::CMSException ); - - /** - * Returns the acknowledgement mode of the session. - * @return the Sessions Acknowledge Mode - */ - virtual cms::Session::AcknowledgeMode getAcknowledgeMode(void) const; - - /** - * Gets if the Sessions is a Transacted Session - * @return transacted true - false. - */ - virtual bool isTransacted(void) const; + /** + * Gets if the Sessions is a Transacted Session + * @return transacted true - false. + */ + virtual bool isTransacted(void) const; public: // ActiveMQSession specific Methods - /** - * Sends a message from the Producer specified - * @param cms::Message pointer - * @param Producer Information - * @throws CMSException - */ - virtual void send(cms::Message* message, ActiveMQProducer* producer) - throw ( cms::CMSException ); + /** + * Sends a message from the Producer specified + * @param cms::Message pointer + * @param Producer Information + * @throws CMSException + */ + virtual void send( cms::Message* message, ActiveMQProducer* producer ) + throw ( cms::CMSException ); - /** - * When a ActiveMQ core object is closed or destroyed it should call - * back and let the session know that it is going away, this allows - * the session to clean up any associated resources. This method - * destroy's the data that is associated with a Producer object - * @param The Producer that is being destoryed - * @throw CMSException - */ - virtual void onDestroySessionResource( ActiveMQSessionResource* resource ) - throw ( cms::CMSException ); + /** + * When a ActiveMQ core object is closed or destroyed it should call + * back and let the session know that it is going away, this allows + * the session to clean up any associated resources. This method + * destroy's the data that is associated with a Producer object + * @param The Producer that is being destoryed + * @throw CMSException + */ + virtual void onDestroySessionResource( ActiveMQSessionResource* resource ) + throw ( cms::CMSException ); - /** - * Called to acknowledge the receipt of a message. - * @param The consumer that received the message - * @param The Message to acknowledge. - * @throws CMSException - */ - virtual void acknowledge(ActiveMQConsumer* consumer, - ActiveMQMessage* message) - throw ( cms::CMSException); + /** + * Called to acknowledge the receipt of a message. + * @param The consumer that received the message + * @param The Message to acknowledge. + * @throws CMSException + */ + virtual void acknowledge( ActiveMQConsumer* consumer, + ActiveMQMessage* message ) + throw ( cms::CMSException ); - /** - * This method gets any registered exception listener of this sessions - * connection and returns it. Mainly intended for use by the objects - * that this session creates so that they can notify the client of - * exceptions that occur in the context of another thread. - * @returns cms::ExceptionListener pointer or NULL - */ - virtual cms::ExceptionListener* getExceptionListener(void); + /** + * This method gets any registered exception listener of this sessions + * connection and returns it. Mainly intended for use by the objects + * that this session creates so that they can notify the client of + * exceptions that occur in the context of another thread. + * @returns cms::ExceptionListener pointer or NULL + */ + virtual cms::ExceptionListener* getExceptionListener(void); - /** - * Gets the Session Information object for this session, if the - * session is closed than this returns null - * @return SessionInfo Pointer - */ - virtual connector::SessionInfo* getSessionInfo(void) { - return sessionInfo; - } + /** + * Gets the Session Information object for this session, if the + * session is closed than this returns null + * @return SessionInfo Pointer + */ + virtual connector::SessionInfo* getSessionInfo(void) { + return sessionInfo; + } }; diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQSessionResource.h b/activemq-cpp/src/main/activemq/core/ActiveMQSessionResource.h index 76bb2adcf7..3fb0678063 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQSessionResource.h +++ b/activemq-cpp/src/main/activemq/core/ActiveMQSessionResource.h @@ -26,7 +26,7 @@ namespace core{ { public: - virtual ~ActiveMQSessionResource(void) {} + virtual ~ActiveMQSessionResource(void) {} /** * Retrieve the Connector resource that is associated with diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQTransaction.cpp b/activemq-cpp/src/main/activemq/core/ActiveMQTransaction.cpp index 6ab78b6557..e7d38e7f3e 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQTransaction.cpp +++ b/activemq-cpp/src/main/activemq/core/ActiveMQTransaction.cpp @@ -41,7 +41,7 @@ ActiveMQTransaction::ActiveMQTransaction( ActiveMQConnection* connection, { try { - if(connection == NULL || session == NULL) + if( connection == NULL || session == NULL ) { throw NullPointerException( __FILE__, __LINE__, @@ -56,9 +56,9 @@ ActiveMQTransaction::ActiveMQTransaction( ActiveMQConnection* connection, // convert from property Strings to int. redeliveryDelay = Integer::parseInt( - properties.getProperty("transaction.redeliveryDelay", "25") ); + properties.getProperty( "transaction.redeliveryDelay", "25" ) ); maxRedeliveries = Integer::parseInt( - properties.getProperty("transaction.maxRedeliveryCount", "5") ); + properties.getProperty( "transaction.maxRedeliveryCount", "5" ) ); // Start a new Transaction transactionInfo = connection->getConnectionData()-> @@ -76,16 +76,16 @@ ActiveMQTransaction::~ActiveMQTransaction(void) // Inform the connector we are rolling back before we close so that // the provider knows we didn't complete this transaction connection->getConnectionData()->getConnector()-> - rollback(transactionInfo, session->getSessionInfo()); + rollback( transactionInfo, session->getSessionInfo() ); // Clean up clearTransaction(); // Must allow all the tasks to complete before we destruct otherwise // the callbacks will cause an exception. - synchronized(&tasksDone) + synchronized( &tasksDone ) { - while(taskCount != 0) + while( taskCount != 0 ) { tasksDone.wait(1000); @@ -102,24 +102,24 @@ void ActiveMQTransaction::clearTransaction(void) { try { - if(transactionInfo != NULL) + if( transactionInfo != NULL ) { // Dispose of the ProducerInfo connection->getConnectionData()-> - getConnector()->destroyResource(transactionInfo); + getConnector()->destroyResource( transactionInfo ); } - synchronized(&rollbackLock) + synchronized( &rollbackLock ) { // If there are any messages that are being transacted, then // they die once and for all here. RollbackMap::iterator itr = rollbackMap.begin(); - for(; itr != rollbackMap.end(); ++itr) + for( ; itr != rollbackMap.end(); ++itr ) { MessageList::iterator msgItr = itr->second.begin(); - for(; msgItr != itr->second.end(); ++msgItr) + for( ; msgItr != itr->second.end(); ++msgItr ) { delete *msgItr; } @@ -136,10 +136,10 @@ void ActiveMQTransaction::clearTransaction(void) void ActiveMQTransaction::addToTransaction( ActiveMQMessage* message, ActiveMQMessageListener* listener ) { - synchronized(&rollbackLock) + synchronized( &rollbackLock ) { // Store in the Multi Map - rollbackMap[listener].push_back(message); + rollbackMap[listener].push_back( message ); } } @@ -151,7 +151,7 @@ void ActiveMQTransaction::removeFromTransaction( { // Delete all the messages, then remove the consumer's entry from // the Rollback Map. - synchronized(&rollbackLock) + synchronized( &rollbackLock ) { RollbackMap::iterator rb_itr = rollbackMap.find( listener ); @@ -162,13 +162,13 @@ void ActiveMQTransaction::removeFromTransaction( MessageList::iterator itr = rb_itr->second.begin(); - for(; itr != rollbackMap[listener].end(); ++itr) + for( ; itr != rollbackMap[listener].end(); ++itr ) { delete *itr; } // Erase the entry from the map - rollbackMap.erase(listener); + rollbackMap.erase( listener ); } } AMQ_CATCH_RETHROW( ActiveMQException ) @@ -180,7 +180,7 @@ void ActiveMQTransaction::commit(void) throw ( exceptions::ActiveMQException ) { try { - if(this->transactionInfo == NULL) + if( this->transactionInfo == NULL ) { throw InvalidStateException( __FILE__, __LINE__, @@ -208,7 +208,7 @@ void ActiveMQTransaction::rollback(void) throw ( exceptions::ActiveMQException ) { try { - if(this->transactionInfo == NULL) + if( this->transactionInfo == NULL ) { throw InvalidStateException( __FILE__, __LINE__, @@ -222,7 +222,7 @@ void ActiveMQTransaction::rollback(void) throw ( exceptions::ActiveMQException ) // Dispose of the ProducerInfo connection->getConnectionData()-> - getConnector()->destroyResource(transactionInfo); + getConnector()->destroyResource( transactionInfo ); // Start a new Transaction transactionInfo = connection->getConnectionData()-> @@ -235,7 +235,7 @@ void ActiveMQTransaction::rollback(void) throw ( exceptions::ActiveMQException ) // doesn't have to wait on this method to complete an release its // mutex so it can dispatch new messages. That would however requre // copying the whole map over to the thread. - synchronized(&rollbackLock) + synchronized( &rollbackLock ) { RollbackMap::iterator itr = rollbackMap.begin(); @@ -247,7 +247,7 @@ void ActiveMQTransaction::rollback(void) throw ( exceptions::ActiveMQException ) session, itr->second, maxRedeliveries, - redeliveryDelay) , this)); + redeliveryDelay ) , this ) ); // Count the tasks started. taskCount++; @@ -273,9 +273,9 @@ void ActiveMQTransaction::onTaskComplete( Runnable* task ) taskCount--; - if(taskCount == 0) + if( taskCount == 0 ) { - synchronized(&tasksDone) + synchronized( &tasksDone ) { tasksDone.notifyAll(); } @@ -292,12 +292,12 @@ void ActiveMQTransaction::onTaskException( Runnable* task, try { // Delegate - onTaskComplete(task); + onTaskComplete( task ); // Route the Error ExceptionListener* listener = connection->getExceptionListener(); - if(listener != NULL) + if( listener != NULL ) { listener->onException( ex ); } @@ -313,20 +313,20 @@ void ActiveMQTransaction::RollbackTask::run(void) { MessageList::iterator itr = messages.begin(); - for(; itr != messages.end(); ++itr) + for( ; itr != messages.end(); ++itr ) { - (*itr)->setRedeliveryCount((*itr)->getRedeliveryCount() + 1); + ( *itr )->setRedeliveryCount( ( *itr )->getRedeliveryCount() + 1 ); // Redeliver Messages at some point in the future - Thread::sleep(redeliveryDelay); + Thread::sleep( redeliveryDelay ); - if((*itr)->getRedeliveryCount() >= maxRedeliveries) + if( ( *itr )->getRedeliveryCount() >= maxRedeliveries ) { // Poison Ack the Message, we give up processing this one connection->getConnectionData()->getConnector()-> acknowledge( session->getSessionInfo(), - dynamic_cast< Message* >(*itr), + dynamic_cast< Message* >( *itr ), Connector::PoisonAck ); // Won't redeliver this so we kill it here. @@ -335,7 +335,7 @@ void ActiveMQTransaction::RollbackTask::run(void) return; } - listener->onActiveMQMessage(*itr); + listener->onActiveMQMessage( *itr ); } } AMQ_CATCH_RETHROW( ActiveMQException ) diff --git a/activemq-cpp/src/main/activemq/core/ActiveMQTransaction.h b/activemq-cpp/src/main/activemq/core/ActiveMQTransaction.h index d61c0664df..95f23a7696 100644 --- a/activemq-cpp/src/main/activemq/core/ActiveMQTransaction.h +++ b/activemq-cpp/src/main/activemq/core/ActiveMQTransaction.h @@ -107,10 +107,7 @@ namespace core{ ActiveMQSession* session, const util::Properties& properties ); - /** - * Destructor - */ - virtual ~ActiveMQTransaction(void); + virtual ~ActiveMQTransaction(void); /** * Adds the Message as a part of the Transaction for the specified diff --git a/activemq-cpp/src/main/activemq/exceptions/ActiveMQException.cpp b/activemq-cpp/src/main/activemq/exceptions/ActiveMQException.cpp index 1dc6d325a1..d8dc476812 100644 --- a/activemq-cpp/src/main/activemq/exceptions/ActiveMQException.cpp +++ b/activemq-cpp/src/main/activemq/exceptions/ActiveMQException.cpp @@ -39,6 +39,11 @@ void ActiveMQException::buildMessage(const char* format, va_list& vargs) // Guessed size was enough. Assign the string. message.assign (buffer, written); + + // assign isn't passing ownership, just copying, delete + // the allocated buffer. + delete buffer; + break; } diff --git a/activemq-cpp/src/main/activemq/exceptions/ActiveMQException.h b/activemq-cpp/src/main/activemq/exceptions/ActiveMQException.h index aa81098296..43ad007ec5 100644 --- a/activemq-cpp/src/main/activemq/exceptions/ActiveMQException.h +++ b/activemq-cpp/src/main/activemq/exceptions/ActiveMQException.h @@ -25,151 +25,153 @@ namespace activemq{ namespace exceptions{ - /* - * Base class for all exceptions. - */ - class ActiveMQException : public cms::CMSException - { - private: + /* + * Base class for all exceptions. + */ + class ActiveMQException : public cms::CMSException + { + private: - /** - * The cause of this exception. - */ - std::string message; - - /** - * The stack trace. - */ - std::vector< std::pair< std::string, int> > stackTrace; - - public: - - /** - * Default Constructor - */ - ActiveMQException(void) {} - - /** - * Copy Constructor - */ - ActiveMQException( const ActiveMQException& ex ){ - *this = ex; - } - - /** - * Constructor - Initializes the file name and line number where - * this message occured. Sets the message to report, using an - * optional list of arguments to parse into the message - * @param file name where exception occurs - * @param line number where the exception occurred. - * @param message to report - * @param list of primitives that are formatted into the message - */ - ActiveMQException(const char* file, const int lineNumber, - const char* msg, ...) - { - va_list vargs ; - va_start(vargs, msg) ; - buildMessage(msg, vargs) ; - - // Set the first mark for this exception. - setMark( file, lineNumber ); - } + /** + * The cause of this exception. + */ + std::string message; - /** - * Destructor - */ - virtual ~ActiveMQException(){} + /** + * The stack trace. + */ + std::vector< std::pair< std::string, int> > stackTrace; - /** - * Gets the message for this exception. - */ - virtual const char* getMessage() const{ return message.c_str(); } + public: + + /** + * Default Constructor + */ + ActiveMQException(void) {} + + /** + * Copy Constructor + */ + ActiveMQException( const ActiveMQException& ex ){ + *this = ex; + } + + /** + * Constructor - Initializes the file name and line number where + * this message occured. Sets the message to report, using an + * optional list of arguments to parse into the message + * @param file name where exception occurs + * @param line number where the exception occurred. + * @param message to report + * @param list of primitives that are formatted into the message + */ + ActiveMQException( const char* file, const int lineNumber, + const char* msg, ... ) + { + va_list vargs; + va_start( vargs, msg ) ; + buildMessage( msg, vargs ); + + // Set the first mark for this exception. + setMark( file, lineNumber ); + } + + virtual ~ActiveMQException(){} - /** - * Sets the cause for this exception. - * @param msg the format string for the msg. - */ - virtual void setMessage( const char* msg, ... ){ - va_list vargs ; - va_start(vargs, msg) ; - buildMessage(msg, vargs) ; - } - - /** - * Adds a file/line number to the stack trace. - * @param file The name of the file calling this method (use __FILE__). - * @param lineNumber The line number in the calling file (use __LINE__). - */ - virtual void setMark( const char* file, const int lineNumber ); - - /** - * Clones this exception. This is useful for cases where you need - * to preserve the type of the original exception as well as the message. - * All subclasses should override. - */ - virtual ActiveMQException* clone() const{ - return new ActiveMQException( *this ); - } - - /** - * Provides the stack trace for every point where - * this exception was caught, marked, and rethrown. The first - * item in the returned vector is the first point where the mark - * was set (e.g. where the exception was created). - * @return the stack trace. - */ - virtual std::vector< std::pair< std::string, int> > getStackTrace() const{ - return stackTrace; - } - - /** - * Prints the stack trace to std::err - */ - virtual void printStackTrace() const{ - printStackTrace( std::cerr ); - } - - /** - * Prints the stack trace to the given output stream. - * @param stream the target output stream. - */ - virtual void printStackTrace( std::ostream& stream ) const{ - stream << getStackTraceString(); - } - - /** - * Gets the stack trace as one contiguous string. - */ - virtual std::string getStackTraceString() const{ - - // Create the output stream. - std::ostringstream stream; - - // Write the message and each stack entry. - stream << message << std::endl; - for( unsigned int ix=0; ixmessage = ex.message; - this->stackTrace = ex.stackTrace; - return *this; - } - - protected: + /** + * Gets the message for this exception. + * @return Text formatted error message + */ + virtual const char* getMessage() const{ return message.c_str(); } - virtual void buildMessage(const char* format, va_list& vargs); + /** + * Sets the cause for this exception. + * @param msg the format string for the msg. + * @param variable - params to format into the string + */ + virtual void setMessage( const char* msg, ... ){ + va_list vargs; + va_start(vargs, msg); + buildMessage(msg, vargs); + } + + /** + * Adds a file/line number to the stack trace. + * @param file The name of the file calling this method (use __FILE__). + * @param lineNumber The line number in the calling file (use __LINE__). + */ + virtual void setMark( const char* file, const int lineNumber ); + + /** + * Clones this exception. This is useful for cases where you need + * to preserve the type of the original exception as well as the message. + * All subclasses should override. + * @return Copy of this Exception object + */ + virtual ActiveMQException* clone() const{ + return new ActiveMQException( *this ); + } + + /** + * Provides the stack trace for every point where + * this exception was caught, marked, and rethrown. The first + * item in the returned vector is the first point where the mark + * was set (e.g. where the exception was created). + * @return the stack trace. + */ + virtual std::vector< std::pair< std::string, int> > getStackTrace() const{ + return stackTrace; + } + + /** + * Prints the stack trace to std::err + */ + virtual void printStackTrace() const{ + printStackTrace( std::cerr ); + } + + /** + * Prints the stack trace to the given output stream. + * @param stream the target output stream. + */ + virtual void printStackTrace( std::ostream& stream ) const{ + stream << getStackTraceString(); + } + + /** + * Gets the stack trace as one contiguous string. + * @return string with formatted stack trace data + */ + virtual std::string getStackTraceString() const{ + + // Create the output stream. + std::ostringstream stream; + + // Write the message and each stack entry. + stream << message << std::endl; + for( unsigned int ix=0; ixmessage = ex.message; + this->stackTrace = ex.stackTrace; + return *this; + } + + protected: + + virtual void buildMessage( const char* format, va_list& vargs ); }; diff --git a/activemq-cpp/src/main/activemq/exceptions/IllegalMonitorStateException.h b/activemq-cpp/src/main/activemq/exceptions/IllegalMonitorStateException.h index 262309a28b..5b603e4c03 100644 --- a/activemq-cpp/src/main/activemq/exceptions/IllegalMonitorStateException.h +++ b/activemq-cpp/src/main/activemq/exceptions/IllegalMonitorStateException.h @@ -22,68 +22,65 @@ namespace activemq{ namespace exceptions{ - /* - * Thrown when an error occurs from calling a method from syncronizable - * and the caller doesn't hold a lock on the object. - */ - class IllegalMonitorStateException : public ActiveMQException - { - public: + /* + * Thrown when an error occurs from calling a method from syncronizable + * and the caller doesn't hold a lock on the object. + */ + class IllegalMonitorStateException : public ActiveMQException + { + public: - /** - * Default Constructor - */ - IllegalMonitorStateException(void) {}; + /** + * Default Constructor + */ + IllegalMonitorStateException(void) {}; - /** - * Conversion Constructor from some other ActiveMQException - * @param An exception that should become this type of Exception - */ - IllegalMonitorStateException(const ActiveMQException& ex){ - *(ActiveMQException*)this = ex; - } + /** + * Conversion Constructor from some other ActiveMQException + * @param An exception that should become this type of Exception + */ + IllegalMonitorStateException(const ActiveMQException& ex){ + *(ActiveMQException*)this = ex; + } - /** - * Copy Constructor - */ - IllegalMonitorStateException(const IllegalMonitorStateException& ex){ - *(ActiveMQException*)this = ex; - } + /** + * Copy Constructor + */ + IllegalMonitorStateException(const IllegalMonitorStateException& ex){ + *(ActiveMQException*)this = ex; + } - /** - * Constructor - Initializes the file name and line number where - * this message occured. Sets the message to report, using an - * optional list of arguments to parse into the message - * @param file name where exception occurs - * @param line number where the exception occurred. - * @param message to report - * @param list of primitives that are formatted into the message - */ - IllegalMonitorStateException(const char* file, - const int lineNumber, - const char* msg, ...) - { - va_list vargs; - va_start(vargs, msg); - buildMessage(msg, vargs); + /** + * Constructor - Initializes the file name and line number where + * this message occured. Sets the message to report, using an + * optional list of arguments to parse into the message + * @param file name where exception occurs + * @param line number where the exception occurred. + * @param message to report + * @param list of primitives that are formatted into the message + */ + IllegalMonitorStateException( const char* file, + const int lineNumber, + const char* msg, ...) + { + va_list vargs; + va_start(vargs, msg); + buildMessage(msg, vargs); - // Set the first mark for this exception. - setMark(file, lineNumber); - } + // Set the first mark for this exception. + setMark(file, lineNumber); + } - /** - * Clones this exception. This is useful for cases where you need - * to preserve the type of the original exception as well as the message. - * All subclasses should override. - */ - virtual ActiveMQException* clone(void) const{ - return new IllegalMonitorStateException(*this); - } + /** + * Clones this exception. This is useful for cases where you need + * to preserve the type of the original exception as well as the message. + * All subclasses should override. + */ + virtual ActiveMQException* clone(void) const{ + return new IllegalMonitorStateException(*this); + } - /** - * Destructor - */ - virtual ~IllegalMonitorStateException(void) {} + virtual ~IllegalMonitorStateException(void) {} }; diff --git a/activemq-cpp/src/main/activemq/exceptions/InterruptedException.h b/activemq-cpp/src/main/activemq/exceptions/InterruptedException.h index df483fff4a..e0476bd93a 100644 --- a/activemq-cpp/src/main/activemq/exceptions/InterruptedException.h +++ b/activemq-cpp/src/main/activemq/exceptions/InterruptedException.h @@ -22,67 +22,64 @@ namespace activemq{ namespace exceptions{ - /* - * Thrown when an Thread is interrupted during a wait. - */ - class InterruptedException : public ActiveMQException - { - public: + /* + * Thrown when an Thread is interrupted during a wait. + */ + class InterruptedException : public ActiveMQException + { + public: - /** - * Default Constructor - */ - InterruptedException(void) {}; + /** + * Default Constructor + */ + InterruptedException(void) {}; - /** - * Conversion Constructor from some other ActiveMQException - * @param An exception that should become this type of Exception - */ - InterruptedException(const ActiveMQException& ex){ - *(ActiveMQException*)this = ex; - } + /** + * Conversion Constructor from some other ActiveMQException + * @param An exception that should become this type of Exception + */ + InterruptedException(const ActiveMQException& ex){ + *(ActiveMQException*)this = ex; + } - /** - * Copy Constructor - */ - InterruptedException(const InterruptedException& ex){ - *(ActiveMQException*)this = ex; - } + /** + * Copy Constructor + */ + InterruptedException(const InterruptedException& ex){ + *(ActiveMQException*)this = ex; + } - /** - * Constructor - Initializes the file name and line number where - * this message occured. Sets the message to report, using an - * optional list of arguments to parse into the message - * @param file name where exception occurs - * @param line number where the exception occurred. - * @param message to report - * @param list of primitives that are formatted into the message - */ - InterruptedException(const char* file, - const int lineNumber, - const char* msg, ...) - { - va_list vargs; - va_start(vargs, msg); - buildMessage(msg, vargs); + /** + * Constructor - Initializes the file name and line number where + * this message occured. Sets the message to report, using an + * optional list of arguments to parse into the message + * @param file name where exception occurs + * @param line number where the exception occurred. + * @param message to report + * @param list of primitives that are formatted into the message + */ + InterruptedException( const char* file, + const int lineNumber, + const char* msg, ... ) + { + va_list vargs; + va_start(vargs, msg); + buildMessage(msg, vargs); - // Set the first mark for this exception. - setMark(file, lineNumber); - } + // Set the first mark for this exception. + setMark(file, lineNumber); + } - /** - * Clones this exception. This is useful for cases where you need - * to preserve the type of the original exception as well as the message. - * All subclasses should override. - */ - virtual ActiveMQException* clone(void) const{ - return new InterruptedException(*this); - } + /** + * Clones this exception. This is useful for cases where you need + * to preserve the type of the original exception as well as the message. + * All subclasses should override. + */ + virtual ActiveMQException* clone(void) const{ + return new InterruptedException(*this); + } - /** - * Destructor - */ - virtual ~InterruptedException(void) {} + virtual ~InterruptedException(void) {} }; diff --git a/activemq-cpp/src/main/activemq/exceptions/InvalidStateException.h b/activemq-cpp/src/main/activemq/exceptions/InvalidStateException.h index 5241213590..e24c9ff77b 100644 --- a/activemq-cpp/src/main/activemq/exceptions/InvalidStateException.h +++ b/activemq-cpp/src/main/activemq/exceptions/InvalidStateException.h @@ -22,70 +22,67 @@ namespace activemq{ namespace exceptions{ - /* - * Thrown when an operation is requested, but the state of the object - * servicing the request is not correct for that request. - */ - class InvalidStateException : public ActiveMQException - { - public: + /* + * Thrown when an operation is requested, but the state of the object + * servicing the request is not correct for that request. + */ + class InvalidStateException : public ActiveMQException + { + public: - /** - * Default Constructor - */ - InvalidStateException(void) {} + /** + * Default Constructor + */ + InvalidStateException(void) {} - /** - * Conversion Constructor from some other ActiveMQException - * @param An exception that should become this type of Exception - */ - InvalidStateException(const ActiveMQException& ex){ - *(ActiveMQException*)this = ex; - } + /** + * Conversion Constructor from some other ActiveMQException + * @param An exception that should become this type of Exception + */ + InvalidStateException(const ActiveMQException& ex){ + *(ActiveMQException*)this = ex; + } - /** - * Copy Constructor - */ - InvalidStateException(const InvalidStateException& ex){ - *(ActiveMQException*)this = ex; - } + /** + * Copy Constructor + */ + InvalidStateException( const InvalidStateException& ex ){ + *(ActiveMQException*)this = ex; + } - /** - * Constructor - Initializes the file name and line number where - * this message occured. Sets the message to report, using an - * optional list of arguments to parse into the message - * @param file name where exception occurs - * @param line number where the exception occurred. - * @param message to report - * @param list of primitives that are formatted into the message - */ - InvalidStateException(const char* file, - const int lineNumber, - const char* msg, ...) - { - va_list vargs; - va_start(vargs, msg); - buildMessage(msg, vargs); + /** + * Constructor - Initializes the file name and line number where + * this message occured. Sets the message to report, using an + * optional list of arguments to parse into the message + * @param file name where exception occurs + * @param line number where the exception occurred. + * @param message to report + * @param list of primitives that are formatted into the message + */ + InvalidStateException( const char* file, + const int lineNumber, + const char* msg, ... ) + { + va_list vargs; + va_start( vargs, msg ); + buildMessage( msg, vargs ); - // Set the first mark for this exception. - setMark(file, lineNumber); - } + // Set the first mark for this exception. + setMark( file, lineNumber ); + } - /** - * Clones this exception. This is useful for cases where you need - * to preserve the type of the original exception as well as the message. - * All subclasses should override. - */ - virtual ActiveMQException* clone(void) const{ - return new InvalidStateException(*this); - } + /** + * Clones this exception. This is useful for cases where you need + * to preserve the type of the original exception as well as the message. + * All subclasses should override. + */ + virtual ActiveMQException* clone(void) const{ + return new InvalidStateException(*this); + } - /** - * Destructor - */ - virtual ~InvalidStateException(void) {} + virtual ~InvalidStateException(void) {} - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/exceptions/NoSuchElementException.h b/activemq-cpp/src/main/activemq/exceptions/NoSuchElementException.h index 1d15623c62..6b6fe10ed3 100644 --- a/activemq-cpp/src/main/activemq/exceptions/NoSuchElementException.h +++ b/activemq-cpp/src/main/activemq/exceptions/NoSuchElementException.h @@ -22,70 +22,67 @@ namespace activemq{ namespace exceptions{ - /* - * Thrown from an operation that attempts to access some element that does - * not exist. - */ - class NoSuchElementException : public ActiveMQException - { - public: + /* + * Thrown from an operation that attempts to access some element that does + * not exist. + */ + class NoSuchElementException : public ActiveMQException + { + public: - /** - * Default Constructor - */ - NoSuchElementException(void) {}; + /** + * Default Constructor + */ + NoSuchElementException(void) {}; - /** - * Conversion Constructor from some other ActiveMQException - * @param An exception that should become this type of Exception - */ - NoSuchElementException(const ActiveMQException& ex){ - *(ActiveMQException*)this = ex; - } + /** + * Conversion Constructor from some other ActiveMQException + * @param An exception that should become this type of Exception + */ + NoSuchElementException( const ActiveMQException& ex ){ + *(ActiveMQException*)this = ex; + } - /** - * Copy Constructor - */ - NoSuchElementException(const NoSuchElementException& ex){ - *(ActiveMQException*)this = ex; - } + /** + * Copy Constructor + */ + NoSuchElementException( const NoSuchElementException& ex ){ + *(ActiveMQException*)this = ex; + } - /** - * Constructor - Initializes the file name and line number where - * this message occured. Sets the message to report, using an - * optional list of arguments to parse into the message - * @param file name where exception occurs - * @param line number where the exception occurred. - * @param message to report - * @param list of primitives that are formatted into the message - */ - NoSuchElementException(const char* file, - const int lineNumber, - const char* msg, ...) - { - va_list vargs; - va_start(vargs, msg); - buildMessage(msg, vargs); + /** + * Constructor - Initializes the file name and line number where + * this message occured. Sets the message to report, using an + * optional list of arguments to parse into the message + * @param file name where exception occurs + * @param line number where the exception occurred. + * @param message to report + * @param list of primitives that are formatted into the message + */ + NoSuchElementException( const char* file, + const int lineNumber, + const char* msg, ... ) + { + va_list vargs; + va_start( vargs, msg ); + buildMessage( msg, vargs ); - // Set the first mark for this exception. - setMark(file, lineNumber); - } + // Set the first mark for this exception. + setMark( file, lineNumber ); + } - /** - * Clones this exception. This is useful for cases where you need - * to preserve the type of the original exception as well as the message. - * All subclasses should override. - */ - virtual ActiveMQException* clone(void) const{ - return new NoSuchElementException(*this); - } + /** + * Clones this exception. This is useful for cases where you need + * to preserve the type of the original exception as well as the message. + * All subclasses should override. + */ + virtual ActiveMQException* clone(void) const{ + return new NoSuchElementException(*this); + } - /** - * Destructor - */ - virtual ~NoSuchElementException(void) {} + virtual ~NoSuchElementException(void) {} - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/exceptions/NullPointerException.h b/activemq-cpp/src/main/activemq/exceptions/NullPointerException.h index 562d1de4ce..978875c69d 100644 --- a/activemq-cpp/src/main/activemq/exceptions/NullPointerException.h +++ b/activemq-cpp/src/main/activemq/exceptions/NullPointerException.h @@ -22,69 +22,66 @@ namespace activemq{ namespace exceptions{ - /* - * Thrown when an error occurs that involves a pointer being NULL - */ - class NullPointerException : public ActiveMQException - { - public: + /* + * Thrown when an error occurs that involves a pointer being NULL + */ + class NullPointerException : public ActiveMQException + { + public: - /** - * Default Constructor - */ - NullPointerException(void) {}; + /** + * Default Constructor + */ + NullPointerException(void) {}; - /** - * Conversion Constructor from some other ActiveMQException - * @param An exception that should become this type of Exception - */ - NullPointerException(const ActiveMQException& ex){ - *(ActiveMQException*)this = ex; - } + /** + * Conversion Constructor from some other ActiveMQException + * @param An exception that should become this type of Exception + */ + NullPointerException( const ActiveMQException& ex ){ + *(ActiveMQException*)this = ex; + } - /** - * Copy Constructor - */ - NullPointerException(const NullPointerException& ex){ - *(ActiveMQException*)this = ex; - } + /** + * Copy Constructor + */ + NullPointerException(const NullPointerException& ex){ + *(ActiveMQException*)this = ex; + } - /** - * Constructor - Initializes the file name and line number where - * this message occured. Sets the message to report, using an - * optional list of arguments to parse into the message - * @param file name where exception occurs - * @param line number where the exception occurred. - * @param message to report - * @param list of primitives that are formatted into the message - */ - NullPointerException(const char* file, - const int lineNumber, - const char* msg, ...) - { - va_list vargs; - va_start(vargs, msg); - buildMessage(msg, vargs); + /** + * Constructor - Initializes the file name and line number where + * this message occured. Sets the message to report, using an + * optional list of arguments to parse into the message + * @param file name where exception occurs + * @param line number where the exception occurred. + * @param message to report + * @param list of primitives that are formatted into the message + */ + NullPointerException( const char* file, + const int lineNumber, + const char* msg, ... ) + { + va_list vargs; + va_start( vargs, msg ); + buildMessage( msg, vargs ); - // Set the first mark for this exception. - setMark(file, lineNumber); - } + // Set the first mark for this exception. + setMark( file, lineNumber ); + } - /** - * Clones this exception. This is useful for cases where you need - * to preserve the type of the original exception as well as the message. - * All subclasses should override. - */ - virtual ActiveMQException* clone(void) const{ - return new NullPointerException(*this); - } + /** + * Clones this exception. This is useful for cases where you need + * to preserve the type of the original exception as well as the message. + * All subclasses should override. + */ + virtual ActiveMQException* clone(void) const{ + return new NullPointerException( *this ); + } - /** - * Destructor - */ - virtual ~NullPointerException(void) {} + virtual ~NullPointerException(void) {} - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/exceptions/RuntimeException.h b/activemq-cpp/src/main/activemq/exceptions/RuntimeException.h index 1f7339668e..7c84754401 100644 --- a/activemq-cpp/src/main/activemq/exceptions/RuntimeException.h +++ b/activemq-cpp/src/main/activemq/exceptions/RuntimeException.h @@ -22,71 +22,68 @@ namespace activemq{ namespace exceptions{ - /* - * Thrown when an error occurs that involves something in the run time - * This could be a memory allocation exception or some other generally - * unrecoverable exception. - */ - class RuntimeException : public ActiveMQException - { - public: + /* + * Thrown when an error occurs that involves something in the run time + * This could be a memory allocation exception or some other generally + * unrecoverable exception. + */ + class RuntimeException : public ActiveMQException + { + public: - /** - * Default Constructor - */ - RuntimeException(void) {}; + /** + * Default Constructor + */ + RuntimeException(void) {}; - /** - * Conversion Constructor from some other ActiveMQException - * @param An exception that should become this type of Exception - */ - RuntimeException(const ActiveMQException& ex){ - *(ActiveMQException*)this = ex; - } + /** + * Conversion Constructor from some other ActiveMQException + * @param An exception that should become this type of Exception + */ + RuntimeException( const ActiveMQException& ex ){ + *(ActiveMQException*)this = ex; + } - /** - * Copy Constructor - */ - RuntimeException(const RuntimeException& ex){ - *(ActiveMQException*)this = ex; - } + /** + * Copy Constructor + */ + RuntimeException( const RuntimeException& ex ){ + *(ActiveMQException*)this = ex; + } - /** - * Constructor - Initializes the file name and line number where - * this message occured. Sets the message to report, using an - * optional list of arguments to parse into the message - * @param file name where exception occurs - * @param line number where the exception occurred. - * @param message to report - * @param list of primitives that are formatted into the message - */ - RuntimeException(const char* file, - const int lineNumber, - const char* msg, ...) - { - va_list vargs; - va_start(vargs, msg); - buildMessage(msg, vargs); + /** + * Constructor - Initializes the file name and line number where + * this message occured. Sets the message to report, using an + * optional list of arguments to parse into the message + * @param file name where exception occurs + * @param line number where the exception occurred. + * @param message to report + * @param list of primitives that are formatted into the message + */ + RuntimeException( const char* file, + const int lineNumber, + const char* msg, ... ) + { + va_list vargs; + va_start(vargs, msg); + buildMessage(msg, vargs); - // Set the first mark for this exception. - setMark(file, lineNumber); - } + // Set the first mark for this exception. + setMark(file, lineNumber); + } - /** - * Clones this exception. This is useful for cases where you need - * to preserve the type of the original exception as well as the message. - * All subclasses should override. - */ - virtual ActiveMQException* clone(void) const{ - return new RuntimeException(*this); - } + /** + * Clones this exception. This is useful for cases where you need + * to preserve the type of the original exception as well as the message. + * All subclasses should override. + */ + virtual ActiveMQException* clone(void) const{ + return new RuntimeException( *this ); + } - /** - * Destructor - */ - virtual ~RuntimeException(void) {} + virtual ~RuntimeException(void) {} - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/exceptions/UnsupportedOperationException.h b/activemq-cpp/src/main/activemq/exceptions/UnsupportedOperationException.h index 934abd9c72..50448a71d7 100644 --- a/activemq-cpp/src/main/activemq/exceptions/UnsupportedOperationException.h +++ b/activemq-cpp/src/main/activemq/exceptions/UnsupportedOperationException.h @@ -22,68 +22,66 @@ namespace activemq{ namespace exceptions{ - /* - * Thrown when an unsupported method is called. - */ - class UnsupportedOperationException : public ActiveMQException - { - public: + /* + * Thrown when an unsupported method is called. + */ + class UnsupportedOperationException : public ActiveMQException + { + public: - /** - * Default Constructor - */ - UnsupportedOperationException(void) {}; + /** + * Default Constructor + */ + UnsupportedOperationException(void) {}; - /** - * Conversion Constructor from some other ActiveMQException - * @param An exception that should become this type of Exception - */ - UnsupportedOperationException( const ActiveMQException& ex ){ - *(ActiveMQException*)this = ex; - } + /** + * Conversion Constructor from some other ActiveMQException + * @param An exception that should become this type of Exception + */ + UnsupportedOperationException( const ActiveMQException& ex ){ + *(ActiveMQException*)this = ex; + } - /** - * Copy Constructor - */ - UnsupportedOperationException( const UnsupportedOperationException& ex ){ - *(ActiveMQException*)this = ex; - } + /** + * Copy Constructor + */ + UnsupportedOperationException( const UnsupportedOperationException& ex ){ + *(ActiveMQException*)this = ex; + } - /** - * Constructor - Initializes the file name and line number where - * this message occured. Sets the message to report, using an - * optional list of arguments to parse into the message - * @param file name where exception occurs - * @param line number where the exception occurred. - * @param message to report - * @param list of primitives that are formatted into the message - */ - UnsupportedOperationException(const char* file, const int lineNumber, - const char* msg, ...) - { - va_list vargs ; - va_start(vargs, msg) ; - buildMessage(msg, vargs) ; + /** + * Constructor - Initializes the file name and line number where + * this message occured. Sets the message to report, using an + * optional list of arguments to parse into the message + * @param file name where exception occurs + * @param line number where the exception occurred. + * @param message to report + * @param list of primitives that are formatted into the message + */ + UnsupportedOperationException( const char* file, + const int lineNumber, + const char* msg, ... ) + { + va_list vargs; + va_start( vargs, msg ); + buildMessage( msg, vargs ); - // Set the first mark for this exception. - setMark( file, lineNumber ); - } + // Set the first mark for this exception. + setMark( file, lineNumber ); + } - /** - * Clones this exception. This is useful for cases where you need - * to preserve the type of the original exception as well as the message. - * All subclasses should override. - */ - virtual ActiveMQException* clone() const{ - return new UnsupportedOperationException( *this ); - } + /** + * Clones this exception. This is useful for cases where you need + * to preserve the type of the original exception as well as the message. + * All subclasses should override. + */ + virtual ActiveMQException* clone() const{ + return new UnsupportedOperationException( *this ); + } - /** - * Destructor - */ - virtual ~UnsupportedOperationException(){} + virtual ~UnsupportedOperationException(){} - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/io/BufferedInputStream.cpp b/activemq-cpp/src/main/activemq/io/BufferedInputStream.cpp index 4fd13c1e7f..3a4f18e424 100644 --- a/activemq-cpp/src/main/activemq/io/BufferedInputStream.cpp +++ b/activemq-cpp/src/main/activemq/io/BufferedInputStream.cpp @@ -24,15 +24,15 @@ using namespace std; //////////////////////////////////////////////////////////////////////////////// BufferedInputStream::BufferedInputStream( InputStream* stream ) { - // Default to a 1k buffer. - init( stream, 1024 ); + // Default to a 1k buffer. + init( stream, 1024 ); } //////////////////////////////////////////////////////////////////////////////// BufferedInputStream::BufferedInputStream( InputStream* stream, - const int bufferSize ) + const int bufferSize ) { - init( stream, bufferSize ); + init( stream, bufferSize ); } //////////////////////////////////////////////////////////////////////////////// @@ -47,99 +47,99 @@ BufferedInputStream::~BufferedInputStream() //////////////////////////////////////////////////////////////////////////////// void BufferedInputStream::init( InputStream* stream, const int bufferSize ){ - - this->stream = stream; - this->bufferSize = bufferSize; - - // Create the buffer and initialize the head and tail positions. - buffer = new unsigned char[bufferSize]; - head = 0; - tail = 0; + + this->stream = stream; + this->bufferSize = bufferSize; + + // Create the buffer and initialize the head and tail positions. + buffer = new unsigned char[bufferSize]; + head = 0; + tail = 0; } //////////////////////////////////////////////////////////////////////////////// -void BufferedInputStream::close() throw(cms::CMSException){ - - // Close the delegate stream. - stream->close(); +void BufferedInputStream::close() throw( cms::CMSException ){ + + // Close the delegate stream. + stream->close(); } //////////////////////////////////////////////////////////////////////////////// -unsigned char BufferedInputStream::read() throw (IOException){ - - // If we don't have any data buffered yet - read as much as we can. - if( tail == head ){ - bufferData(); - } - - // Get the next character. - char returnValue = buffer[head++]; - - // If the buffer is now empty - reset it to the beginning of the buffer. - if( tail == head ){ - tail = head = 0; - } - - return returnValue; +unsigned char BufferedInputStream::read() throw ( IOException ){ + + // If we don't have any data buffered yet - read as much as we can. + if( tail == head ){ + bufferData(); + } + + // Get the next character. + char returnValue = buffer[head++]; + + // If the buffer is now empty - reset it to the beginning of the buffer. + if( tail == head ){ + tail = head = 0; + } + + return returnValue; } //////////////////////////////////////////////////////////////////////////////// int BufferedInputStream::read( unsigned char* buffer, - const int bufferSize ) throw (IOException){ - - // If we still haven't filled the output buffer AND there is data - // on the input stream to be read, read a buffer's - // worth from the stream. - int totalRead = 0; - while( totalRead < bufferSize ){ - - // Get the remaining bytes to copy. - int bytesToCopy = min( tail-head, (bufferSize-totalRead) ); - - // Copy the data to the output buffer. - memcpy( buffer+totalRead, this->buffer+head, bytesToCopy ); - - // Increment the total bytes read. - totalRead += bytesToCopy; - - // Increment the head position. If the buffer is now empty, - // reset the positions and buffer more data. - head += bytesToCopy; - if( head == tail ){ - - // Reset the buffer indicies. - head = tail = 0; - - // If there is no more data currently available on the - // input stream, stop the loop. - if( stream->available() == 0 ){ - break; - } - - // Buffer as much data as we can. - bufferData(); - } - } - - // Return the total number of bytes read. - return totalRead; + const int bufferSize ) throw ( IOException ){ + + // If we still haven't filled the output buffer AND there is data + // on the input stream to be read, read a buffer's + // worth from the stream. + int totalRead = 0; + while( totalRead < bufferSize ){ + + // Get the remaining bytes to copy. + int bytesToCopy = min( tail-head, (bufferSize-totalRead) ); + + // Copy the data to the output buffer. + memcpy( buffer+totalRead, this->buffer+head, bytesToCopy ); + + // Increment the total bytes read. + totalRead += bytesToCopy; + + // Increment the head position. If the buffer is now empty, + // reset the positions and buffer more data. + head += bytesToCopy; + if( head == tail ){ + + // Reset the buffer indicies. + head = tail = 0; + + // If there is no more data currently available on the + // input stream, stop the loop. + if( stream->available() == 0 ){ + break; + } + + // Buffer as much data as we can. + bufferData(); + } + } + + // Return the total number of bytes read. + return totalRead; } //////////////////////////////////////////////////////////////////////////////// -void BufferedInputStream::bufferData() throw (IOException){ - - if( tail == bufferSize ){ - throw IOException( __FILE__, __LINE__, +void BufferedInputStream::bufferData() throw ( IOException ){ + + if( tail == bufferSize ){ + throw IOException( __FILE__, __LINE__, "BufferedInputStream::bufferData - buffer full" ); - } - - // Read in as many bytes as we can. - int bytesRead = stream->read( buffer+tail, bufferSize-tail ); - if( bytesRead == 0 ){ - throw IOException( __FILE__, __LINE__, + } + + // Read in as many bytes as we can. + int bytesRead = stream->read( buffer+tail, bufferSize-tail ); + if( bytesRead == 0 ){ + throw IOException( __FILE__, __LINE__, "BufferedInputStream::read() - failed reading bytes from stream"); - } - - // Increment the tail to the new end position. - tail += bytesRead; + } + + // Increment the tail to the new end position. + tail += bytesRead; } diff --git a/activemq-cpp/src/main/activemq/io/BufferedInputStream.h b/activemq-cpp/src/main/activemq/io/BufferedInputStream.h index 85778634c1..b3574b00e5 100644 --- a/activemq-cpp/src/main/activemq/io/BufferedInputStream.h +++ b/activemq-cpp/src/main/activemq/io/BufferedInputStream.h @@ -24,167 +24,174 @@ namespace activemq{ namespace io{ - /** - * A wrapper around another input stream that performs - * a buffered read, where it reads more data than it needs - * in order to reduce the number of io operations on the - * input stream. - */ - class BufferedInputStream : public InputStream - { - private: + /** + * A wrapper around another input stream that performs + * a buffered read, where it reads more data than it needs + * in order to reduce the number of io operations on the + * input stream. + */ + class BufferedInputStream : public InputStream + { + private: - /** - * The target input stream. - */ - InputStream* stream; + /** + * The target input stream. + */ + InputStream* stream; - /** - * The internal buffer. - */ - unsigned char* buffer; + /** + * The internal buffer. + */ + unsigned char* buffer; - /** - * The buffer size. - */ - int bufferSize; + /** + * The buffer size. + */ + int bufferSize; - /** - * The current head of the buffer. - */ - int head; + /** + * The current head of the buffer. + */ + int head; - /** - * The current tail of the buffer. - */ - int tail; + /** + * The current tail of the buffer. + */ + int tail; - public: + public: - /** - * Constructor - * @param stream The target input stream. - */ - BufferedInputStream( InputStream* stream ); + /** + * Constructor + * @param stream The target input stream. + */ + BufferedInputStream( InputStream* stream ); - /** - * Constructor - * @param stream the target input stream - * @param bufferSize the size for the internal buffer. - */ - BufferedInputStream( InputStream* stream, const int bufferSize ); + /** + * Constructor + * @param stream the target input stream + * @param bufferSize the size for the internal buffer. + */ + BufferedInputStream( InputStream* stream, const int bufferSize ); - /** - * Destructor. - */ - virtual ~BufferedInputStream(); + virtual ~BufferedInputStream(); - /** - * Locks the object. - */ - virtual void lock() throw(exceptions::ActiveMQException){ - assert( stream != NULL ); - stream->lock(); - } + /** + * Locks the object. + * throws ActiveMQException + */ + virtual void lock() throw( exceptions::ActiveMQException ){ + assert( stream != NULL ); + stream->lock(); + } - /** - * Unlocks the object. - */ - virtual void unlock() throw(exceptions::ActiveMQException){ - assert( stream != NULL ); - stream->unlock(); - } + /** + * Unlocks the object. + * throws ActiveMQException + */ + virtual void unlock() throw( exceptions::ActiveMQException ){ + assert( stream != NULL ); + stream->unlock(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. - */ - virtual void wait() throw(exceptions::ActiveMQException){ - assert( stream != NULL ); - stream->wait(); - } + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. + * throws ActiveMQException + */ + virtual void wait() throw( exceptions::ActiveMQException ){ + assert( stream != NULL ); + stream->wait(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. This wait will timeout after the specified time - * interval. - * @param time in millisecsonds to wait, or WAIT_INIFINITE - * @throws ActiveMQException - */ - virtual void wait(unsigned long millisecs) - throw(exceptions::ActiveMQException) { + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. This wait will timeout after the specified time + * interval. + * @param time in millisecsonds to wait, or WAIT_INIFINITE + * @throws ActiveMQException + */ + virtual void wait( unsigned long millisecs ) + throw( exceptions::ActiveMQException ) { - assert( stream != NULL ); - stream->wait(millisecs); - } + assert( stream != NULL ); + stream->wait(millisecs); + } - /** - * Signals a waiter on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - */ - virtual void notify() throw(exceptions::ActiveMQException){ - assert( stream != NULL ); - stream->notify(); - } + /** + * Signals a waiter on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + * throws ActiveMQException + */ + virtual void notify() throw( exceptions::ActiveMQException ){ + assert( stream != NULL ); + stream->notify(); + } - /** - * Signals the waiters on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - */ - virtual void notifyAll() throw(exceptions::ActiveMQException){ - assert( stream != NULL ); - stream->notifyAll(); - } + /** + * Signals the waiters on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + * throws ActiveMQException + */ + virtual void notifyAll() throw( exceptions::ActiveMQException ){ + assert( stream != NULL ); + stream->notifyAll(); + } - /** - * Indcates the number of bytes avaialable. - * @return the sum of the amount of data avalable - * in the buffer and the data available on the target - * input stream. - */ - virtual int available() const{ - return (tail-head)+stream->available(); - } + /** + * Indcates the number of bytes avaialable. + * @return the sum of the amount of data avalable + * in the buffer and the data available on the target + * input stream. + */ + virtual int available() const{ + return ( tail - head ) + stream->available(); + } - /** - * Reads a single byte from the buffer. - * @return The next byte. - * @throws IOException thrown if an error occurs. - */ - virtual unsigned char read() throw (IOException); + /** + * Reads a single byte from the buffer. + * @return The next byte. + * @throws IOException thrown if an error occurs. + */ + virtual unsigned char read() throw ( IOException ); - /** - * Reads an array of bytes from the buffer. - * @param buffer (out) the target buffer. - * @param bufferSize the size of the output buffer. - * @return The number of bytes read. - * @throws IOException thrown if an error occurs. - */ - virtual int read( unsigned char* buffer, const int bufferSize ) throw (IOException); + /** + * Reads an array of bytes from the buffer. + * @param buffer (out) the target buffer. + * @param bufferSize the size of the output buffer. + * @return The number of bytes read. + * @throws IOException thrown if an error occurs. + */ + virtual int read( unsigned char* buffer, const int bufferSize ) + throw ( IOException ); - /** - * Closes the target input stream. - */ - virtual void close(void) throw(cms::CMSException); + /** + * Closes the target input stream. + * @throws CMSException + */ + virtual void close(void) throw( cms::CMSException ); - private: + private: - /** - * Initializes the internal structures. - */ - void init( InputStream* stream, const int bufferSize ); + /** + * Initializes the internal structures. + * @param stream to read from + * @param size of buffer to allocate + */ + void init( InputStream* stream, const int bufferSize ); - /** - * Populates the buffer with as much data as possible - * from the target input stream. - */ - void bufferData(void) throw (IOException); + /** + * Populates the buffer with as much data as possible + * from the target input stream. + * @throws CMSException + */ + void bufferData(void) throw ( IOException ); - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/io/BufferedOutputStream.cpp b/activemq-cpp/src/main/activemq/io/BufferedOutputStream.cpp index 3a19076ed1..87dc5cc3c9 100644 --- a/activemq-cpp/src/main/activemq/io/BufferedOutputStream.cpp +++ b/activemq-cpp/src/main/activemq/io/BufferedOutputStream.cpp @@ -24,15 +24,15 @@ using namespace std; //////////////////////////////////////////////////////////////////////////////// BufferedOutputStream::BufferedOutputStream( OutputStream* stream ) { - // Default to 1k buffer. - init( stream, 1024 ); + // Default to 1k buffer. + init( stream, 1024 ); } //////////////////////////////////////////////////////////////////////////////// BufferedOutputStream::BufferedOutputStream( OutputStream* stream, - const int bufSize ) + const int bufSize ) { - init( stream, bufSize ); + init( stream, bufSize ); } //////////////////////////////////////////////////////////////////////////////// @@ -47,75 +47,74 @@ BufferedOutputStream::~BufferedOutputStream() //////////////////////////////////////////////////////////////////////////////// void BufferedOutputStream::init( OutputStream* stream, const int bufSize ){ - - this->stream = stream; - this->bufferSize = bufSize; - - buffer = new unsigned char[bufSize]; - head = tail = 0; + + this->stream = stream; + this->bufferSize = bufSize; + + buffer = new unsigned char[bufSize]; + head = tail = 0; } //////////////////////////////////////////////////////////////////////////////// -void BufferedOutputStream::close() throw(cms::CMSException){ - - // Flush this stream. - flush(); - - // Close the delegate stream. - stream->close(); +void BufferedOutputStream::close() throw( cms::CMSException ){ + + // Flush this stream. + flush(); + + // Close the delegate stream. + stream->close(); } //////////////////////////////////////////////////////////////////////////////// -void BufferedOutputStream::emptyBuffer() throw (IOException){ - - if( head != tail ){ - stream->write( buffer+head, tail-head ); - } - head = tail = 0; +void BufferedOutputStream::emptyBuffer() throw ( IOException ){ + + if( head != tail ){ + stream->write( buffer+head, tail-head ); + } + head = tail = 0; } - + //////////////////////////////////////////////////////////////////////////////// -void BufferedOutputStream::flush() throw (IOException){ - - // Empty the contents of the buffer to the output stream. - emptyBuffer(); - - // Flush the output stream. - stream->flush(); +void BufferedOutputStream::flush() throw ( IOException ){ + + // Empty the contents of the buffer to the output stream. + emptyBuffer(); + + // Flush the output stream. + stream->flush(); } //////////////////////////////////////////////////////////////////////////////// -void BufferedOutputStream::write( const unsigned char c ) throw (IOException){ - - if( tail >= bufferSize ){ - emptyBuffer(); - } - - buffer[tail++] = c; +void BufferedOutputStream::write( const unsigned char c ) throw ( IOException ){ + + if( tail >= bufferSize ){ + emptyBuffer(); + } + + buffer[tail++] = c; } -//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// void BufferedOutputStream::write( const unsigned char* buffer, const int len ) - throw (IOException) -{ - // Iterate until all the data is written. - for( int pos=0; pos < len; ){ - - if( tail >= bufferSize ){ - emptyBuffer(); - } - - // Get the number of bytes left to write. - int bytesToWrite = min( bufferSize-tail, len-pos ); - - // Copy the data. - memcpy( this->buffer+tail, buffer+pos, bytesToWrite ); - - // Increase the tail position. - tail += bytesToWrite; - - // Decrease the number of bytes to write. - pos += bytesToWrite; - } + throw ( IOException ) +{ + // Iterate until all the data is written. + for( int pos=0; pos < len; ){ + + if( tail >= bufferSize ){ + emptyBuffer(); + } + + // Get the number of bytes left to write. + int bytesToWrite = min( bufferSize-tail, len-pos ); + + // Copy the data. + memcpy( this->buffer+tail, buffer+pos, bytesToWrite ); + + // Increase the tail position. + tail += bytesToWrite; + + // Decrease the number of bytes to write. + pos += bytesToWrite; + } } - diff --git a/activemq-cpp/src/main/activemq/io/BufferedOutputStream.h b/activemq-cpp/src/main/activemq/io/BufferedOutputStream.h index 816aba8a92..8d685c7da6 100644 --- a/activemq-cpp/src/main/activemq/io/BufferedOutputStream.h +++ b/activemq-cpp/src/main/activemq/io/BufferedOutputStream.h @@ -24,156 +24,161 @@ namespace activemq{ namespace io{ - /** - * Wrapper around another output stream that buffers - * output before writing to the target output stream. - */ - class BufferedOutputStream : public OutputStream - { - private: + /** + * Wrapper around another output stream that buffers + * output before writing to the target output stream. + */ + class BufferedOutputStream : public OutputStream + { + private: - /** - * The target output stream. - */ - OutputStream* stream; + /** + * The target output stream. + */ + OutputStream* stream; - /** - * The internal buffer. - */ - unsigned char* buffer; + /** + * The internal buffer. + */ + unsigned char* buffer; - /** - * The size of the internal buffer. - */ - int bufferSize; + /** + * The size of the internal buffer. + */ + int bufferSize; - /** - * The current head of the buffer. - */ - int head; + /** + * The current head of the buffer. + */ + int head; - /** - * The current tail of the buffer. - */ - int tail; + /** + * The current tail of the buffer. + */ + int tail; - public: + public: - /** - * Constructor. - * @param stream the target output stream. - */ - BufferedOutputStream( OutputStream* stream ); + /** + * Constructor. + * @param stream the target output stream. + */ + BufferedOutputStream( OutputStream* stream ); - /** - * Constructor - * @param stream the target output stream. - * @param bufSize the size for the internal buffer. - */ - BufferedOutputStream( OutputStream* stream, const int bufSize ); + /** + * Constructor + * @param stream the target output stream. + * @param bufSize the size for the internal buffer. + */ + BufferedOutputStream( OutputStream* stream, const int bufSize ); - /** - * Destructor - */ - virtual ~BufferedOutputStream(); + virtual ~BufferedOutputStream(); - /** - * Locks the object. - */ - virtual void lock() throw(exceptions::ActiveMQException){ - assert( stream != NULL ); - stream->lock(); - } + /** + * Locks the object. + * @throws ActiveMQException + */ + virtual void lock() throw( exceptions::ActiveMQException ){ + assert( stream != NULL ); + stream->lock(); + } - /** - * Unlocks the object. - */ - virtual void unlock() throw(exceptions::ActiveMQException){ - assert( stream != NULL ); - stream->unlock(); - } + /** + * Unlocks the object. + * @throws ActiveMQException + */ + virtual void unlock() throw( exceptions::ActiveMQException ){ + assert( stream != NULL ); + stream->unlock(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. - */ - virtual void wait() throw(exceptions::ActiveMQException){ - assert( stream != NULL ); - stream->wait(); - } + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void wait() throw( exceptions::ActiveMQException ){ + assert( stream != NULL ); + stream->wait(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. This wait will timeout after the specified time - * interval. - * @param time in millisecsonds to wait, or WAIT_INIFINITE - * @throws ActiveMQException - */ - virtual void wait(unsigned long millisecs) - throw(exceptions::ActiveMQException) { + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. This wait will timeout after the specified time + * interval. + * @param time in millisecsonds to wait, or WAIT_INIFINITE + * @throws ActiveMQException + */ + virtual void wait( unsigned long millisecs ) + throw( exceptions::ActiveMQException ) { - assert( stream != NULL ); - stream->wait(millisecs); - } + assert( stream != NULL ); + stream->wait( millisecs ); + } - /** - * Signals a waiter on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - */ - virtual void notify() throw(exceptions::ActiveMQException){ - assert( stream != NULL ); - stream->notify(); - } + /** + * Signals a waiter on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void notify() throw( exceptions::ActiveMQException ){ + assert( stream != NULL ); + stream->notify(); + } - /** - * Signals the waiters on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - */ - virtual void notifyAll() throw(exceptions::ActiveMQException){ - assert( stream != NULL ); - stream->notifyAll(); - } + /** + * Signals the waiters on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void notifyAll() throw( exceptions::ActiveMQException ){ + assert( stream != NULL ); + stream->notifyAll(); + } - /** - * Writes a single byte to the output stream. - * @param c the byte. - * @throws IOException thrown if an error occurs. - */ - virtual void write( const unsigned char c ) throw (IOException); + /** + * Writes a single byte to the output stream. + * @param c the byte. + * @throws IOException thrown if an error occurs. + */ + virtual void write( const unsigned char c ) throw ( IOException ); - /** - * Writes an array of bytes to the output stream. - * @param buffer The array of bytes to write. - * @param len The number of bytes from the buffer to be written. - * @throws IOException thrown if an error occurs. - */ - virtual void write( const unsigned char* buffer, const int len ) throw (IOException); + /** + * Writes an array of bytes to the output stream. + * @param buffer The array of bytes to write. + * @param len The number of bytes from the buffer to be written. + * @throws IOException thrown if an error occurs. + */ + virtual void write( const unsigned char* buffer, const int len ) throw ( IOException ); - /** - * Invokes flush on the target output stream. - */ - virtual void flush() throw (IOException); + /** + * Invokes flush on the target output stream. + * @throws IOException thrown if an error occurs. + */ + virtual void flush() throw ( IOException ); - /** - * Invokes close on the target output stream. - */ - void close() throw(cms::CMSException); + /** + * Invokes close on the target output stream. + * @throws CMSException thrown if an error occurs. + */ + void close() throw( cms::CMSException ); private: - /** - * Initializes the internal structures. - */ - void init( OutputStream* stream, const int bufSize ); + /** + * Initializes the internal structures. + */ + void init( OutputStream* stream, const int bufSize ); - /** - * Writes the contents of the buffer to the output stream. - */ - void emptyBuffer() throw (IOException); + /** + * Writes the contents of the buffer to the output stream. + */ + void emptyBuffer() throw ( IOException ); + }; }} diff --git a/activemq-cpp/src/main/activemq/io/ByteArrayInputStream.cpp b/activemq-cpp/src/main/activemq/io/ByteArrayInputStream.cpp index 014b495bc8..c2cba1894e 100644 --- a/activemq-cpp/src/main/activemq/io/ByteArrayInputStream.cpp +++ b/activemq-cpp/src/main/activemq/io/ByteArrayInputStream.cpp @@ -24,14 +24,14 @@ using namespace std; //////////////////////////////////////////////////////////////////////////////// ByteArrayInputStream::ByteArrayInputStream() { - pos = buffer.end(); + pos = buffer.end(); } //////////////////////////////////////////////////////////////////////////////// ByteArrayInputStream::ByteArrayInputStream( const unsigned char* buffer, int bufferSize ) { - setByteArray( buffer, bufferSize ); + setByteArray( buffer, bufferSize ); } //////////////////////////////////////////////////////////////////////////////// @@ -43,54 +43,54 @@ ByteArrayInputStream::~ByteArrayInputStream(void) void ByteArrayInputStream::setByteArray( const unsigned char* buffer, int bufferSize ) { - // Remove old data - this->buffer.clear(); + // Remove old data + this->buffer.clear(); - // Copy data to internal buffer. - for( int ix = 0; ix < bufferSize; ++ix ) - { - this->buffer.push_back(buffer[ix]); - } + // Copy data to internal buffer. + for( int ix = 0; ix < bufferSize; ++ix ) + { + this->buffer.push_back(buffer[ix]); + } - // Begin at the Beginning. - pos = this->buffer.begin(); + // Begin at the Beginning. + pos = this->buffer.begin(); } //////////////////////////////////////////////////////////////////////////////// -void ByteArrayInputStream::close() throw(cms::CMSException){ - - // Close the delegate stream. - buffer.clear(); +void ByteArrayInputStream::close() throw( cms::CMSException ){ + + // Close the delegate stream. + buffer.clear(); } //////////////////////////////////////////////////////////////////////////////// -unsigned char ByteArrayInputStream::read() throw (IOException) +unsigned char ByteArrayInputStream::read() throw ( IOException ) { - if(pos != buffer.end()) - { - return *(pos++); - } + if(pos != buffer.end()) + { + return *(pos++); + } - throw IOException( __FILE__, __LINE__, - "ByteArrayInputStream::read: Out of Data"); + throw IOException( __FILE__, __LINE__, + "ByteArrayInputStream::read: Out of Data"); } //////////////////////////////////////////////////////////////////////////////// int ByteArrayInputStream::read( unsigned char* buffer, - const int bufferSize ) - throw (IOException) + const int bufferSize ) + throw ( IOException ) { - int ix = 0; + int ix = 0; - for( ; ix < bufferSize; ++ix, ++pos) - { - if(pos == this->buffer.end()) - { - break; - } + for( ; ix < bufferSize; ++ix, ++pos) + { + if(pos == this->buffer.end()) + { + break; + } - buffer[ix] = *(pos); - } + buffer[ix] = *(pos); + } - return ix; + return ix; } diff --git a/activemq-cpp/src/main/activemq/io/ByteArrayInputStream.h b/activemq-cpp/src/main/activemq/io/ByteArrayInputStream.h index 84d524351b..e75b09075a 100644 --- a/activemq-cpp/src/main/activemq/io/ByteArrayInputStream.h +++ b/activemq-cpp/src/main/activemq/io/ByteArrayInputStream.h @@ -26,147 +26,145 @@ namespace activemq{ namespace io{ - class ByteArrayInputStream : public InputStream - { - private: + class ByteArrayInputStream : public InputStream + { + private: - /** - * The Array of Bytes to read from. - */ - std::vector buffer; + /** + * The Array of Bytes to read from. + */ + std::vector buffer; - /** - * iterator to current position in buffer. - */ - std::vector::const_iterator pos; + /** + * iterator to current position in buffer. + */ + std::vector::const_iterator pos; - /** - * Synchronization object. - */ - concurrent::Mutex mutex; + /** + * Synchronization object. + */ + concurrent::Mutex mutex; - public: + public: - /** - * Constructor - */ - ByteArrayInputStream(void); + /** + * Default Constructor + */ + ByteArrayInputStream(void); - /** - * Constructor - * @param initial byte array to use to read from - * @param the size of the buffer - */ - ByteArrayInputStream( const unsigned char* buffer, - int bufferSize ); + /** + * Constructor + * @param initial byte array to use to read from + * @param the size of the buffer + */ + ByteArrayInputStream( const unsigned char* buffer, + int bufferSize ); - /** - * Destructor - */ - virtual ~ByteArrayInputStream(void); + virtual ~ByteArrayInputStream(void); - /** - * Sets the data that this reader uses, replaces any existing - * data and resets to beginning of the buffer. - * @param initial byte array to use to read from - * @param the size of the buffer - */ - virtual void setByteArray( const unsigned char* buffer, - int bufferSize ); + /** + * Sets the data that this reader uses, replaces any existing + * data and resets to beginning of the buffer. + * @param initial byte array to use to read from + * @param the size of the buffer + */ + virtual void setByteArray( const unsigned char* buffer, + int bufferSize ); - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void lock() throw(exceptions::ActiveMQException){ - mutex.lock(); - } + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void lock() throw(exceptions::ActiveMQException){ + mutex.lock(); + } - /** - * Unlocks the object. - * @throws ActiveMQException - */ - virtual void unlock() throw(exceptions::ActiveMQException){ - mutex.unlock(); - } + /** + * Unlocks the object. + * @throws ActiveMQException + */ + virtual void unlock() throw(exceptions::ActiveMQException){ + mutex.unlock(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void wait() throw(exceptions::ActiveMQException){ - mutex.wait(); - } + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void wait() throw(exceptions::ActiveMQException){ + mutex.wait(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. This wait will timeout after the specified time - * interval. - * @param time in millisecsonds to wait, or WAIT_INIFINITE - * @throws ActiveMQException - */ - virtual void wait(unsigned long millisecs) throw(exceptions::ActiveMQException){ - mutex.wait(millisecs); - } + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. This wait will timeout after the specified time + * interval. + * @param time in millisecsonds to wait, or WAIT_INIFINITE + * @throws ActiveMQException + */ + virtual void wait(unsigned long millisecs) throw(exceptions::ActiveMQException){ + mutex.wait(millisecs); + } - /** - * Signals a waiter on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void notify() throw(exceptions::ActiveMQException){ - mutex.notify(); - } - - /** - * Signals the waiters on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void notifyAll() throw(exceptions::ActiveMQException){ - mutex.notifyAll(); - } + /** + * Signals a waiter on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void notify() throw(exceptions::ActiveMQException){ + mutex.notify(); + } + + /** + * Signals the waiters on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void notifyAll() throw(exceptions::ActiveMQException){ + mutex.notifyAll(); + } - /** - * Indcates the number of bytes avaialable. - * @return the sum of the amount of data avalable - * in the buffer and the data available on the target - * input stream. - */ - virtual int available() const{ - return distance(pos, buffer.end()); - } + /** + * Indcates the number of bytes avaialable. + * @return the sum of the amount of data avalable + * in the buffer and the data available on the target + * input stream. + */ + virtual int available() const{ + return distance(pos, buffer.end()); + } - /** - * Reads a single byte from the buffer. - * @return The next byte. - * @throws IOException thrown if an error occurs. - */ - virtual unsigned char read() throw (IOException); + /** + * Reads a single byte from the buffer. + * @return The next byte. + * @throws IOException thrown if an error occurs. + */ + virtual unsigned char read() throw (IOException); - /** - * Reads an array of bytes from the buffer. - * @param buffer (out) the target buffer. - * @param bufferSize the size of the output buffer. - * @return The number of bytes read. - * @throws IOException thrown if an error occurs. - */ - virtual int read( unsigned char* buffer, const int bufferSize ) - throw (IOException); + /** + * Reads an array of bytes from the buffer. + * @param buffer (out) the target buffer. + * @param bufferSize the size of the output buffer. + * @return The number of bytes read. + * @throws IOException thrown if an error occurs. + */ + virtual int read( unsigned char* buffer, const int bufferSize ) + throw (IOException); - /** - * Closes the target input stream. - */ - virtual void close() throw(cms::CMSException); + /** + * Closes the target input stream. + * @throws IOException thrown if an error occurs. + */ + virtual void close() throw(cms::CMSException); - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/io/ByteArrayOutputStream.cpp b/activemq-cpp/src/main/activemq/io/ByteArrayOutputStream.cpp index eb1ecfe1b0..d9c7442de2 100644 --- a/activemq-cpp/src/main/activemq/io/ByteArrayOutputStream.cpp +++ b/activemq-cpp/src/main/activemq/io/ByteArrayOutputStream.cpp @@ -22,41 +22,39 @@ using namespace activemq::io; using namespace std; //////////////////////////////////////////////////////////////////////////////// -void ByteArrayOutputStream::close() throw(cms::CMSException) +void ByteArrayOutputStream::close() throw( cms::CMSException ) { - // Clear the Buffer - flush(); + // Clear the Buffer + flush(); } //////////////////////////////////////////////////////////////////////////////// -void ByteArrayOutputStream::flush() throw (IOException) -{ - // No Op -} +void ByteArrayOutputStream::flush() throw ( IOException ) +{} //////////////////////////////////////////////////////////////////////////////// -void ByteArrayOutputStream::clear() throw (IOException) +void ByteArrayOutputStream::clear() throw ( IOException ) { - // Empty the contents of the buffer to the output stream. - buffer.clear(); + // Empty the contents of the buffer to the output stream. + buffer.clear(); } //////////////////////////////////////////////////////////////////////////////// void ByteArrayOutputStream::write( const unsigned char c ) - throw (IOException) + throw ( IOException ) { - buffer.push_back( c ); + buffer.push_back( c ); } //////////////////////////////////////////////////////////////////////////////// void ByteArrayOutputStream::write( const unsigned char* buffer, const int len ) - throw (IOException) + throw ( IOException ) { - // Iterate until all the data is written. - for( int ix = 0; ix < len; ++ix) - { - this->buffer.push_back( buffer[ix] ); - } + // Iterate until all the data is written. + for( int ix = 0; ix < len; ++ix) + { + this->buffer.push_back( buffer[ix] ); + } } diff --git a/activemq-cpp/src/main/activemq/io/ByteArrayOutputStream.h b/activemq-cpp/src/main/activemq/io/ByteArrayOutputStream.h index 9d97bafc03..4ab4740780 100644 --- a/activemq-cpp/src/main/activemq/io/ByteArrayOutputStream.h +++ b/activemq-cpp/src/main/activemq/io/ByteArrayOutputStream.h @@ -25,143 +25,142 @@ namespace activemq{ namespace io{ - class ByteArrayOutputStream : public OutputStream - { - private: + class ByteArrayOutputStream : public OutputStream + { + private: - /** - * The Array of Bytes to read from. - */ - std::vector buffer; + /** + * The Array of Bytes to read from. + */ + std::vector buffer; - /** - * Synchronization object. - */ - concurrent::Mutex mutex; + /** + * Synchronization object. + */ + concurrent::Mutex mutex; - public: + public: - /** - * Constructor - */ - ByteArrayOutputStream(void) {}; + /** + * Default Constructor + */ + ByteArrayOutputStream(void) {}; - /** - * Destructor - */ - virtual ~ByteArrayOutputStream(void) {}; + /** + * Destructor + */ + virtual ~ByteArrayOutputStream(void) {}; - /** - * Get a snapshot of the data - * @return pointer to the data - */ - virtual const unsigned char* getByteArray(void) const - { - return &buffer[0]; - } + /** + * Get a snapshot of the data + * @return pointer to the data + */ + virtual const unsigned char* getByteArray(void) const { + return &buffer[0]; + } - /** - * Get the Size of the Internal Buffer - */ - virtual int getByteArraySize(void) const - { - return buffer.size(); - } + /** + * Get the Size of the Internal Buffer + * @return size of the internal buffer + */ + virtual int getByteArraySize(void) const { + return buffer.size(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void lock() throw(exceptions::ActiveMQException){ - mutex.lock(); - } + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void lock() throw( exceptions::ActiveMQException ){ + mutex.lock(); + } - /** - * Unlocks the object. - * @throws ActiveMQException - */ - virtual void unlock() throw(exceptions::ActiveMQException){ - mutex.unlock(); - } + /** + * Unlocks the object. + * @throws ActiveMQException + */ + virtual void unlock() throw( exceptions::ActiveMQException ){ + mutex.unlock(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void wait() throw(exceptions::ActiveMQException){ - mutex.wait(); - } + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void wait() throw( exceptions::ActiveMQException ){ + mutex.wait(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. This wait will timeout after the specified time - * interval. - * @param time in millisecsonds to wait, or WAIT_INIFINITE - * @throws ActiveMQException - */ - virtual void wait(unsigned long millisecs) throw(exceptions::ActiveMQException){ - mutex.wait(millisecs); - } + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. This wait will timeout after the specified time + * interval. + * @param time in millisecsonds to wait, or WAIT_INIFINITE + * @throws ActiveMQException + */ + virtual void wait( unsigned long millisecs ) throw( exceptions::ActiveMQException ){ + mutex.wait(millisecs); + } - /** - * Signals a waiter on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void notify() throw(exceptions::ActiveMQException){ - mutex.notify(); - } + /** + * Signals a waiter on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void notify() throw( exceptions::ActiveMQException ){ + mutex.notify(); + } - /** - * Signals the waiters on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void notifyAll() throw(exceptions::ActiveMQException){ - mutex.notifyAll(); - } + /** + * Signals the waiters on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void notifyAll() throw( exceptions::ActiveMQException ){ + mutex.notifyAll(); + } - /** - * Writes a single byte to the output stream. - * @param c the byte. - * @throws IOException thrown if an error occurs. - */ - virtual void write( const unsigned char c ) - throw (IOException); + /** + * Writes a single byte to the output stream. + * @param c the byte. + * @throws IOException thrown if an error occurs. + */ + virtual void write( const unsigned char c ) + throw ( IOException ); - /** - * Writes an array of bytes to the output stream. - * @param buffer The array of bytes to write. - * @param len The number of bytes from the buffer to be written. - * @throws IOException thrown if an error occurs. - */ - virtual void write( const unsigned char* buffer, const int len ) - throw (IOException); + /** + * Writes an array of bytes to the output stream. + * @param buffer The array of bytes to write. + * @param len The number of bytes from the buffer to be written. + * @throws IOException thrown if an error occurs. + */ + virtual void write( const unsigned char* buffer, const int len ) + throw ( IOException ); - /** - * Invokes flush on the target output stream, has no affect. - * @throws IOException - */ - virtual void flush( void ) throw (IOException); + /** + * Invokes flush on the target output stream, has no affect. + * @throws IOException + */ + virtual void flush( void ) throw ( IOException ); - /** - * Clear current Stream contents - * @throws IOException - */ - virtual void clear( void ) throw (IOException); + /** + * Clear current Stream contents + * @throws IOException + */ + virtual void clear( void ) throw ( IOException ); - /** - * Invokes close on the target output stream. - * @throws CMSException - */ - void close( void ) throw(cms::CMSException); + /** + * Invokes close on the target output stream. + * @throws CMSException + */ + void close( void ) throw( cms::CMSException ); }; diff --git a/activemq-cpp/src/main/activemq/io/EndianReader.cpp b/activemq-cpp/src/main/activemq/io/EndianReader.cpp index 4e4d6eea77..c3b71deeda 100644 --- a/activemq-cpp/src/main/activemq/io/EndianReader.cpp +++ b/activemq-cpp/src/main/activemq/io/EndianReader.cpp @@ -35,37 +35,35 @@ EndianReader::EndianReader( InputStream* is ) //////////////////////////////////////////////////////////////////////////////// EndianReader::~EndianReader() -{ - // no-op -} +{} //////////////////////////////////////////////////////////////////////////////// -unsigned char EndianReader::readByte() throw(IOException) +unsigned char EndianReader::readByte() throw( IOException ) { unsigned char value ; // Read a single byte - read(&value, sizeof(unsigned char)) ; - return value ; + read(&value, sizeof(unsigned char)); + return value; } //////////////////////////////////////////////////////////////////////////////// -double EndianReader::readDouble() throw(IOException) +double EndianReader::readDouble() throw( IOException ) { - double value ; + double value; // Read a double and convert from big endian to little endian if necessary - read((unsigned char*)&value, sizeof(double) ) ; + read( (unsigned char*)&value, sizeof( double ) ); return Endian::byteSwap(value) ; } //////////////////////////////////////////////////////////////////////////////// -float EndianReader::readFloat() throw(IOException) +float EndianReader::readFloat() throw( IOException ) { float value ; // Read a float and convert from big endian to little endian if necessary - read((unsigned char*)&value, sizeof(float)) ; + read( (unsigned char*)&value, sizeof( float ) ); return Endian::byteSwap(value) ; } @@ -85,18 +83,18 @@ uint32_t EndianReader::readUInt32() throw(IOException) uint32_t value; // Read an int and convert from big endian to little endian if necessary - read((unsigned char*)&value, sizeof(value)) ; - return Endian::byteSwap(value) ; + read( (unsigned char*)&value, sizeof( value ) ); + return Endian::byteSwap(value); } //////////////////////////////////////////////////////////////////////////////// uint64_t EndianReader::readUInt64() throw(IOException) { - uint64_t value ; + uint64_t value; // Read a long long and convert from big endian to little endian if necessary - read((unsigned char*)&value, sizeof(value)) ; - return Endian::byteSwap(value) ; + read( (unsigned char*)&value, sizeof( value ) ); + return Endian::byteSwap(value); } //////////////////////////////////////////////////////////////////////////////// @@ -118,7 +116,7 @@ uint64_t EndianReader::readUInt64() throw(IOException) }*/ //////////////////////////////////////////////////////////////////////////////// -int EndianReader::read(unsigned char* buffer, int count) throw(IOException){ +int EndianReader::read( unsigned char* buffer, int count ) throw( IOException ){ if( inputStream == NULL ){ throw IOException( __FILE__, __LINE__, diff --git a/activemq-cpp/src/main/activemq/io/EndianReader.h b/activemq-cpp/src/main/activemq/io/EndianReader.h index cfd299ce51..657ce905a2 100644 --- a/activemq-cpp/src/main/activemq/io/EndianReader.h +++ b/activemq-cpp/src/main/activemq/io/EndianReader.h @@ -23,109 +23,110 @@ namespace activemq{ namespace io{ - /* - * The BinaryReader class reads primitive C++ data types from an - * underlying input stream in a Java compatible way. Strings are - * read as raw bytes, no character decoding is performed. - * - * All numeric data types are assumed to be available in big - * endian (network byte order) and are converted automatically - * to little endian if needed by the platform. - * - * Should any error occur an IOException will be thrown. - */ - class EndianReader : public Reader - { - private: - - /** - * The target input stream. - */ - InputStream* inputStream; - - public: - - /** - * Constructor. - */ - EndianReader(); - - /** - * Constructor. - * @param is the target input stream. - */ - EndianReader( InputStream* is ); - - /** - * Destructor. - */ - virtual ~EndianReader(); - - /** - * Sets the target input stream. - */ - virtual void setInputStream( InputStream* is ){ - inputStream = is; - } - - /** - * Gets the target input stream. - */ - virtual InputStream* getInputStream(){ - return inputStream; - } - - /** - * Attempts to read an array of bytes from the stream. - * @param buffer The target byte buffer. - * @param count The number of bytes to read. - * @return The number of bytes read. - * @throws IOException thrown if an error occurs. - */ - virtual int read(unsigned char* buffer, int count) throw(IOException); - - /** - * Attempts to read a byte from the input stream - * @return The byte. - * @throws IOException thrown if an error occurs. - */ - virtual unsigned char readByte() throw(IOException); - - /** - * Attempts to read a double from the input stream - * @return The byte. - * @throws IOException thrown if an error occurs. - */ - virtual double readDouble() throw(IOException); - - /** - * Attempts to read a float from the input stream - * @return The byte. - * @throws IOException thrown if an error occurs. - */ - virtual float readFloat() throw(IOException); - - /** - * Attempts to read a short from the input stream - * @return The byte. - * @throws IOException thrown if an error occurs. - */ - virtual uint16_t readUInt16() throw(IOException); - - /** - * Attempts to read an int from the input stream - * @return The byte. - * @throws IOException thrown if an error occurs. - */ - virtual uint32_t readUInt32() throw(IOException); - - /** - * Attempts to read a long long from the input stream - * @return The byte. - * @throws IOException thrown if an error occurs. - */ - virtual uint64_t readUInt64() throw(IOException); - }; + /* + * The EndianReader class reads primitive C++ data types from an + * underlying input stream in a Java compatible way. Strings are + * read as raw bytes, no character decoding is performed. + * + * All numeric data types are assumed to be available in big + * endian (network byte order) and are converted automatically + * to little endian if needed by the platform. + * + * Should any error occur an IOException will be thrown. + */ + class EndianReader : public Reader + { + private: + + /** + * The target input stream. + */ + InputStream* inputStream; + + public: + + /** + * Constructor. + */ + EndianReader(); + + /** + * Constructor. + * @param is the target input stream. + */ + EndianReader( InputStream* is ); + + /** + * Destructor. + */ + virtual ~EndianReader(); + + /** + * Sets the target input stream. + */ + virtual void setInputStream( InputStream* is ){ + inputStream = is; + } + + /** + * Gets the target input stream. + */ + virtual InputStream* getInputStream(){ + return inputStream; + } + + /** + * Attempts to read an array of bytes from the stream. + * @param buffer The target byte buffer. + * @param count The number of bytes to read. + * @return The number of bytes read. + * @throws IOException thrown if an error occurs. + */ + virtual int read( unsigned char* buffer, int count ) + throw( IOException ); + + /** + * Attempts to read a byte from the input stream + * @return The byte. + * @throws IOException thrown if an error occurs. + */ + virtual unsigned char readByte() throw( IOException ); + + /** + * Attempts to read a double from the input stream + * @return The byte. + * @throws IOException thrown if an error occurs. + */ + virtual double readDouble() throw( IOException ); + + /** + * Attempts to read a float from the input stream + * @return The byte. + * @throws IOException thrown if an error occurs. + */ + virtual float readFloat() throw( IOException ); + + /** + * Attempts to read a short from the input stream + * @return The byte. + * @throws IOException thrown if an error occurs. + */ + virtual uint16_t readUInt16() throw( IOException ); + + /** + * Attempts to read an int from the input stream + * @return The byte. + * @throws IOException thrown if an error occurs. + */ + virtual uint32_t readUInt32() throw( IOException ); + + /** + * Attempts to read a long long from the input stream + * @return The byte. + * @throws IOException thrown if an error occurs. + */ + virtual uint64_t readUInt64() throw( IOException ); + }; }} diff --git a/activemq-cpp/src/main/activemq/io/EndianWriter.cpp b/activemq-cpp/src/main/activemq/io/EndianWriter.cpp index f5ec7baf2b..bf544e5146 100644 --- a/activemq-cpp/src/main/activemq/io/EndianWriter.cpp +++ b/activemq-cpp/src/main/activemq/io/EndianWriter.cpp @@ -35,43 +35,41 @@ EndianWriter::EndianWriter( OutputStream* os ) //////////////////////////////////////////////////////////////////////////////// EndianWriter::~EndianWriter() -{ - // no-op -} +{} //////////////////////////////////////////////////////////////////////////////// -void EndianWriter::writeByte(unsigned char value) throw(IOException) +void EndianWriter::writeByte( unsigned char value ) throw( IOException ) { // Write a single byte - write(&value, sizeof(unsigned char)); + write( &value, sizeof(unsigned char) ); } //////////////////////////////////////////////////////////////////////////////// -void EndianWriter::writeDouble(double v) throw(IOException) +void EndianWriter::writeDouble( double v ) throw( IOException ) { // Write a double, byteswap if necessary double value = Endian::byteSwap(v); - write((unsigned char*)&value, sizeof(value)); + write( (unsigned char*)&value, sizeof(value) ); } //////////////////////////////////////////////////////////////////////////////// -void EndianWriter::writeFloat(float v) throw(IOException) +void EndianWriter::writeFloat( float v ) throw( IOException ) { // Write a float, byteswap if necessary float value = Endian::byteSwap(v); - write((unsigned char*)&value, sizeof(value)); + write( (unsigned char*)&value, sizeof(value) ); } //////////////////////////////////////////////////////////////////////////////// -void EndianWriter::writeUInt16(uint16_t v) throw(IOException) +void EndianWriter::writeUInt16( uint16_t v ) throw( IOException ) { // Write a short, byteswap if necessary uint16_t value = Endian::byteSwap(v) ; - write((unsigned char*)&value, sizeof(value)); + write( (unsigned char*)&value, sizeof(value) ); } //////////////////////////////////////////////////////////////////////////////// -void EndianWriter::writeUInt32(uint32_t v) throw(IOException) +void EndianWriter::writeUInt32( uint32_t v ) throw( IOException ) { // Write an int, byteswap if necessary uint32_t value = Endian::byteSwap(v); @@ -79,11 +77,11 @@ void EndianWriter::writeUInt32(uint32_t v) throw(IOException) } //////////////////////////////////////////////////////////////////////////////// -void EndianWriter::writeUInt64(uint64_t v) throw(IOException) +void EndianWriter::writeUInt64( uint64_t v ) throw( IOException ) { // Write a long long, byteswap if necessary uint64_t value = Endian::byteSwap(v); - write((unsigned char*)&value, sizeof(value)); + write( (unsigned char*)&value, sizeof(value) ); } //////////////////////////////////////////////////////////////////////////////// @@ -103,7 +101,7 @@ void EndianWriter::writeUInt64(uint64_t v) throw(IOException) }*/ //////////////////////////////////////////////////////////////////////////////// -void EndianWriter::write(const unsigned char* buffer, int count) throw(IOException){ +void EndianWriter::write( const unsigned char* buffer, int count ) throw( IOException ){ if( outputStream == NULL ){ throw IOException( __FILE__, __LINE__, diff --git a/activemq-cpp/src/main/activemq/io/EndianWriter.h b/activemq-cpp/src/main/activemq/io/EndianWriter.h index 42b655a3d6..04afd895f5 100644 --- a/activemq-cpp/src/main/activemq/io/EndianWriter.h +++ b/activemq-cpp/src/main/activemq/io/EndianWriter.h @@ -24,108 +24,109 @@ namespace activemq{ namespace io{ - /* - * The BinaryWriter class writes primitive C++ data types to an - * underlying output stream in a Java compatible way. Strings - * are written as raw bytes, no character encoding is performed. - * - * All numeric data types are written in big endian (network byte - * order) and if the platform is little endian they are converted - * automatically. - * - * Should any error occur an IOException will be thrown. - */ - class EndianWriter : public Writer - { - private: - - /** - * Target output stream. - */ - OutputStream* outputStream; - - public: - - /** - * Constructor. - */ - EndianWriter(); - - /** - * Constructor. - * @param os the target output stream. - */ - EndianWriter( OutputStream* os ); - - /** - * Destructor. - */ - virtual ~EndianWriter(); - - /** - * Sets the target output stream. - */ - virtual void setOutputStream( OutputStream* os ){ - outputStream = os; - } - - /** - * Gets the target output stream. - */ - virtual OutputStream* getOutputStream(){ - return outputStream; - } - - /** - * Writes a byte array to the target output stream. - * @param buffer a byte array. - * @param count the number of bytes to write. - * @throws IOException thrown if an error occurs. - */ - virtual void write(const unsigned char* buffer, int count) throw(IOException); - - /** - * Writes a byte to the target output stream. - * @param v the value to be written - * @throws IOException thrown if an error occurs. - */ - virtual void writeByte(unsigned char v) throw(IOException); - - /** - * Writes a double to the target output stream. - * @param v the value to be written - * @throws IOException thrown if an error occurs. - */ - virtual void writeDouble(double v) throw(IOException); - - /** - * Writes a float to the target output stream. - * @param v the value to be written - * @throws IOException thrown if an error occurs. - */ - virtual void writeFloat(float v) throw(IOException); - - /** - * Writes a short to the target output stream. - * @param v the value to be written - * @throws IOException thrown if an error occurs. - */ - virtual void writeUInt16(uint16_t v) throw(IOException); - - /** - * Writes an int to the target output stream. - * @param v the value to be written - * @throws IOException thrown if an error occurs. - */ - virtual void writeUInt32(uint32_t v) throw(IOException); - - /** - * Writes a long long to the target output stream. - * @param v the value to be written - * @throws IOException thrown if an error occurs. - */ - virtual void writeUInt64(uint64_t v) throw(IOException); - }; + /* + * The EndianWriter class writes primitive C++ data types to an + * underlying output stream in a Java compatible way. Strings + * are written as raw bytes, no character encoding is performed. + * + * All numeric data types are written in big endian (network byte + * order) and if the platform is little endian they are converted + * automatically. + * + * Should any error occur an IOException will be thrown. + */ + class EndianWriter : public Writer + { + private: + + /** + * Target output stream. + */ + OutputStream* outputStream; + + public: + + /** + * Default Constructor. + */ + EndianWriter(); + + /** + * Constructor. + * @param os the target output stream. + */ + EndianWriter( OutputStream* os ); + + /** + * Destructor. + */ + virtual ~EndianWriter(); + + /** + * Sets the target output stream. + */ + virtual void setOutputStream( OutputStream* os ){ + outputStream = os; + } + + /** + * Gets the target output stream. + */ + virtual OutputStream* getOutputStream(){ + return outputStream; + } + + /** + * Writes a byte array to the target output stream. + * @param buffer a byte array. + * @param count the number of bytes to write. + * @throws IOException thrown if an error occurs. + */ + virtual void write( const unsigned char* buffer, int count ) + throw( IOException ); + + /** + * Writes a byte to the target output stream. + * @param v the value to be written + * @throws IOException thrown if an error occurs. + */ + virtual void writeByte( unsigned char v ) throw( IOException ); + + /** + * Writes a double to the target output stream. + * @param v the value to be written + * @throws IOException thrown if an error occurs. + */ + virtual void writeDouble( double v ) throw( IOException ); + + /** + * Writes a float to the target output stream. + * @param v the value to be written + * @throws IOException thrown if an error occurs. + */ + virtual void writeFloat( float v ) throw( IOException ); + + /** + * Writes a short to the target output stream. + * @param v the value to be written + * @throws IOException thrown if an error occurs. + */ + virtual void writeUInt16( uint16_t v ) throw( IOException ); + + /** + * Writes an int to the target output stream. + * @param v the value to be written + * @throws IOException thrown if an error occurs. + */ + virtual void writeUInt32( uint32_t v ) throw( IOException ); + + /** + * Writes a long long to the target output stream. + * @param v the value to be written + * @throws IOException thrown if an error occurs. + */ + virtual void writeUInt64( uint64_t v ) throw( IOException ); + }; }} diff --git a/activemq-cpp/src/main/activemq/io/IOException.h b/activemq-cpp/src/main/activemq/io/IOException.h index 737b0ce9e2..deaa6c7a62 100644 --- a/activemq-cpp/src/main/activemq/io/IOException.h +++ b/activemq-cpp/src/main/activemq/io/IOException.h @@ -22,30 +22,31 @@ namespace activemq{ namespace io{ - /* - * Signals that an I/O exception of some sort has occurred. - */ - class IOException : public exceptions::ActiveMQException - { - public: - IOException(){} + /* + * Signals that an I/O exception of some sort has occurred. + */ + class IOException : public exceptions::ActiveMQException + { + public: + + IOException(){} IOException( const exceptions::ActiveMQException& ex ){ *(exceptions::ActiveMQException*)this = ex; } IOException( const IOException& ex ){ *(exceptions::ActiveMQException*)this = ex; } - IOException(const char* file, const int lineNumber, - const char* msg, ...) - { - va_list vargs ; - va_start(vargs, msg) ; - buildMessage(msg, vargs) ; + IOException( const char* file, const int lineNumber, + const char* msg, ... ) + { + va_list vargs; + va_start( vargs, msg ); + buildMessage( msg, vargs ); // Set the first mark for this exception. setMark( file, lineNumber ); - } - + } + /** * Clones this exception. This is useful for cases where you need * to preserve the type of the original exception as well as the message. @@ -55,9 +56,9 @@ namespace io{ return new IOException( *this ); } - virtual ~IOException(){} - - }; + virtual ~IOException(){} + + }; }} diff --git a/activemq-cpp/src/main/activemq/io/InputStream.h b/activemq-cpp/src/main/activemq/io/InputStream.h index bdcec585bc..437c4ae9db 100644 --- a/activemq-cpp/src/main/activemq/io/InputStream.h +++ b/activemq-cpp/src/main/activemq/io/InputStream.h @@ -24,43 +24,44 @@ namespace activemq{ namespace io{ - - /** - * Base interface for an input stream. - */ - class InputStream - : - public cms::Closeable, - public concurrent::Synchronizable - { - - public: - - virtual ~InputStream(){} - - /** - * Indcates the number of bytes avaialable. - * @return the number of bytes available on this input stream. - */ - virtual int available() const = 0; - - /** - * Reads a single byte from the buffer. - * @return The next byte. - * @throws IOException thrown if an error occurs. - */ - virtual unsigned char read() throw (IOException) = 0; - - /** - * Reads an array of bytes from the buffer. - * @param buffer (out) the target buffer. - * @param bufferSize the size of the output buffer. - * @return The number of bytes read. - * @throws IOException thrown if an error occurs. - */ - virtual int read( unsigned char* buffer, const int bufferSize ) throw (IOException) = 0; - }; - + + /** + * Base interface for an input stream. + */ + class InputStream + : + public cms::Closeable, + public concurrent::Synchronizable + { + + public: + + virtual ~InputStream(){} + + /** + * Indcates the number of bytes avaialable. + * @return the number of bytes available on this input stream. + */ + virtual int available() const = 0; + + /** + * Reads a single byte from the buffer. + * @return The next byte. + * @throws IOException thrown if an error occurs. + */ + virtual unsigned char read() throw ( IOException ) = 0; + + /** + * Reads an array of bytes from the buffer. + * @param buffer (out) the target buffer. + * @param bufferSize the size of the output buffer. + * @return The number of bytes read. + * @throws IOException thrown if an error occurs. + */ + virtual int read( unsigned char* buffer, const int bufferSize ) + throw ( IOException ) = 0; + }; + }} #endif /*ACTIVEMQ_IO_INPUTSTREAM_H_*/ diff --git a/activemq-cpp/src/main/activemq/io/OutputStream.h b/activemq-cpp/src/main/activemq/io/OutputStream.h index c168fa3800..060829c136 100644 --- a/activemq-cpp/src/main/activemq/io/OutputStream.h +++ b/activemq-cpp/src/main/activemq/io/OutputStream.h @@ -25,39 +25,40 @@ namespace activemq{ namespace io{ - /** - * Base interface for an output stream. - */ - class OutputStream - : - public cms::Closeable, - public concurrent::Synchronizable - { - public: - - virtual ~OutputStream(){} - - /** - * Writes a single byte to the output stream. - * @param c the byte. - * @throws IOException thrown if an error occurs. - */ - virtual void write( const unsigned char c ) throw (IOException) = 0; - - /** - * Writes an array of bytes to the output stream. - * @param buffer The array of bytes to write. - * @param len The number of bytes from the buffer to be written. - * @throws IOException thrown if an error occurs. - */ - virtual void write( const unsigned char* buffer, const int len ) throw (IOException) = 0; - - /** - * Flushes any pending writes in this output stream. - */ - virtual void flush() throw (IOException) = 0; - }; - + /** + * Base interface for an output stream. + */ + class OutputStream + : + public cms::Closeable, + public concurrent::Synchronizable + { + public: + + virtual ~OutputStream(){} + + /** + * Writes a single byte to the output stream. + * @param c the byte. + * @throws IOException thrown if an error occurs. + */ + virtual void write( const unsigned char c ) throw ( IOException ) = 0; + + /** + * Writes an array of bytes to the output stream. + * @param buffer The array of bytes to write. + * @param len The number of bytes from the buffer to be written. + * @throws IOException thrown if an error occurs. + */ + virtual void write( const unsigned char* buffer, const int len ) + throw ( IOException ) = 0; + + /** + * Flushes any pending writes in this output stream. + */ + virtual void flush() throw ( IOException ) = 0; + }; + }} #endif /*ACTIVEMQ_IO_OUTPUTSTREAM_H*/ diff --git a/activemq-cpp/src/main/activemq/io/Reader.h b/activemq-cpp/src/main/activemq/io/Reader.h index 6a973f9a51..4906f7711e 100644 --- a/activemq-cpp/src/main/activemq/io/Reader.h +++ b/activemq-cpp/src/main/activemq/io/Reader.h @@ -24,42 +24,44 @@ namespace activemq{ namespace io{ - /* - * Reader interface that wraps around an input stream and provides - * an interface for extracting the data from the input stream. - */ - class Reader - { - public: - - virtual ~Reader(){}; - - /** - * Sets the target input stream. - */ - virtual void setInputStream( InputStream* is ) = 0; - - /** - * Gets the target input stream. - */ - virtual InputStream* getInputStream() = 0; - - /** - * Attempts to read an array of bytes from the stream. - * @param buffer The target byte buffer. - * @param count The number of bytes to read. - * @return The number of bytes read. - * @throws IOException thrown if an error occurs. - */ - virtual int read(unsigned char* buffer, int count) throw(IOException) = 0; - - /** - * Attempts to read a byte from the input stream - * @return The byte. - * @throws IOException thrown if an error occurs. - */ - virtual unsigned char readByte() throw(IOException) = 0; - } ; + /* + * Reader interface that wraps around an input stream and provides + * an interface for extracting the data from the input stream. + */ + class Reader + { + public: + + virtual ~Reader(){}; + + /** + * Sets the target input stream. + */ + virtual void setInputStream( InputStream* is ) = 0; + + /** + * Gets the target input stream. + */ + virtual InputStream* getInputStream() = 0; + + /** + * Attempts to read an array of bytes from the stream. + * @param buffer The target byte buffer. + * @param count The number of bytes to read. + * @return The number of bytes read. + * @throws IOException thrown if an error occurs. + */ + virtual int read( unsigned char* buffer, int count ) + throw( IOException ) = 0; + + /** + * Attempts to read a byte from the input stream + * @return The byte. + * @throws IOException thrown if an error occurs. + */ + virtual unsigned char readByte() throw( IOException ) = 0; + + }; }} diff --git a/activemq-cpp/src/main/activemq/io/StandardErrorOutputStream.h b/activemq-cpp/src/main/activemq/io/StandardErrorOutputStream.h index 1f4d6061a7..b1048b4673 100644 --- a/activemq-cpp/src/main/activemq/io/StandardErrorOutputStream.h +++ b/activemq-cpp/src/main/activemq/io/StandardErrorOutputStream.h @@ -25,128 +25,127 @@ namespace activemq{ namespace io{ - class StandardErrorOutputStream : public OutputStream - { - private: + class StandardErrorOutputStream : public OutputStream + { + private: - /** - * Synchronization object. - */ - concurrent::Mutex mutex; + /** + * Synchronization object. + */ + concurrent::Mutex mutex; - public: + public: - /** - * Constructor - */ - StandardErrorOutputStream(void) {} + /** + * Default Constructor + */ + StandardErrorOutputStream(void) {} - /** - * Destructor - */ - virtual ~StandardErrorOutputStream(void) {} + virtual ~StandardErrorOutputStream(void) {} - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void lock() throw(exceptions::ActiveMQException){ - mutex.lock(); - } + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void lock() throw( exceptions::ActiveMQException ){ + mutex.lock(); + } - /** - * Unlocks the object. - * @throws ActiveMQException - */ - virtual void unlock() throw(exceptions::ActiveMQException){ - mutex.unlock(); - } + /** + * Unlocks the object. + * @throws ActiveMQException + */ + virtual void unlock() throw( exceptions::ActiveMQException ){ + mutex.unlock(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void wait() throw(exceptions::ActiveMQException){ - mutex.wait(); - } + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void wait() throw( exceptions::ActiveMQException ){ + mutex.wait(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. This wait will timeout after the specified time - * interval. - * @param time in millisecsonds to wait, or WAIT_INIFINITE - * @throws ActiveMQException - */ - virtual void wait(unsigned long millisecs) throw(exceptions::ActiveMQException){ - mutex.wait(millisecs); - } + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. This wait will timeout after the specified time + * interval. + * @param time in millisecsonds to wait, or WAIT_INIFINITE + * @throws ActiveMQException + */ + virtual void wait( unsigned long millisecs ) throw( exceptions::ActiveMQException ){ + mutex.wait( millisecs ); + } - /** - * Signals a waiter on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void notify() throw(exceptions::ActiveMQException){ - mutex.notify(); - } + /** + * Signals a waiter on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void notify() throw( exceptions::ActiveMQException ){ + mutex.notify(); + } - /** - * Signals the waiters on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - * @throws ActiveMQException - */ - virtual void notifyAll() throw(exceptions::ActiveMQException){ - mutex.notifyAll(); - } + /** + * Signals the waiters on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void notifyAll() throw( exceptions::ActiveMQException ){ + mutex.notifyAll(); + } - /** - * Writes a single byte to the output stream. - * @param c the byte. - * @throws IOException thrown if an error occurs. - */ - virtual void write( const unsigned char c ) - throw (IOException) - { - std::cerr << c; - } + /** + * Writes a single byte to the output stream. + * @param c the byte. + * @throws IOException thrown if an error occurs. + */ + virtual void write( const unsigned char c ) + throw ( IOException ) + { + std::cerr << c; + } - /** - * Writes an array of bytes to the output stream. - * @param buffer The array of bytes to write. - * @param len The number of bytes from the buffer to be written. - * @throws IOException thrown if an error occurs. - */ - virtual void write( const unsigned char* buffer, const int len ) - throw (IOException) - { - for(int i = 0; i < len; ++i) - { - std::cerr << buffer[i]; - } - } + /** + * Writes an array of bytes to the output stream. + * @param buffer The array of bytes to write. + * @param len The number of bytes from the buffer to be written. + * @throws IOException thrown if an error occurs. + */ + virtual void write( const unsigned char* buffer, const int len ) + throw ( IOException ) + { + for(int i = 0; i < len; ++i) + { + std::cerr << buffer[i]; + } + } - /** - * Invokes flush on the target output stream. - */ - virtual void flush() throw (IOException){ - std::cerr.flush(); - } + /** + * Invokes flush on the target output stream. + * throws IOException if an error occurs + */ + virtual void flush() throw ( IOException ){ + std::cerr.flush(); + } - /** - * Invokes close on the target output stream. - */ - void close() throw(cms::CMSException){ - std::cerr.flush(); - } + /** + * Invokes close on the target output stream. + * throws CMSException if an error occurs + */ + void close() throw( cms::CMSException ){ + std::cerr.flush(); + } - }; + }; } diff --git a/activemq-cpp/src/main/activemq/io/Writer.h b/activemq-cpp/src/main/activemq/io/Writer.h index c13e618b91..db3dc7c6f3 100644 --- a/activemq-cpp/src/main/activemq/io/Writer.h +++ b/activemq-cpp/src/main/activemq/io/Writer.h @@ -24,41 +24,43 @@ namespace activemq{ namespace io{ - /* - * Writer interface for an object that wraps around an output - * stream - */ - class Writer - { - public: + /* + * Writer interface for an object that wraps around an output + * stream + */ + class Writer + { + public: - virtual ~Writer(){}; + virtual ~Writer(){}; - /** - * Sets the target output stream. - */ - virtual void setOutputStream( OutputStream* os ) = 0; + /** + * Sets the target output stream. + * @param Outputstream to use + */ + virtual void setOutputStream( OutputStream* os ) = 0; - /** - * Gets the target output stream. - */ - virtual OutputStream* getOutputStream() = 0; + /** + * Gets the target output stream. + * @returns the output stream currently being used + */ + virtual OutputStream* getOutputStream() = 0; - /** - * Writes a byte array to the output stream. - * @param buffer a byte array - * @param count the number of bytes in the array to write. - * @throws IOException thrown if an error occurs. - */ - virtual void write(const unsigned char* buffer, int count) throw(IOException) = 0; + /** + * Writes a byte array to the output stream. + * @param buffer a byte array + * @param count the number of bytes in the array to write. + * @throws IOException thrown if an error occurs. + */ + virtual void write( const unsigned char* buffer, int count ) throw( IOException ) = 0; - /** - * Writes a byte to the output stream. - * @param v The value to be written. - * @throws IOException thrown if an error occurs. - */ - virtual void writeByte(unsigned char v) throw(IOException) = 0; - }; + /** + * Writes a byte to the output stream. + * @param v The value to be written. + * @throws IOException thrown if an error occurs. + */ + virtual void writeByte( unsigned char v ) throw( IOException ) = 0; + }; }} diff --git a/activemq-cpp/src/main/activemq/network/BufferedSocket.cpp b/activemq-cpp/src/main/activemq/network/BufferedSocket.cpp index 8fc3691b2f..e1a0080ebf 100644 --- a/activemq-cpp/src/main/activemq/network/BufferedSocket.cpp +++ b/activemq-cpp/src/main/activemq/network/BufferedSocket.cpp @@ -25,97 +25,97 @@ using namespace activemq::io; using namespace activemq::exceptions; //////////////////////////////////////////////////////////////////////////////// -BufferedSocket::BufferedSocket(Socket* socket, - unsigned int inputBufferSize, - unsigned int outputBufferSize, - bool own) +BufferedSocket::BufferedSocket( Socket* socket, + unsigned int inputBufferSize, + unsigned int outputBufferSize, + bool own ) { - if(socket == NULL) - { - throw IllegalArgumentException( - __FILE__, __LINE__, - "BufferedSocket::BufferedSocket - Constructed with NULL Socket"); - } + if(socket == NULL) + { + throw IllegalArgumentException( + __FILE__, __LINE__, + "BufferedSocket::BufferedSocket - Constructed with NULL Socket"); + } - this->socket = socket; - this->inputBufferSize = inputBufferSize; - this->outputBufferSize = outputBufferSize; - this->own = own; + this->socket = socket; + this->inputBufferSize = inputBufferSize; + this->outputBufferSize = outputBufferSize; + this->own = own; } //////////////////////////////////////////////////////////////////////////////// BufferedSocket::~BufferedSocket(void) { - try - { - if(outputStream) - { - // Ensure all data is written - outputStream->flush(); - } + try + { + if( outputStream ) + { + // Ensure all data is written + outputStream->flush(); + } - // Close the socket - socket->close(); + // Close the socket + socket->close(); - // if we own it, delete it. - if(own) - { - delete socket; - } + // if we own it, delete it. + if( own ) + { + delete socket; + } - // Clean up our streams. - delete inputStream; - delete outputStream; - } - AMQ_CATCH_NOTHROW( ActiveMQException ) - AMQ_CATCHALL_NOTHROW( ) + // Clean up our streams. + delete inputStream; + delete outputStream; + } + AMQ_CATCH_NOTHROW( ActiveMQException ) + AMQ_CATCHALL_NOTHROW( ) } //////////////////////////////////////////////////////////////////////////////// void BufferedSocket::connect( const char* host, const int port ) - throw( SocketException ) + throw( SocketException ) { - try - { - if( socket->isConnected() ) - { - throw SocketException( __FILE__, __LINE__, - "BufferedSocket::connect() - socket already connected" ); - } + try + { + if( socket->isConnected() ) + { + throw SocketException( __FILE__, __LINE__, + "BufferedSocket::connect() - socket already connected" ); + } - // Connect the socket. - socket->connect( host, port ); + // Connect the socket. + socket->connect( host, port ); - // Now create the buffered streams that wrap around the socket. - inputStream = new BufferedInputStream( - socket->getInputStream(), inputBufferSize ); - outputStream = new BufferedOutputStream( - socket->getOutputStream(), outputBufferSize ); - } - AMQ_CATCH_RETHROW( SocketException ) - AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, SocketException ) - AMQ_CATCHALL_THROW( SocketException ) + // Now create the buffered streams that wrap around the socket. + inputStream = new BufferedInputStream( + socket->getInputStream(), inputBufferSize ); + outputStream = new BufferedOutputStream( + socket->getOutputStream(), outputBufferSize ); + } + AMQ_CATCH_RETHROW( SocketException ) + AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, SocketException ) + AMQ_CATCHALL_THROW( SocketException ) } //////////////////////////////////////////////////////////////////////////////// void BufferedSocket::close(void) throw( cms::CMSException ) { - try - { - // Ensure all data writen - outputStream->flush(); + try + { + // Ensure all data writen + outputStream->flush(); - // Close the Socket - socket->close(); + // Close the Socket + socket->close(); - // Remove old stream, recreate if reconnected - delete inputStream; - delete outputStream; + // Remove old stream, recreate if reconnected + delete inputStream; + delete outputStream; - inputStream = NULL; - outputStream = NULL; - } - AMQ_CATCH_RETHROW( SocketException ) - AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, SocketException ) - AMQ_CATCHALL_THROW( SocketException ) + inputStream = NULL; + outputStream = NULL; + } + AMQ_CATCH_RETHROW( SocketException ) + AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, SocketException ) + AMQ_CATCHALL_THROW( SocketException ) } diff --git a/activemq-cpp/src/main/activemq/network/BufferedSocket.h b/activemq-cpp/src/main/activemq/network/BufferedSocket.h index ee7474fac2..a8f112af12 100644 --- a/activemq-cpp/src/main/activemq/network/BufferedSocket.h +++ b/activemq-cpp/src/main/activemq/network/BufferedSocket.h @@ -25,195 +25,190 @@ namespace activemq{ namespace network{ - /** - * Buffered Socket class that wraps a Socket derived - * object and provides Buffered input and Output Streams to improce - * the efficiency of the reads and writes. - */ - class BufferedSocket : public Socket - { - private: + /** + * Buffered Socket class that wraps a Socket derived + * object and provides Buffered input and Output Streams to improce + * the efficiency of the reads and writes. + */ + class BufferedSocket : public Socket + { + private: - // Socket that this class wraps to provide buffering - Socket* socket; + // Socket that this class wraps to provide buffering + Socket* socket; - // Indicates if the lifetime of the Socket is controlled by this - // class. If true Socket is deleted at destruction. - bool own; + // Indicates if the lifetime of the Socket is controlled by this + // class. If true Socket is deleted at destruction. + bool own; - // Buffered Input stream to wrap the Socket input stream - io::BufferedInputStream* inputStream; + // Buffered Input stream to wrap the Socket input stream + io::BufferedInputStream* inputStream; - // Buffered Output stream to wrap the Socket input stream - io::BufferedOutputStream* outputStream; + // Buffered Output stream to wrap the Socket input stream + io::BufferedOutputStream* outputStream; - // Sizes for the Buffered Streams - unsigned int inputBufferSize; - unsigned int outputBufferSize; + // Sizes for the Buffered Streams + unsigned int inputBufferSize; + unsigned int outputBufferSize; - public: + public: - /** - * Constructor - */ - BufferedSocket(Socket* socket, - unsigned int inputBufferSize = 1000, - unsigned int outputBufferSize = 1000, - bool own = true); + BufferedSocket( Socket* socket, + unsigned int inputBufferSize = 1000, + unsigned int outputBufferSize = 1000, + bool own = true ); - /** - * Destructor - */ - virtual ~BufferedSocket(void); + virtual ~BufferedSocket(void); - /** - * Connects to the specified destination. Closes this socket if - * connected to another destination. - * @param host The host of the server to connect to. - * @param port The port of the server to connect to. - * @throws IOException Thrown if a failure occurred in the connect. - */ - virtual void connect( const char* host, const int port ) - throw(SocketException); + /** + * Connects to the specified destination. Closes this socket if + * connected to another destination. + * @param host The host of the server to connect to. + * @param port The port of the server to connect to. + * @throws IOException Thrown if a failure occurred in the connect. + */ + virtual void connect( const char* host, const int port ) + throw( SocketException ); - /** - * Closes this object and deallocates the appropriate resources. - * @throws CMSException - */ - virtual void close() throw( cms::CMSException ); + /** + * Closes this object and deallocates the appropriate resources. + * @throws CMSException + */ + virtual void close() throw( cms::CMSException ); - /** - * Indicates whether or not this socket is connected to a destination. - */ - virtual bool isConnected() const{ - return socket->isConnected(); - } + /** + * Indicates whether or not this socket is connected to a destination. + * @return true if connected + */ + virtual bool isConnected() const{ + return socket->isConnected(); + } - /** - * Gets the InputStream for this socket. - * @return The InputStream for this socket. NULL if not connected. - */ - virtual io::InputStream* getInputStream(){ - return inputStream; - } + /** + * Gets the InputStream for this socket. + * @return The InputStream for this socket. NULL if not connected. + */ + virtual io::InputStream* getInputStream(){ + return inputStream; + } - /** - * Gets the OutputStream for this socket. - * @return the OutputStream for this socket. NULL if not connected. - */ - virtual io::OutputStream* getOutputStream(){ - return outputStream; - } + /** + * Gets the OutputStream for this socket. + * @return the OutputStream for this socket. NULL if not connected. + */ + virtual io::OutputStream* getOutputStream(){ + return outputStream; + } - /** - * Gets the linger time. - * @return The linger time in seconds. - * @throws SocketException if the operation fails. - */ - virtual int getSoLinger() const throw(SocketException){ - return socket->getSoLinger(); - } + /** + * Gets the linger time. + * @return The linger time in seconds. + * @throws SocketException if the operation fails. + */ + virtual int getSoLinger() const throw( SocketException ){ + return socket->getSoLinger(); + } - /** - * Sets the linger time. - * @param linger The linger time in seconds. If 0, linger is off. - * @throws SocketException if the operation fails. - */ - virtual void setSoLinger( const int linger ) throw(SocketException){ - socket->setSoLinger(linger); - } + /** + * Sets the linger time. + * @param linger The linger time in seconds. If 0, linger is off. + * @throws SocketException if the operation fails. + */ + virtual void setSoLinger( const int linger ) throw( SocketException ){ + socket->setSoLinger( linger ); + } - /** - * Gets the keep alive flag. - * @return True if keep alive is enabled. - * @throws SocketException if the operation fails. - */ - virtual bool getKeepAlive() const throw(SocketException){ - return socket->getKeepAlive(); - } + /** + * Gets the keep alive flag. + * @return True if keep alive is enabled. + * @throws SocketException if the operation fails. + */ + virtual bool getKeepAlive() const throw( SocketException ){ + return socket->getKeepAlive(); + } - /** - * Enables/disables the keep alive flag. - * @param keepAlive If true, enables the flag. - * @throws SocketException if the operation fails. - */ - virtual void setKeepAlive( const bool keepAlive ) throw(SocketException){ - socket->setKeepAlive(keepAlive); - } + /** + * Enables/disables the keep alive flag. + * @param keepAlive If true, enables the flag. + * @throws SocketException if the operation fails. + */ + virtual void setKeepAlive( const bool keepAlive ) throw( SocketException ){ + socket->setKeepAlive( keepAlive ); + } - /** - * Gets the receive buffer size. - * @return the receive buffer size in bytes. - * @throws SocketException if the operation fails. - */ - virtual int getReceiveBufferSize() const throw(SocketException){ - return socket->getReceiveBufferSize(); - } + /** + * Gets the receive buffer size. + * @return the receive buffer size in bytes. + * @throws SocketException if the operation fails. + */ + virtual int getReceiveBufferSize() const throw( SocketException ){ + return socket->getReceiveBufferSize(); + } - /** - * Sets the recieve buffer size. - * @param size Number of bytes to set the receive buffer to. - * @throws SocketException if the operation fails. - */ - virtual void setReceiveBufferSize( const int size ) throw(SocketException){ - socket->setReceiveBufferSize(size); - } + /** + * Sets the recieve buffer size. + * @param size Number of bytes to set the receive buffer to. + * @throws SocketException if the operation fails. + */ + virtual void setReceiveBufferSize( const int size ) throw( SocketException ){ + socket->setReceiveBufferSize( size ); + } - /** - * Gets the reuse address flag. - * @return True if the address can be reused. - * @throws SocketException if the operation fails. - */ - virtual bool getReuseAddress() const throw(SocketException){ - return socket->getReuseAddress(); - } + /** + * Gets the reuse address flag. + * @return True if the address can be reused. + * @throws SocketException if the operation fails. + */ + virtual bool getReuseAddress() const throw( SocketException ){ + return socket->getReuseAddress(); + } - /** - * Sets the reuse address flag. - * @param reuse If true, sets the flag. - * @throws SocketException if the operation fails. - */ - virtual void setReuseAddress( const bool reuse ) throw(SocketException){ - socket->setReuseAddress(reuse); - } + /** + * Sets the reuse address flag. + * @param reuse If true, sets the flag. + * @throws SocketException if the operation fails. + */ + virtual void setReuseAddress( const bool reuse ) throw( SocketException ){ + socket->setReuseAddress( reuse ); + } - /** - * Gets the send buffer size. - * @return the size in bytes of the send buffer. - * @throws SocketException if the operation fails. - */ - virtual int getSendBufferSize() const throw(SocketException){ - return socket->getSendBufferSize(); - } + /** + * Gets the send buffer size. + * @return the size in bytes of the send buffer. + * @throws SocketException if the operation fails. + */ + virtual int getSendBufferSize() const throw( SocketException ){ + return socket->getSendBufferSize(); + } - /** - * Sets the send buffer size. - * @param size The number of bytes to set the send buffer to. - * @throws SocketException if the operation fails. - */ - virtual void setSendBufferSize( const int size ) throw(SocketException){ - socket->setSendBufferSize(size); - } + /** + * Sets the send buffer size. + * @param size The number of bytes to set the send buffer to. + * @throws SocketException if the operation fails. + */ + virtual void setSendBufferSize( const int size ) throw( SocketException ){ + socket->setSendBufferSize( size ); + } - /** - * Gets the timeout for socket operations. - * @return The timeout in milliseconds for socket operations. - * @throws SocketException Thrown if unable to retrieve the information. - */ - virtual int getSoTimeout() const throw(SocketException){ - return socket->getSoTimeout(); - } + /** + * Gets the timeout for socket operations. + * @return The timeout in milliseconds for socket operations. + * @throws SocketException Thrown if unable to retrieve the information. + */ + virtual int getSoTimeout() const throw( SocketException ){ + return socket->getSoTimeout(); + } - /** - * Sets the timeout for socket operations. - * @param timeout The timeout in milliseconds for socket operations.

- * @throws SocketException Thrown if unable to set the information. - */ - virtual void setSoTimeout( const int timeout ) throw(SocketException){ - socket->setSoTimeout(timeout); - } + /** + * Sets the timeout for socket operations. + * @param timeout The timeout in milliseconds for socket operations.

+ * @throws SocketException Thrown if unable to set the information. + */ + virtual void setSoTimeout( const int timeout ) throw( SocketException ){ + socket->setSoTimeout( timeout ); + } - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/network/ServerSocket.cpp b/activemq-cpp/src/main/activemq/network/ServerSocket.cpp index 75b6fb1d2a..00a3d53b44 100644 --- a/activemq-cpp/src/main/activemq/network/ServerSocket.cpp +++ b/activemq-cpp/src/main/activemq/network/ServerSocket.cpp @@ -16,23 +16,23 @@ */ #if (defined(unix) || defined(__APPLE__)) && !defined(__CYGWIN__) - #include - #include - #include - #include - #include - #include - #include - extern int errno; + #include + #include + #include + #include + #include + #include + #include + extern int errno; #else - #include - #include - #include - #define stat _stat - #ifdef errno - #undef errno - #endif - int errno; + #include + #include + #include + #define stat _stat + #ifdef errno + #undef errno + #endif + int errno; #endif #include @@ -48,28 +48,28 @@ using namespace activemq::network; -#if !(defined( unix ) || defined(__APPLE__)) || defined( __CYGWIN__ ) +#if !defined( unix ) || defined( __CYGWIN__ ) - // Static socket initializer needed for winsock + // Static socket initializer needed for winsock - ServerSocket::StaticServerSocketInitializer::StaticServerSocketInitializer () { - socketInitError = NULL; - const WORD version_needed = MAKEWORD(2,2); // lo-order byte: major version - WSAData temp; - if (WSAStartup(version_needed, &temp)){ - clear(); - socketInitError = new SocketException ( __FILE__, __LINE__, - "winsock.dll was not found"); - } - } - ServerSocket::StaticServerSocketInitializer::~StaticServerSocketInitializer () { - clear(); - WSACleanup(); - } + ServerSocket::StaticServerSocketInitializer::StaticServerSocketInitializer () { + socketInitError = NULL; + const WORD version_needed = MAKEWORD(2,2); // lo-order byte: major version + WSAData temp; + if( WSAStartup(version_needed, &temp )){ + clear(); + socketInitError = new SocketException ( __FILE__, __LINE__, + "winsock.dll was not found"); + } + } + ServerSocket::StaticServerSocketInitializer::~StaticServerSocketInitializer () { + clear(); + WSACleanup(); + } - // Create static instance of the socket initializer. - ServerSocket::StaticServerSocketInitializer - ServerSocket::staticSocketInitializer; + // Create static instance of the socket initializer. + ServerSocket::StaticServerSocketInitializer + ServerSocket::staticSocketInitializer; #endif @@ -77,128 +77,127 @@ using namespace activemq::network; //////////////////////////////////////////////////////////////////////////////// ServerSocket::ServerSocket() { - socketHandle = Socket::INVALID_SOCKET_HANDLE; + socketHandle = Socket::INVALID_SOCKET_HANDLE; -#if !(defined( unix ) || defined(__APPLE__)) || defined( __CYGWIN__ ) - if (ServerSocket::staticSocketInitializer.getSocketInitError() != NULL) { - throw *ServerSocket::staticSocketInitializer.getSocketInitError(); - } +#if !defined( unix ) || defined( __CYGWIN__ ) + if( ServerSocket::staticSocketInitializer.getSocketInitError() != NULL ) { + throw *ServerSocket::staticSocketInitializer.getSocketInitError(); + } #endif } //////////////////////////////////////////////////////////////////////////////// ServerSocket::~ServerSocket() { - // No shutdown, just close - dont want blocking destructor. - close(); + // No shutdown, just close - dont want blocking destructor. + close(); } //////////////////////////////////////////////////////////////////////////////// -void ServerSocket::bind (const char* host, int port) throw (SocketException) +void ServerSocket::bind( const char* host, int port ) throw ( SocketException ) { - bind (host, port, SOMAXCONN); + bind (host, port, SOMAXCONN); } //////////////////////////////////////////////////////////////////////////////// -void ServerSocket::bind (const char* host, int port, int backlog) throw (SocketException) +void ServerSocket::bind( const char* host, int port, int backlog ) throw ( SocketException ) { - if (isBound()) { - throw SocketException ( __FILE__, __LINE__, - "ServerSocket::bind - Socket already bound" ); - } + if(isBound()) { + throw SocketException ( __FILE__, __LINE__, + "ServerSocket::bind - Socket already bound" ); + } // Create the socket. - socketHandle = ::socket(AF_INET, SOCK_STREAM, 0); - if (socketHandle < 0) { - socketHandle = Socket::INVALID_SOCKET_HANDLE; - throw SocketException( __FILE__, __LINE__, ::strerror( errno )); - } + socketHandle = ::socket(AF_INET, SOCK_STREAM, 0 ); + if( socketHandle < 0) { + socketHandle = Socket::INVALID_SOCKET_HANDLE; + throw SocketException( __FILE__, __LINE__, ::strerror( errno )); + } - // Verify the port value. - if (port <= 0 || port > 65535) { - throw SocketException( __FILE__, __LINE__, - "ServerSocket::bind - Port out of range: %d", port ); - } - - - 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; - int status = ::getaddrinfo(host, NULL, &hints, &res_ptr); - if( status != 0 || res_ptr == NULL) { - throw SocketException( __FILE__, __LINE__, ::strerror( errno ) ); - } - 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); - - // Set the socket to reuse the address. - int value = 1; - ::setsockopt(socketHandle, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int) ); + // Verify the port value. + if( port <= 0 || port > 65535 ) { + throw SocketException( __FILE__, __LINE__, + "ServerSocket::bind - Port out of range: %d", port ); + } - status = ::bind(socketHandle, - (sockaddr *)&bind_addr, sizeof(bind_addr)); + 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)); - if( status < 0 ){ + // Resolve name + ::addrinfo hints; + memset(&hints, 0, sizeof(addrinfo)); + hints.ai_family = PF_INET; + struct addrinfo *res_ptr = NULL; + int status = ::getaddrinfo(host, NULL, &hints, &res_ptr); + if( status != 0 || res_ptr == NULL) { + throw SocketException( __FILE__, __LINE__, ::strerror( errno ) ); + } + 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); + + // Set the socket to reuse the address. + int value = 1; + ::setsockopt(socketHandle, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int) ); + + status = ::bind(socketHandle, + (sockaddr *)&bind_addr, sizeof( bind_addr )); + + if( status < 0 ){ close(); - throw SocketException ( __FILE__, __LINE__, + throw SocketException ( __FILE__, __LINE__, "ServerSocket::bind - %s", ::strerror( errno ) ); - } - status = ::listen(socketHandle, backlog); - if (status < 0) { - close(); - throw SocketException( __FILE__, __LINE__, ::strerror( errno ) ); - } + } + status = ::listen( socketHandle, backlog ); + if( status < 0 ) { + close(); + throw SocketException( __FILE__, __LINE__, ::strerror( errno ) ); + } } //////////////////////////////////////////////////////////////////////////////// void ServerSocket::close() throw (cms::CMSException){ - if (isBound()) { + if( isBound() ) { - #if (defined(unix) || defined(__APPLE__)) && !defined(__CYGWIN__) - ::close(socketHandle); - #else - ::closesocket(socketHandle); - #endif + #if defined(unix) && !defined( __CYGWIN__ ) + ::close( socketHandle ); + #else + ::closesocket( socketHandle ); + #endif - socketHandle = Socket::INVALID_SOCKET_HANDLE; - } + socketHandle = Socket::INVALID_SOCKET_HANDLE; + } } //////////////////////////////////////////////////////////////////////////////// bool ServerSocket::isBound() const { - return this->socketHandle != Socket::INVALID_SOCKET_HANDLE; + return this->socketHandle != Socket::INVALID_SOCKET_HANDLE; } //////////////////////////////////////////////////////////////////////////////// Socket* ServerSocket::accept () throw (SocketException) { - struct sockaddr_in temp; + struct sockaddr_in temp; -#if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - socklen_t temp_len = sizeof (sockaddr_in); -#else - int temp_len = sizeof (sockaddr_in); -#endif + #if defined( unix ) && !defined( __CYGWIN__ ) + socklen_t temp_len = sizeof( sockaddr_in ); + #else + int temp_len = sizeof( sockaddr_in ); + #endif - SocketHandle ss_socket_handle = - ::accept(socketHandle, (struct sockaddr*)&temp, &temp_len); - if (ss_socket_handle < 0) { - throw SocketException( __FILE__, __LINE__, - "ServerSocket::accept- %s", ::strerror( errno ) ); - } + SocketHandle ss_socket_handle = + ::accept( socketHandle, (struct sockaddr*)&temp, &temp_len ); + if( ss_socket_handle < 0 ) { + throw SocketException( __FILE__, __LINE__, + "ServerSocket::accept- %s", ::strerror( errno ) ); + } - return new TcpSocket(ss_socket_handle); + return new TcpSocket( ss_socket_handle ); } diff --git a/activemq-cpp/src/main/activemq/network/ServerSocket.h b/activemq-cpp/src/main/activemq/network/ServerSocket.h index 28c64afdba..28d0f7b00e 100644 --- a/activemq-cpp/src/main/activemq/network/ServerSocket.h +++ b/activemq-cpp/src/main/activemq/network/ServerSocket.h @@ -23,65 +23,65 @@ namespace activemq{ namespace network{ - /** - * A server socket class (for testing purposes). - */ - class ServerSocket - { - public: - - typedef Socket::SocketHandle SocketHandle; - - private: - - SocketHandle socketHandle; - - public: - - /** - * Constructor. - * Creates a non-bound server socket. - */ - ServerSocket(); - - /** - * Destructor. - * Releases socket handle if close() hasn't been called. - */ - virtual ~ServerSocket(); - - public: - - /** - * Bind and listen to given IP/dns and port. - * @param host IP address or host name. - * @param port TCP port between 1..655535 - */ - virtual void bind (const char* host, int port) throw (SocketException); - - /** - * Bind and listen to given IP/dns and port. - * @param host IP address or host name. - * @param port TCP port between 1..655535 - * @param backlog Size of listen backlog. - */ - virtual void bind (const char* host, int port, int backlog) throw (SocketException); - - /** - * Blocks until a client connects to the bound socket. - * @return new socket. Never returns NULL. - */ - virtual Socket* accept () throw (SocketException); - - /** - * Closes the server socket. - */ - virtual void close() throw(cms::CMSException); - - /** - * @return true of the server socket is bound. - */ - virtual bool isBound() const; + /** + * A server socket class (for testing purposes). + */ + class ServerSocket + { + public: + + typedef Socket::SocketHandle SocketHandle; + + private: + + SocketHandle socketHandle; + + public: + + /** + * Constructor. + * Creates a non-bound server socket. + */ + ServerSocket(); + + /** + * Destructor. + * Releases socket handle if close() hasn't been called. + */ + virtual ~ServerSocket(); + + public: + + /** + * Bind and listen to given IP/dns and port. + * @param host IP address or host name. + * @param port TCP port between 1..655535 + */ + virtual void bind( const char* host, int port ) throw ( SocketException ); + + /** + * Bind and listen to given IP/dns and port. + * @param host IP address or host name. + * @param port TCP port between 1..655535 + * @param backlog Size of listen backlog. + */ + virtual void bind( const char* host, int port, int backlog ) throw ( SocketException ); + + /** + * Blocks until a client connects to the bound socket. + * @return new socket. Never returns NULL. + */ + virtual Socket* accept () throw ( SocketException ); + + /** + * Closes the server socket. + */ + virtual void close() throw( cms::CMSException ); + + /** + * @return true of the server socket is bound. + */ + virtual bool isBound() const; protected: @@ -94,18 +94,19 @@ namespace network{ SocketException* socketInitError; void clear(){ - if( socketInitError != NULL ){ - delete socketInitError; - } - socketInitError = NULL; + if( socketInitError != NULL ){ + delete socketInitError; + } + socketInitError = NULL; } public: - SocketException* getSocketInitError () { + + SocketException* getSocketInitError() { return socketInitError; } StaticServerSocketInitializer(); - virtual ~StaticServerSocketInitializer (); + virtual ~StaticServerSocketInitializer(); }; static StaticServerSocketInitializer staticSocketInitializer; diff --git a/activemq-cpp/src/main/activemq/network/Socket.h b/activemq-cpp/src/main/activemq/network/Socket.h index 40c7b8d222..f808983203 100644 --- a/activemq-cpp/src/main/activemq/network/Socket.h +++ b/activemq-cpp/src/main/activemq/network/Socket.h @@ -29,141 +29,139 @@ namespace activemq{ namespace network{ - class Socket : public cms::Closeable - { - public: + class Socket : public cms::Closeable + { + public: - // Define the SocketHandle type. - #if defined( unix ) || defined(__APPLE__) && !defined( __CYGWIN__ ) - typedef int SocketHandle; - #else - typedef SOCKET SocketHandle; - #endif + // Define the SocketHandle type. + #if defined( unix ) && !defined( __CYGWIN__ ) + typedef int SocketHandle; + #else + typedef SOCKET SocketHandle; + #endif - /** - * Defines a constant for an invalid socket handle. - */ - static const SocketHandle INVALID_SOCKET_HANDLE = (SocketHandle) -1; + /** + * Defines a constant for an invalid socket handle. + */ + static const SocketHandle INVALID_SOCKET_HANDLE = (SocketHandle) -1; - public: + public: - /** - * Destructor - */ - virtual ~Socket(void) {} + virtual ~Socket(void) {} - /** - * Connects to the specified destination. Closes this socket if - * connected to another destination. - * @param host The host of the server to connect to. - * @param port The port of the server to connect to. - * @throws IOException Thrown if a failure occurred in the connect. - */ - virtual void connect( const char* host, const int port ) - throw(SocketException) = 0; + /** + * Connects to the specified destination. Closes this socket if + * connected to another destination. + * @param host The host of the server to connect to. + * @param port The port of the server to connect to. + * @throws IOException Thrown if a failure occurred in the connect. + */ + virtual void connect( const char* host, const int port ) + throw(SocketException) = 0; - /** - * Indicates whether or not this socket is connected to a destination. - */ - virtual bool isConnected() const = 0; + /** + * Indicates whether or not this socket is connected to a destination. + * @returns true if connected + */ + virtual bool isConnected() const = 0; - /** - * Gets the InputStream for this socket. - * @return The InputStream for this socket. NULL if not connected. - */ - virtual io::InputStream* getInputStream() = 0; + /** + * Gets the InputStream for this socket. + * @return The InputStream for this socket. NULL if not connected. + */ + virtual io::InputStream* getInputStream() = 0; - /** - * Gets the OutputStream for this socket. - * @return the OutputStream for this socket. NULL if not connected. - */ - virtual io::OutputStream* getOutputStream() = 0; + /** + * Gets the OutputStream for this socket. + * @return the OutputStream for this socket. NULL if not connected. + */ + virtual io::OutputStream* getOutputStream() = 0; - /** - * Gets the linger time. - * @return The linger time in seconds. - * @throws SocketException if the operation fails. - */ - virtual int getSoLinger() const throw(SocketException) = 0; + /** + * Gets the linger time. + * @return The linger time in seconds. + * @throws SocketException if the operation fails. + */ + virtual int getSoLinger() const throw( SocketException ) = 0; - /** - * Sets the linger time. - * @param linger The linger time in seconds. If 0, linger is off. - * @throws SocketException if the operation fails. - */ - virtual void setSoLinger( const int linger ) throw(SocketException) = 0; + /** + * Sets the linger time. + * @param linger The linger time in seconds. If 0, linger is off. + * @throws SocketException if the operation fails. + */ + virtual void setSoLinger( const int linger ) throw( SocketException ) = 0; - /** - * Gets the keep alive flag. - * @return True if keep alive is enabled. - * @throws SocketException if the operation fails. - */ - virtual bool getKeepAlive() const throw(SocketException) = 0; + /** + * Gets the keep alive flag. + * @return True if keep alive is enabled. + * @throws SocketException if the operation fails. + */ + virtual bool getKeepAlive() const throw( SocketException ) = 0; - /** - * Enables/disables the keep alive flag. - * @param keepAlive If true, enables the flag. - * @throws SocketException if the operation fails. - */ - virtual void setKeepAlive( const bool keepAlive ) throw(SocketException) = 0; + /** + * Enables/disables the keep alive flag. + * @param keepAlive If true, enables the flag. + * @throws SocketException if the operation fails. + */ + virtual void setKeepAlive( const bool keepAlive ) throw( SocketException ) = 0; - /** - * Gets the receive buffer size. - * @return the receive buffer size in bytes. - * @throws SocketException if the operation fails. - */ - virtual int getReceiveBufferSize() const throw(SocketException) = 0; + /** + * Gets the receive buffer size. + * @return the receive buffer size in bytes. + * @throws SocketException if the operation fails. + */ + virtual int getReceiveBufferSize() const throw( SocketException ) = 0; - /** - * Sets the recieve buffer size. - * @param size Number of bytes to set the receive buffer to. - * @throws SocketException if the operation fails. - */ - virtual void setReceiveBufferSize( const int size ) throw(SocketException) = 0; + /** + * Sets the recieve buffer size. + * @param size Number of bytes to set the receive buffer to. + * @throws SocketException if the operation fails. + */ + virtual void setReceiveBufferSize( const int size ) throw( SocketException ) = 0; - /** - * Gets the reuse address flag. - * @return True if the address can be reused. - * @throws SocketException if the operation fails. - */ - virtual bool getReuseAddress() const throw(SocketException) = 0; + /** + * Gets the reuse address flag. + * @return True if the address can be reused. + * @throws SocketException if the operation fails. + */ + virtual bool getReuseAddress() const throw( SocketException ) = 0; - /** - * Sets the reuse address flag. - * @param reuse If true, sets the flag. - * @throws SocketException if the operation fails. - */ - virtual void setReuseAddress( const bool reuse ) throw(SocketException) = 0; + /** + * Sets the reuse address flag. + * @param reuse If true, sets the flag. + * @throws SocketException if the operation fails. + */ + virtual void setReuseAddress( const bool reuse ) throw( SocketException ) = 0; - /** - * Gets the send buffer size. - * @return the size in bytes of the send buffer. - * @throws SocketException if the operation fails. - */ - virtual int getSendBufferSize() const throw(SocketException) = 0; + /** + * Gets the send buffer size. + * @return the size in bytes of the send buffer. + * @throws SocketException if the operation fails. + */ + virtual int getSendBufferSize() const throw( SocketException ) = 0; - /** - * Sets the send buffer size. - * @param size The number of bytes to set the send buffer to. - * @throws SocketException if the operation fails. - */ - virtual void setSendBufferSize( const int size ) throw(SocketException) = 0; + /** + * Sets the send buffer size. + * @param size The number of bytes to set the send buffer to. + * @throws SocketException if the operation fails. + */ + virtual void setSendBufferSize( const int size ) throw( SocketException ) = 0; - /** - * Gets the timeout for socket operations. - * @return The timeout in milliseconds for socket operations. - * @throws SocketException Thrown if unable to retrieve the information. - */ - virtual int getSoTimeout() const throw(SocketException) = 0; + /** + * Gets the timeout for socket operations. + * @return The timeout in milliseconds for socket operations. + * @throws SocketException Thrown if unable to retrieve the information. + */ + virtual int getSoTimeout() const throw( SocketException ) = 0; - /** - * Sets the timeout for socket operations. - * @param timeout The timeout in milliseconds for socket operations.

- * @throws SocketException Thrown if unable to set the information. - */ - virtual void setSoTimeout( const int timeout ) throw(SocketException) = 0; + /** + * Sets the timeout for socket operations. + * @param timeout The timeout in milliseconds for socket operations.

+ * @throws SocketException Thrown if unable to set the information. + */ + virtual void setSoTimeout( const int timeout ) throw( SocketException ) = 0; - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/network/SocketException.h b/activemq-cpp/src/main/activemq/network/SocketException.h index 17f9d9e9ee..1881814435 100644 --- a/activemq-cpp/src/main/activemq/network/SocketException.h +++ b/activemq-cpp/src/main/activemq/network/SocketException.h @@ -36,12 +36,12 @@ namespace network{ SocketException( const SocketException& ex ){ *(ActiveMQException*)this = ex; } - SocketException(const char* file, const int lineNumber, - const char* msg, ...) + SocketException( const char* file, const int lineNumber, + const char* msg, ...) { - va_list vargs ; - va_start(vargs, msg) ; - buildMessage(msg, vargs) ; + va_list vargs; + va_start(vargs, msg); + buildMessage(msg, vargs); // Set the first mark for this exception. setMark( file, lineNumber ); @@ -57,7 +57,8 @@ namespace network{ } virtual ~SocketException(){} - } ; + + }; }} diff --git a/activemq-cpp/src/main/activemq/network/SocketFactory.cpp b/activemq-cpp/src/main/activemq/network/SocketFactory.cpp index 1a3d1b2a4b..dee8be9e62 100644 --- a/activemq-cpp/src/main/activemq/network/SocketFactory.cpp +++ b/activemq-cpp/src/main/activemq/network/SocketFactory.cpp @@ -27,91 +27,91 @@ using namespace activemq::exceptions; //////////////////////////////////////////////////////////////////////////////// Socket* SocketFactory::createSocket(const Properties& properties) - throw ( SocketException ) + throw ( SocketException ) { - try - { - const char* uri = properties.getProperty( "uri" ); - if( uri == NULL ) - { - throw SocketException( __FILE__, __LINE__, - "SocketTransport::start() - uri not provided" ); - } + try + { + const char* uri = properties.getProperty( "uri" ); + if( uri == NULL ) + { + throw SocketException( __FILE__, __LINE__, + "SocketTransport::start() - uri not provided" ); + } - string dummy = uri; + string dummy = uri; - // Extract the port. - unsigned int portIx = dummy.find( ':' ); - if( portIx == string::npos ) - { - throw SocketException( __FILE__, __LINE__, - "SocketTransport::start() - uri malformed - port not specified: %s", uri); - } - string host = dummy.substr( 0, portIx ); - string portString = dummy.substr( portIx + 1 ); - int port; - if( sscanf( portString.c_str(), "%d", &port) != 1 ) - { - throw SocketException( __FILE__, __LINE__, - "SocketTransport::start() - unable to extract port from uri: %s", uri); - } + // Extract the port. + unsigned int portIx = dummy.find( ':' ); + if( portIx == string::npos ) + { + throw SocketException( __FILE__, __LINE__, + "SocketTransport::start() - uri malformed - port not specified: %s", uri); + } + string host = dummy.substr( 0, portIx ); + string portString = dummy.substr( portIx + 1 ); + int port; + if( sscanf( portString.c_str(), "%d", &port) != 1 ) + { + throw SocketException( __FILE__, __LINE__, + "SocketTransport::start() - unable to extract port from uri: %s", uri); + } - // Get the read buffer size. - int inputBufferSize = 10000; - dummy = properties.getProperty( "inputBufferSize", "10000" ); - sscanf( dummy.c_str(), "%d", &inputBufferSize ); + // Get the read buffer size. + int inputBufferSize = 10000; + dummy = properties.getProperty( "inputBufferSize", "10000" ); + sscanf( dummy.c_str(), "%d", &inputBufferSize ); - // Get the write buffer size. - int outputBufferSize = 10000; - dummy = properties.getProperty( "outputBufferSize", "10000" ); - sscanf( dummy.c_str(), "%d", &outputBufferSize ); + // Get the write buffer size. + int outputBufferSize = 10000; + dummy = properties.getProperty( "outputBufferSize", "10000" ); + sscanf( dummy.c_str(), "%d", &outputBufferSize ); - // Get the linger flag. - int soLinger = 0; - dummy = properties.getProperty( "soLinger", "0" ); - sscanf( dummy.c_str(), "%d", &soLinger ); + // Get the linger flag. + int soLinger = 0; + dummy = properties.getProperty( "soLinger", "0" ); + sscanf( dummy.c_str(), "%d", &soLinger ); - // Get the keepAlive flag. - bool soKeepAlive = - properties.getProperty( "soKeepAlive", "false" ) == "true"; + // Get the keepAlive flag. + bool soKeepAlive = + properties.getProperty( "soKeepAlive", "false" ) == "true"; - // Get the socket receive buffer size. - int soReceiveBufferSize = 2000000; - dummy = properties.getProperty( "soReceiveBufferSize", "2000000" ); - sscanf( dummy.c_str(), "%d", &soReceiveBufferSize ); + // Get the socket receive buffer size. + int soReceiveBufferSize = 2000000; + dummy = properties.getProperty( "soReceiveBufferSize", "2000000" ); + sscanf( dummy.c_str(), "%d", &soReceiveBufferSize ); - // Get the socket send buffer size. - int soSendBufferSize = 2000000; - dummy = properties.getProperty( "soSendBufferSize", "2000000" ); - sscanf( dummy.c_str(), "%d", &soSendBufferSize ); + // Get the socket send buffer size. + int soSendBufferSize = 2000000; + dummy = properties.getProperty( "soSendBufferSize", "2000000" ); + sscanf( dummy.c_str(), "%d", &soSendBufferSize ); - // Get the socket send buffer size. - int soTimeout = 10000; - dummy = properties.getProperty( "soTimeout", "10000" ); - sscanf( dummy.c_str(), "%d", &soTimeout ); + // Get the socket send buffer size. + int soTimeout = 10000; + dummy = properties.getProperty( "soTimeout", "10000" ); + sscanf( dummy.c_str(), "%d", &soTimeout ); - // Now that we have all the elements that we wanted - let's do it! - // Create a TCP Socket and then Wrap it in a buffered socket - // so that users get the benefit of buffered reads and writes. - // The buffered socket will own the TcpSocket instance, and will - // clean it up when it is cleaned up. - TcpSocket* tcpSocket = new TcpSocket(); - BufferedSocket* socket = - new BufferedSocket(tcpSocket, inputBufferSize, outputBufferSize); + // Now that we have all the elements that we wanted - let's do it! + // Create a TCP Socket and then Wrap it in a buffered socket + // so that users get the benefit of buffered reads and writes. + // The buffered socket will own the TcpSocket instance, and will + // clean it up when it is cleaned up. + TcpSocket* tcpSocket = new TcpSocket(); + BufferedSocket* socket = + new BufferedSocket(tcpSocket, inputBufferSize, outputBufferSize); - // Connect the socket. - socket->connect( host.c_str(), port ); + // Connect the socket. + socket->connect( host.c_str(), port ); - // Set the socket options. - socket->setSoLinger( soLinger ); - socket->setKeepAlive( soKeepAlive ); - socket->setReceiveBufferSize( soReceiveBufferSize ); - socket->setSendBufferSize( soSendBufferSize ); - socket->setSoTimeout( soTimeout ); + // Set the socket options. + socket->setSoLinger( soLinger ); + socket->setKeepAlive( soKeepAlive ); + socket->setReceiveBufferSize( soReceiveBufferSize ); + socket->setSendBufferSize( soSendBufferSize ); + socket->setSoTimeout( soTimeout ); - return socket; - } - AMQ_CATCH_RETHROW( SocketException ) - AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, SocketException ) - AMQ_CATCHALL_THROW( SocketException ) + return socket; + } + AMQ_CATCH_RETHROW( SocketException ) + AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, SocketException ) + AMQ_CATCHALL_THROW( SocketException ) } diff --git a/activemq-cpp/src/main/activemq/network/SocketFactory.h b/activemq-cpp/src/main/activemq/network/SocketFactory.h index 956abd0b07..3fde4ec059 100644 --- a/activemq-cpp/src/main/activemq/network/SocketFactory.h +++ b/activemq-cpp/src/main/activemq/network/SocketFactory.h @@ -23,45 +23,42 @@ namespace activemq{ namespace network{ - class Socket; + class Socket; - /** - * Socket Factory implementation for use in Creating Sockets - *

- *

- * Property Options:

- * Name Value

- * -------------------------------------

- * uri The uri for the transport connection. Must be provided.

- * inputBufferSize size in bytes of the buffered input stream buffer. Defaults to 10000.

- * outputBufferSize size in bytes of the buffered output stream buffer. Defaults to 10000.

- * soLinger linger time for the socket (in microseconds). Defaults to 0.

- * soKeepAlive keep alive flag for the socket (true/false). Defaults to false.

- * soReceiveBufferSize The size of the socket receive buffer (in bytes). Defaults to 2MB.

- * soSendBufferSize The size of the socket send buffer (in bytes). Defaults to 2MB.

- * soTimeout The timeout of socket IO operations (in microseconds). Defaults to 10000

- * - * @see Socket - */ - class SocketFactory - { - public: + /** + * Socket Factory implementation for use in Creating Sockets + *

+ *

+ * Property Options:

+ * Name Value

+ * -------------------------------------

+ * uri The uri for the transport connection. Must be provided.

+ * inputBufferSize size in bytes of the buffered input stream buffer. Defaults to 10000.

+ * outputBufferSize size in bytes of the buffered output stream buffer. Defaults to 10000.

+ * soLinger linger time for the socket (in microseconds). Defaults to 0.

+ * soKeepAlive keep alive flag for the socket (true/false). Defaults to false.

+ * soReceiveBufferSize The size of the socket receive buffer (in bytes). Defaults to 2MB.

+ * soSendBufferSize The size of the socket send buffer (in bytes). Defaults to 2MB.

+ * soTimeout The timeout of socket IO operations (in microseconds). Defaults to 10000

+ * + * @see Socket + */ + class SocketFactory + { + public: - /** - * Destructor - */ - virtual ~SocketFactory(); + virtual ~SocketFactory(); - /** - * Creates and returns a Socket dervied Object based on the values - * defined in the Properties Object that is passed in. - * @param a IProperties pointer. - * @throws SocketException. - */ - static Socket* createSocket(const util::Properties& properties) - throw ( SocketException ); + /** + * Creates and returns a Socket dervied Object based on the values + * defined in the Properties Object that is passed in. + * @param a IProperties pointer. + * @throws SocketException. + */ + static Socket* createSocket( const util::Properties& properties ) + throw ( SocketException ); - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/network/SocketInputStream.cpp b/activemq-cpp/src/main/activemq/network/SocketInputStream.cpp index 71229769ae..358ec699c6 100644 --- a/activemq-cpp/src/main/activemq/network/SocketInputStream.cpp +++ b/activemq-cpp/src/main/activemq/network/SocketInputStream.cpp @@ -16,12 +16,12 @@ */ #if (defined(unix) || defined(__APPLE__)) && !defined(__CYGWIN__) - #include - #include - #include - extern int errno; + #include + #include + #include + extern int errno; #else - #include + #include #endif #include @@ -50,7 +50,7 @@ SocketInputStream::~SocketInputStream() int SocketInputStream::available() const{ -#if (defined(unix) || defined(__APPLE__)) && !defined(__CYGWIN__) +#if defined(unix) && !defined(__CYGWIN__) // Poll the socket for input. pollfd fd; @@ -121,7 +121,7 @@ int SocketInputStream::read( unsigned char* buffer, const int bufferSize ) throw // If the socket was temporarily unavailable - just try again. int errorCode = ::WSAGetLastError(); - if( errorCode == WSAEWOULDBLOCK ){ + if( errorCode == WSAEWOULDBLOCK || errorCode == WSAETIMEDOUT ){ continue; } diff --git a/activemq-cpp/src/main/activemq/network/SocketInputStream.h b/activemq-cpp/src/main/activemq/network/SocketInputStream.h index 97cd7c7e09..21f3a27fc6 100644 --- a/activemq-cpp/src/main/activemq/network/SocketInputStream.h +++ b/activemq-cpp/src/main/activemq/network/SocketInputStream.h @@ -57,57 +57,57 @@ namespace network{ /** * Locks the object. */ - virtual void lock() throw(exceptions::ActiveMQException){ + virtual void lock() throw( exceptions::ActiveMQException ){ mutex.lock(); } - /** - * Unlocks the object. - */ - virtual void unlock() throw(exceptions::ActiveMQException){ - mutex.unlock(); - } + /** + * Unlocks the object. + */ + virtual void unlock() throw( exceptions::ActiveMQException ){ + mutex.unlock(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. - */ - virtual void wait() throw(exceptions::ActiveMQException){ - mutex.wait(); - } + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. + */ + virtual void wait() throw( exceptions::ActiveMQException ){ + mutex.wait(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. This wait will timeout after the specified time - * interval. - * @param time in millisecsonds to wait, or WAIT_INIFINITE - * @throws ActiveMQException - */ - virtual void wait(unsigned long millisecs) - throw(exceptions::ActiveMQException) { + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. This wait will timeout after the specified time + * interval. + * @param time in millisecsonds to wait, or WAIT_INIFINITE + * @throws ActiveMQException + */ + virtual void wait( unsigned long millisecs ) + throw( exceptions::ActiveMQException ) { - mutex.wait(millisecs); - } + mutex.wait( millisecs ); + } - /** - * Signals a waiter on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - */ - virtual void notify() throw(exceptions::ActiveMQException){ - mutex.notify(); - } + /** + * Signals a waiter on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + */ + virtual void notify() throw( exceptions::ActiveMQException ){ + mutex.notify(); + } - /** - * Signals the waiters on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - */ - virtual void notifyAll() throw(exceptions::ActiveMQException){ - mutex.notifyAll(); - } + /** + * Signals the waiters on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + */ + virtual void notifyAll() throw( exceptions::ActiveMQException ){ + mutex.notifyAll(); + } /** * Polls instantaneously to see if data is available on @@ -121,7 +121,7 @@ namespace network{ * @return The next byte. * @throws IOException thrown if an error occurs. */ - virtual unsigned char read() throw (io::IOException); + virtual unsigned char read() throw ( io::IOException ); /** * Reads an array of bytes from the buffer. @@ -136,7 +136,8 @@ namespace network{ * Close - does nothing. It is the responsibility of the owner * of the socket object to close it. */ - virtual void close() throw(cms::CMSException){} + virtual void close() throw( cms::CMSException ){} + }; }} diff --git a/activemq-cpp/src/main/activemq/network/SocketOutputStream.h b/activemq-cpp/src/main/activemq/network/SocketOutputStream.h index 655531acc2..7a3b93f902 100644 --- a/activemq-cpp/src/main/activemq/network/SocketOutputStream.h +++ b/activemq-cpp/src/main/activemq/network/SocketOutputStream.h @@ -25,117 +25,125 @@ namespace activemq{ namespace network{ - /** - * Output stream for performing write operations - * on a socket. - */ - class SocketOutputStream : public io::OutputStream - { - private: + /** + * Output stream for performing write operations + * on a socket. + */ + class SocketOutputStream : public io::OutputStream + { + private: - // The socket. - Socket::SocketHandle socket; - concurrent::Mutex mutex; - bool debug; + // The socket. + Socket::SocketHandle socket; + concurrent::Mutex mutex; + bool debug; - public: + public: - /** - * Constructor. - * @param socket the socket handle. - */ - SocketOutputStream( Socket::SocketHandle socket ); + /** + * Constructor. + * @param socket the socket handle. + */ + SocketOutputStream( Socket::SocketHandle socket ); - /** - * Destructor. - */ - virtual ~SocketOutputStream(); - - virtual void setDebug( const bool debug ){ - this->debug = debug; - } - - /** - * Locks the object. - */ - virtual void lock() throw(exceptions::ActiveMQException){ - mutex.lock(); - } - - /** - * Unlocks the object. - */ - virtual void unlock() throw(exceptions::ActiveMQException){ - mutex.unlock(); - } - - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. - */ - virtual void wait() throw(exceptions::ActiveMQException){ - mutex.wait(); - } - - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. This wait will timeout after the specified time - * interval. - * @param time in millisecsonds to wait, or WAIT_INIFINITE - * @throws ActiveMQException - */ - virtual void wait(unsigned long millisecs) - throw(exceptions::ActiveMQException) { - - mutex.wait(millisecs); - } + virtual ~SocketOutputStream(); - /** - * Signals a waiter on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - */ - virtual void notify() throw(exceptions::ActiveMQException){ - mutex.notify(); - } - - /** - * Signals the waiters on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - */ - virtual void notifyAll() throw(exceptions::ActiveMQException){ - mutex.notifyAll(); - } + /** + * Enables Debugging of Socket Data + * @param true to enable + */ + virtual void setDebug( const bool debug ){ + this->debug = debug; + } + + /** + * Locks the object. + * @throws ActiveMQException + */ + virtual void lock() throw( exceptions::ActiveMQException ){ + mutex.lock(); + } + + /** + * Unlocks the object. + * @throws ActiveMQException + */ + virtual void unlock() throw( exceptions::ActiveMQException ){ + mutex.unlock(); + } - /** - * Writes a single byte to the output stream. - * @param c the byte. - * @throws IOException thrown if an error occurs. - */ - virtual void write( const unsigned char c ) throw (io::IOException); + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void wait() throw( exceptions::ActiveMQException ){ + mutex.wait(); + } + + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. This wait will timeout after the specified time + * interval. + * @param time in millisecsonds to wait, or WAIT_INIFINITE + * @throws ActiveMQException + */ + virtual void wait( unsigned long millisecs ) + throw( exceptions::ActiveMQException ) { + + mutex.wait( millisecs ); + } + + /** + * Signals a waiter on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + * @throws ActiveMQException + */ + virtual void notify() throw( exceptions::ActiveMQException ){ + mutex.notify(); + } + + /** + * Signals the waiters on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + */ + virtual void notifyAll() throw( exceptions::ActiveMQException ){ + mutex.notifyAll(); + } + + /** + * Writes a single byte to the output stream. + * @param c the byte. + * @throws IOException thrown if an error occurs. + */ + virtual void write( const unsigned char c ) throw ( io::IOException ); - /** - * Writes an array of bytes to the output stream. - * @param buffer The array of bytes to write. - * @param len The number of bytes from the buffer to be written. - * @throws IOException thrown if an error occurs. - */ - virtual void write( const unsigned char* buffer, const int len ) throw (io::IOException); + /** + * Writes an array of bytes to the output stream. + * @param buffer The array of bytes to write. + * @param len The number of bytes from the buffer to be written. + * @throws IOException thrown if an error occurs. + */ + virtual void write( const unsigned char* buffer, const int len ) throw ( io::IOException ); - /** - * Flush - does nothing. - */ - virtual void flush() throw (io::IOException){}; + /** + * Flush - does nothing. + * @throws IOException + */ + virtual void flush() throw ( io::IOException ){}; - /** - * Close - does nothing. It is the responsibility of the owner - * of the socket object to close it. - */ - virtual void close() throw(cms::CMSException){} - }; + /** + * Close - does nothing. It is the responsibility of the owner + * of the socket object to close it. + * @throws CMSException + */ + virtual void close() throw( cms::CMSException ){} + + }; }} diff --git a/activemq-cpp/src/main/activemq/network/TcpSocket.cpp b/activemq-cpp/src/main/activemq/network/TcpSocket.cpp index a86685e92a..28d900883d 100644 --- a/activemq-cpp/src/main/activemq/network/TcpSocket.cpp +++ b/activemq-cpp/src/main/activemq/network/TcpSocket.cpp @@ -16,19 +16,19 @@ */ #if (defined(unix) || defined(__APPLE__)) && !defined(__CYGWIN__) - #include - #include - #include - #include - #include - #include - #include - extern int errno; + #include + #include + #include + #include + #include + #include + #include + extern int errno; #else - #include - #include - #include - #define stat _stat + #include + #include + #include + #define stat _stat #endif #include @@ -45,278 +45,276 @@ using namespace activemq::network; using namespace activemq::io; +#if !defined( unix ) || defined( __CYGWIN__ ) -#if !(defined( unix ) || defined(__APPLE__)) || defined( __CYGWIN__ ) + // Static socket initializer needed for winsock - // Static socket initializer needed for winsock - - TcpSocket::StaticSocketInitializer::StaticSocketInitializer () { - socketInitError = NULL; - const WORD version_needed = MAKEWORD(2,2); // lo-order byte: major version - WSAData temp; - if (WSAStartup(version_needed, &temp)){ - clear(); + TcpSocket::StaticSocketInitializer::StaticSocketInitializer() { + socketInitError = NULL; + const WORD version_needed = MAKEWORD(2,2); // lo-order byte: major version + WSAData temp; + if( WSAStartup( version_needed, &temp ) ){ + clear(); socketInitError = new SocketException ( __FILE__, __LINE__, - "winsock.dll was not found"); - } - } - TcpSocket::StaticSocketInitializer::~StaticSocketInitializer () { - clear(); - WSACleanup(); - } + "winsock.dll was not found"); + } + } + TcpSocket::StaticSocketInitializer::~StaticSocketInitializer() { + clear(); + WSACleanup(); + } - // Create static instance of the socket initializer. - TcpSocket::StaticSocketInitializer TcpSocket::staticSocketInitializer; + // Create static instance of the socket initializer. + TcpSocket::StaticSocketInitializer TcpSocket::staticSocketInitializer; #endif //////////////////////////////////////////////////////////////////////////////// TcpSocket::TcpSocket() { - socketHandle = INVALID_SOCKET_HANDLE; - inputStream = NULL; - outputStream = NULL; + socketHandle = INVALID_SOCKET_HANDLE; + inputStream = NULL; + outputStream = NULL; -#if !(defined( unix ) || defined(__APPLE__)) || defined( __CYGWIN__ ) - if (staticSocketInitializer.getSocketInitError() != NULL) { - throw *staticSocketInitializer.getSocketInitError(); - } -#endif + #if !defined( unix ) || defined( __CYGWIN__ ) + if( staticSocketInitializer.getSocketInitError() != NULL ) { + throw *staticSocketInitializer.getSocketInitError(); + } + #endif } //////////////////////////////////////////////////////////////////////////////// -TcpSocket::TcpSocket(Socket::SocketHandle socketHandle){ - this->socketHandle = socketHandle; +TcpSocket::TcpSocket( Socket::SocketHandle socketHandle ){ + this->socketHandle = socketHandle; - inputStream = new SocketInputStream( socketHandle ); - outputStream = new SocketOutputStream( socketHandle ); + inputStream = new SocketInputStream( socketHandle ); + outputStream = new SocketOutputStream( socketHandle ); } //////////////////////////////////////////////////////////////////////////////// TcpSocket::~TcpSocket() { - // No shutdown, just close - dont want blocking destructor. - close(); + // No shutdown, just close - dont want blocking destructor. + close(); } //////////////////////////////////////////////////////////////////////////////// InputStream* TcpSocket::getInputStream(){ - return inputStream; + return inputStream; } //////////////////////////////////////////////////////////////////////////////// OutputStream* TcpSocket::getOutputStream(){ - return outputStream; + return outputStream; } //////////////////////////////////////////////////////////////////////////////// -void TcpSocket::connect(const char* host, int port) throw (SocketException) +void TcpSocket::connect(const char* host, int port) throw ( SocketException ) { - if( isConnected() ) { - throw SocketException( __FILE__, __LINE__, - "Socket::connect - Socket already connected. host: %s, port: %d", host, port ); - } + if( isConnected() ) { + throw SocketException( __FILE__, __LINE__, + "Socket::connect - Socket already connected. host: %s, port: %d", host, port ); + } - // Create the socket. - socketHandle = ::socket(AF_INET, SOCK_STREAM, 0); - if( socketHandle < 0 ) { - socketHandle = INVALID_SOCKET_HANDLE; - throw SocketException( __FILE__, __LINE__, ::strerror( errno ) ); - } + // Create the socket. + socketHandle = ::socket(AF_INET, SOCK_STREAM, 0); + if( socketHandle < 0 ) { + socketHandle = INVALID_SOCKET_HANDLE; + throw SocketException( __FILE__, __LINE__, ::strerror( errno ) ); + } - // Check port value. - if (port <= 0 || port > 65535) { - close(); - throw SocketException ( __FILE__, __LINE__, - "Socket::connect- Port out of range: %d", port ); - } + // Check port value. + if (port <= 0 || port > 65535) { + close(); + throw SocketException ( __FILE__, __LINE__, + "Socket::connect- Port out of range: %d", port ); + } - 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)); + 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; + // Resolve name + addrinfo hints; + memset(&hints, 0, sizeof(addrinfo)); + hints.ai_family = PF_INET; + struct addrinfo *res_ptr = NULL; - int status = ::getaddrinfo(host, NULL, &hints, &res_ptr); - if( status != 0 || res_ptr == NULL){ - throw SocketException( __FILE__, __LINE__, - "Socket::connect - %s", ::strerror( errno ) ); - } + int status = ::getaddrinfo( host, NULL, &hints, &res_ptr ); + if( status != 0 || res_ptr == NULL){ + throw SocketException( __FILE__, __LINE__, + "Socket::connect - %s", ::strerror( errno ) ); + } - 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); + 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 ); - // Attempt the connection to the server. - status = ::connect(socketHandle, - (const sockaddr *)&target_addr, - sizeof(target_addr)); + // Attempt the connection to the server. + status = ::connect( socketHandle, + ( const sockaddr * )&target_addr, + sizeof( target_addr ) ); - if( status < 0 ){ - close(); - throw SocketException( __FILE__, __LINE__, - "Socket::connect - %s", ::strerror( errno ) ); - } + if( status < 0 ){ + close(); + throw SocketException( __FILE__, __LINE__, + "Socket::connect - %s", ::strerror( errno ) ); + } - // Create an input/output stream for this socket. - inputStream = new SocketInputStream( socketHandle ); - outputStream = new SocketOutputStream( socketHandle ); + // Create an input/output stream for this socket. + inputStream = new SocketInputStream( socketHandle ); + outputStream = new SocketOutputStream( socketHandle ); } //////////////////////////////////////////////////////////////////////////////// void TcpSocket::close() throw( cms::CMSException ) { - // Destroy the input stream. - if( inputStream != NULL ){ - delete inputStream; - inputStream = NULL; - } + // Destroy the input stream. + if( inputStream != NULL ){ + delete inputStream; + inputStream = NULL; + } - // Destroy the output stream. - if( outputStream != NULL ){ - delete outputStream; - outputStream = NULL; - } + // Destroy the output stream. + if( outputStream != NULL ){ + delete outputStream; + outputStream = NULL; + } - if( isConnected() ) - { - - ::shutdown(socketHandle, 2); + if( isConnected() ) + { + ::shutdown( socketHandle, 2 ); - #if (defined(unix) || defined(__APPLE__)) && !defined(__CYGWIN__) - ::close(socketHandle); - #else - ::closesocket(socketHandle); - #endif + #if defined(unix) && !defined(__CYGWIN__) + ::close( socketHandle ); + #else + ::closesocket( socketHandle ); + #endif - socketHandle = INVALID_SOCKET_HANDLE; - } + socketHandle = INVALID_SOCKET_HANDLE; + } } //////////////////////////////////////////////////////////////////////////////// -int TcpSocket::getSoLinger() const throw(SocketException){ +int TcpSocket::getSoLinger() const throw( SocketException ){ - linger value; - socklen_t length = sizeof(value); - ::getsockopt(socketHandle, SOL_SOCKET, SO_LINGER, (char*)&value, &length ); + linger value; + socklen_t length = sizeof( value ); + ::getsockopt( socketHandle, SOL_SOCKET, SO_LINGER, (char*)&value, &length ); - return value.l_onoff? value.l_linger : 0; + return value.l_onoff? value.l_linger : 0; } //////////////////////////////////////////////////////////////////////////////// -void TcpSocket::setSoLinger( const int dolinger ) throw(SocketException){ +void TcpSocket::setSoLinger( const int dolinger ) throw( SocketException ){ - linger value; - value.l_onoff = dolinger != 0; - value.l_linger = dolinger; - ::setsockopt(socketHandle, SOL_SOCKET, SO_LINGER, (char*)&value, sizeof(value) ); + linger value; + value.l_onoff = dolinger != 0; + value.l_linger = dolinger; + ::setsockopt( socketHandle, SOL_SOCKET, SO_LINGER, (char*)&value, sizeof(value) ); } //////////////////////////////////////////////////////////////////////////////// -bool TcpSocket::getKeepAlive() const throw(SocketException){ +bool TcpSocket::getKeepAlive() const throw( SocketException ){ - int value; - socklen_t length = sizeof(int); - ::getsockopt(socketHandle, SOL_SOCKET, SO_KEEPALIVE, (char*)&value, &length ); - return value != 0; + int value; + socklen_t length = sizeof( int ); + ::getsockopt( socketHandle, SOL_SOCKET, SO_KEEPALIVE, (char*)&value, &length ); + return value != 0; } //////////////////////////////////////////////////////////////////////////////// -void TcpSocket::setKeepAlive( const bool keepAlive ) throw(SocketException){ +void TcpSocket::setKeepAlive( const bool keepAlive ) throw( SocketException ){ - int value = keepAlive? 1 : 0; - ::setsockopt(socketHandle, SOL_SOCKET, SO_KEEPALIVE, (char*)&value, sizeof(int) ); + int value = keepAlive? 1 : 0; + ::setsockopt(socketHandle, SOL_SOCKET, SO_KEEPALIVE, (char*)&value, sizeof(int) ); } //////////////////////////////////////////////////////////////////////////////// -int TcpSocket::getReceiveBufferSize() const throw(SocketException){ +int TcpSocket::getReceiveBufferSize() const throw( SocketException ){ - int value; - socklen_t length = sizeof(int); - ::getsockopt(socketHandle, SOL_SOCKET, SO_RCVBUF, (char*)&value, &length ); - return value; + int value; + socklen_t length = sizeof( int ); + ::getsockopt( socketHandle, SOL_SOCKET, SO_RCVBUF, (char*)&value, &length ); + return value; } //////////////////////////////////////////////////////////////////////////////// -void TcpSocket::setReceiveBufferSize( const int size ) throw(SocketException){ +void TcpSocket::setReceiveBufferSize( const int size ) throw( SocketException ){ - ::setsockopt(socketHandle, SOL_SOCKET, SO_RCVBUF, (char*)&size, sizeof(int) ); + ::setsockopt( socketHandle, SOL_SOCKET, SO_RCVBUF, (char*)&size, sizeof(int) ); } //////////////////////////////////////////////////////////////////////////////// -bool TcpSocket::getReuseAddress() const throw(SocketException){ +bool TcpSocket::getReuseAddress() const throw( SocketException ){ - int value; - socklen_t length = sizeof(int); - ::getsockopt(socketHandle, SOL_SOCKET, SO_REUSEADDR, (char*)&value, &length ); - return value != 0; + int value; + socklen_t length = sizeof( int ); + ::getsockopt( socketHandle, SOL_SOCKET, SO_REUSEADDR, (char*)&value, &length ); + return value != 0; } //////////////////////////////////////////////////////////////////////////////// -void TcpSocket::setReuseAddress( const bool reuse ) throw(SocketException){ +void TcpSocket::setReuseAddress( const bool reuse ) throw( SocketException ){ - int value = reuse? 1 : 0; - ::setsockopt(socketHandle, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int) ); + int value = reuse? 1 : 0; + ::setsockopt( socketHandle, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int) ); } //////////////////////////////////////////////////////////////////////////////// -int TcpSocket::getSendBufferSize() const throw(SocketException){ +int TcpSocket::getSendBufferSize() const throw( SocketException ){ - int value; - socklen_t length = sizeof(int); - ::getsockopt(socketHandle, SOL_SOCKET, SO_SNDBUF, (char*)&value, &length ); - return value; + int value; + socklen_t length = sizeof( int ); + ::getsockopt( socketHandle, SOL_SOCKET, SO_SNDBUF, (char*)&value, &length ); + return value; } //////////////////////////////////////////////////////////////////////////////// -void TcpSocket::setSendBufferSize( const int size ) throw(SocketException){ +void TcpSocket::setSendBufferSize( const int size ) throw( SocketException ){ - ::setsockopt(socketHandle, SOL_SOCKET, SO_SNDBUF, (char*)&size, sizeof(int) ); + ::setsockopt( socketHandle, SOL_SOCKET, SO_SNDBUF, ( char* )&size, sizeof( int ) ); } //////////////////////////////////////////////////////////////////////////////// -void TcpSocket::setSoTimeout ( const int millisecs ) throw (SocketException) +void TcpSocket::setSoTimeout ( const int millisecs ) throw ( SocketException ) { -#if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - timeval timot; - timot.tv_sec = millisecs / 1000; - timot.tv_usec = (millisecs % 1000) * 1000; -#else - int timot = millisecs; -#endif + #if defined( unix ) && !defined( __CYGWIN__ ) + 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)); + ::setsockopt( socketHandle, SOL_SOCKET, SO_RCVTIMEO, (const char*) &timot, sizeof (timot) ); + ::setsockopt( socketHandle, SOL_SOCKET, SO_SNDTIMEO, (const char*) &timot, sizeof (timot) ); } //////////////////////////////////////////////////////////////////////////////// -int TcpSocket::getSoTimeout() const throw(SocketException) +int TcpSocket::getSoTimeout() const throw( SocketException ) { -#if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - timeval timot; - timot.tv_sec = 0; - timot.tv_usec = 0; - socklen_t size = sizeof(timot); -#else - int timot = 0; - int size = sizeof(timot); -#endif + #if defined( unix ) && !defined( __CYGWIN__ ) + 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); + ::getsockopt(socketHandle, SOL_SOCKET, SO_RCVTIMEO, (char*) &timot, &size); -#if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - return (timot.tv_sec * 1000) + (timot.tv_usec / 1000); -#else - return timot; -#endif -} + #if defined( unix ) && !defined( __CYGWIN__ ) + return (timot.tv_sec * 1000) + (timot.tv_usec / 1000); + #else + return timot; + #endif +} diff --git a/activemq-cpp/src/main/activemq/network/TcpSocket.h b/activemq-cpp/src/main/activemq/network/TcpSocket.h index 381474d0cd..0f143ea56f 100644 --- a/activemq-cpp/src/main/activemq/network/TcpSocket.h +++ b/activemq-cpp/src/main/activemq/network/TcpSocket.h @@ -25,209 +25,211 @@ namespace activemq{ namespace network{ - // Forward declarations - class SocketInputStream; - class SocketOutputStream; + // Forward declarations + class SocketInputStream; + class SocketOutputStream; - /** - * Platform-independent implementation of the socket interface. - */ - class TcpSocket : public Socket - { - private: + /** + * Platform-independent implementation of the socket interface. + */ + class TcpSocket : public Socket + { + private: - /** - * The handle for this socket. - */ - SocketHandle socketHandle; + /** + * The handle for this socket. + */ + SocketHandle socketHandle; - /** - * The input stream for reading this socket. - */ - SocketInputStream* inputStream; + /** + * The input stream for reading this socket. + */ + SocketInputStream* inputStream; - /** - * The output stream for writing to this socket. - */ - SocketOutputStream* outputStream; + /** + * The output stream for writing to this socket. + */ + SocketOutputStream* outputStream; - public: + public: - /** - * Construct a non-connected socket. - */ - TcpSocket(); + /** + * Construct a non-connected socket. + */ + TcpSocket(); + + /** + * Construct a connected or bound socket based on given + * socket handle. + */ + TcpSocket( SocketHandle socketHandle ); - /** - * Construct a connected or bound socket based on given - * socket handle. - */ - TcpSocket(SocketHandle socketHandle); + /** + * Destruct. + * Releases the socket handle but not + * gracefully shut down the connection. + */ + virtual ~TcpSocket(); - /** - * Destruct. - * Releases the socket handle but not - * gracefully shut down the connection. - */ - virtual ~TcpSocket(); - - /** - * Gets the handle for the socket. - */ - SocketHandle getSocketHandle () { - return socketHandle; - } + /** + * Gets the handle for the socket. + * @return SocketHabler for this Socket, can be NULL + */ + SocketHandle getSocketHandle () { + return socketHandle; + } - /** - * Connects to the specified destination. Closes this socket if - * connected to another destination. - * @param host The host of the server to connect to. - * @param port The port of the server to connect to. - * @throws IOException Thrown if a failure occurred in the connect. - */ - virtual void connect( const char* host, const int port ) throw(SocketException); + /** + * Connects to the specified destination. Closes this socket if + * connected to another destination. + * @param host The host of the server to connect to. + * @param port The port of the server to connect to. + * @throws IOException Thrown if a failure occurred in the connect. + */ + virtual void connect( const char* host, const int port ) throw( SocketException ); - /** - * Indicates whether or not this socket is connected to a destination. - */ - virtual bool isConnected() const{ - return socketHandle != INVALID_SOCKET_HANDLE; - } + /** + * Indicates whether or not this socket is connected to a destination. + * @return true if connected + */ + virtual bool isConnected() const{ + return socketHandle != INVALID_SOCKET_HANDLE; + } - /** - * Gets the InputStream for this socket. - * @return The InputStream for this socket. NULL if not connected. - */ - virtual io::InputStream* getInputStream(); + /** + * Gets the InputStream for this socket. + * @return The InputStream for this socket. NULL if not connected. + */ + virtual io::InputStream* getInputStream(); - /** - * Gets the OutputStream for this socket. - * @return the OutputStream for this socket. NULL if not connected. - */ - virtual io::OutputStream* getOutputStream(); + /** + * Gets the OutputStream for this socket. + * @return the OutputStream for this socket. NULL if not connected. + */ + virtual io::OutputStream* getOutputStream(); - /** - * Gets the linger time. - * @return The linger time in seconds. - * @throws SocketException if the operation fails. - */ - virtual int getSoLinger() const throw(SocketException); + /** + * Gets the linger time. + * @return The linger time in seconds. + * @throws SocketException if the operation fails. + */ + virtual int getSoLinger() const throw( SocketException ); - /** - * Sets the linger time. - * @param linger The linger time in seconds. If 0, linger is off. - * @throws SocketException if the operation fails. - */ - virtual void setSoLinger( const int linger ) throw(SocketException); + /** + * Sets the linger time. + * @param linger The linger time in seconds. If 0, linger is off. + * @throws SocketException if the operation fails. + */ + virtual void setSoLinger( const int linger ) throw( SocketException ); - /** - * Gets the keep alive flag. - * @return True if keep alive is enabled. - * @throws SocketException if the operation fails. - */ - virtual bool getKeepAlive() const throw(SocketException); + /** + * Gets the keep alive flag. + * @return True if keep alive is enabled. + * @throws SocketException if the operation fails. + */ + virtual bool getKeepAlive() const throw( SocketException ); - /** - * Enables/disables the keep alive flag. - * @param keepAlive If true, enables the flag. - * @throws SocketException if the operation fails. - */ - virtual void setKeepAlive( const bool keepAlive ) throw(SocketException); + /** + * Enables/disables the keep alive flag. + * @param keepAlive If true, enables the flag. + * @throws SocketException if the operation fails. + */ + virtual void setKeepAlive( const bool keepAlive ) throw( SocketException ); - /** - * Gets the receive buffer size. - * @return the receive buffer size in bytes. - * @throws SocketException if the operation fails. - */ - virtual int getReceiveBufferSize() const throw(SocketException); + /** + * Gets the receive buffer size. + * @return the receive buffer size in bytes. + * @throws SocketException if the operation fails. + */ + virtual int getReceiveBufferSize() const throw( SocketException ); - /** - * Sets the recieve buffer size. - * @param size Number of bytes to set the receive buffer to. - * @throws SocketException if the operation fails. - */ - virtual void setReceiveBufferSize( const int size ) throw(SocketException); + /** + * Sets the recieve buffer size. + * @param size Number of bytes to set the receive buffer to. + * @throws SocketException if the operation fails. + */ + virtual void setReceiveBufferSize( const int size ) throw( SocketException ); - /** - * Gets the reuse address flag. - * @return True if the address can be reused. - * @throws SocketException if the operation fails. - */ - virtual bool getReuseAddress() const throw(SocketException); + /** + * Gets the reuse address flag. + * @return True if the address can be reused. + * @throws SocketException if the operation fails. + */ + virtual bool getReuseAddress() const throw( SocketException ); - /** - * Sets the reuse address flag. - * @param reuse If true, sets the flag. - * @throws SocketException if the operation fails. - */ - virtual void setReuseAddress( const bool reuse ) throw(SocketException); + /** + * Sets the reuse address flag. + * @param reuse If true, sets the flag. + * @throws SocketException if the operation fails. + */ + virtual void setReuseAddress( const bool reuse ) throw( SocketException ); - /** - * Gets the send buffer size. - * @return the size in bytes of the send buffer. - * @throws SocketException if the operation fails. - */ - virtual int getSendBufferSize() const throw(SocketException); + /** + * Gets the send buffer size. + * @return the size in bytes of the send buffer. + * @throws SocketException if the operation fails. + */ + virtual int getSendBufferSize() const throw( SocketException ); - /** - * Sets the send buffer size. - * @param size The number of bytes to set the send buffer to. - * @throws SocketException if the operation fails. - */ - virtual void setSendBufferSize( const int size ) throw(SocketException); + /** + * Sets the send buffer size. + * @param size The number of bytes to set the send buffer to. + * @throws SocketException if the operation fails. + */ + virtual void setSendBufferSize( const int size ) throw( SocketException ); - /** - * Gets the timeout for socket operations. - * @return The timeout in milliseconds for socket operations. - * @throws SocketException Thrown if unable to retrieve the information. - */ - virtual int getSoTimeout() const throw(SocketException); + /** + * Gets the timeout for socket operations. + * @return The timeout in milliseconds for socket operations. + * @throws SocketException Thrown if unable to retrieve the information. + */ + virtual int getSoTimeout() const throw( SocketException ); - /** - * Sets the timeout for socket operations. - * @param timeout The timeout in milliseconds for socket operations.

- * @throws SocketException Thrown if unable to set the information. - */ - virtual void setSoTimeout( const int timeout ) throw(SocketException); + /** + * Sets the timeout for socket operations. + * @param timeout The timeout in milliseconds for socket operations.

+ * @throws SocketException Thrown if unable to set the information. + */ + virtual void setSoTimeout( const int timeout ) throw(SocketException); - /** - * Closes this object and deallocates the appropriate resources. - * @throws CMSException - */ - virtual void close() throw( cms::CMSException ); + /** + * Closes this object and deallocates the appropriate resources. + * @throws CMSException + */ + virtual void close() throw( cms::CMSException ); - protected: + protected: - #if !defined( unix ) || defined( __CYGWIN__ ) + #if !defined( unix ) || defined( __CYGWIN__ ) - // WINDOWS needs initialization of winsock - class StaticSocketInitializer { - private: + // WINDOWS needs initialization of winsock + class StaticSocketInitializer { + private: - SocketException* socketInitError; + SocketException* socketInitError; - void clear(){ - if( socketInitError != NULL ){ - delete socketInitError; - } - socketInitError = NULL; - } + void clear(){ + if( socketInitError != NULL ){ + delete socketInitError; + } + socketInitError = NULL; + } - public: + public: - SocketException* getSocketInitError () { - return socketInitError; - } + SocketException* getSocketInitError() { + return socketInitError; + } - StaticSocketInitializer(); - virtual ~StaticSocketInitializer (); + StaticSocketInitializer(); + virtual ~StaticSocketInitializer(); - }; + }; - static StaticSocketInitializer staticSocketInitializer; - #endif + static StaticSocketInitializer staticSocketInitializer; + #endif - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/transport/BrokerError.h b/activemq-cpp/src/main/activemq/transport/BrokerError.h index 85541f3e08..53e27028ea 100644 --- a/activemq-cpp/src/main/activemq/transport/BrokerError.h +++ b/activemq-cpp/src/main/activemq/transport/BrokerError.h @@ -24,12 +24,12 @@ namespace activemq{ namespace transport{ - /** - * A distributed exception that implies that an error occurred at - * the broker. - */ - class BrokerError : public exceptions::ActiveMQException{ - public: + /** + * A distributed exception that implies that an error occurred at + * the broker. + */ + class BrokerError : public exceptions::ActiveMQException{ + public: BrokerError(){}; BrokerError( const exceptions::ActiveMQException& ex ){ @@ -60,7 +60,7 @@ namespace transport{ virtual ~BrokerError(){} - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/transport/Command.h b/activemq-cpp/src/main/activemq/transport/Command.h index 4989c5c9d8..be57c62947 100644 --- a/activemq-cpp/src/main/activemq/transport/Command.h +++ b/activemq-cpp/src/main/activemq/transport/Command.h @@ -21,8 +21,8 @@ namespace activemq{ namespace transport{ - class Command{ - public: + class Command{ + public: virtual ~Command(void){} @@ -50,7 +50,7 @@ namespace transport{ */ virtual bool isResponseRequired() const = 0; - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/transport/CommandIOException.h b/activemq-cpp/src/main/activemq/transport/CommandIOException.h index 4473f96159..3234d1499a 100644 --- a/activemq-cpp/src/main/activemq/transport/CommandIOException.h +++ b/activemq-cpp/src/main/activemq/transport/CommandIOException.h @@ -24,8 +24,8 @@ namespace activemq{ namespace transport{ - class CommandIOException : public io::IOException{ - public: + class CommandIOException : public io::IOException{ + public: CommandIOException(){}; CommandIOException( const exceptions::ActiveMQException& ex ){ @@ -34,12 +34,12 @@ namespace transport{ CommandIOException( const CommandIOException& ex ){ *(exceptions::ActiveMQException*)this = ex; } - CommandIOException(const char* file, const int lineNumber, - const char* msg, ...) + CommandIOException( const char* file, const int lineNumber, + const char* msg, ... ) { - va_list vargs ; - va_start(vargs, msg) ; - buildMessage(msg, vargs) ; + va_list vargs; + va_start( vargs, msg ); + buildMessage( msg, vargs ); // Set the first mark for this exception. setMark( file, lineNumber ); @@ -55,7 +55,7 @@ namespace transport{ } virtual ~CommandIOException(){} - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/transport/ExceptionResponse.h b/activemq-cpp/src/main/activemq/transport/ExceptionResponse.h index 17be16fe9a..f811614e1c 100644 --- a/activemq-cpp/src/main/activemq/transport/ExceptionResponse.h +++ b/activemq-cpp/src/main/activemq/transport/ExceptionResponse.h @@ -24,12 +24,12 @@ namespace activemq{ namespace transport{ - /** - * A response object that indicates an error occurred at the - * broker. - */ - class ExceptionResponse : public Response{ - public: + /** + * A response object that indicates an error occurred at the + * broker. + */ + class ExceptionResponse : public Response{ + public: virtual ~ExceptionResponse(){} @@ -38,7 +38,7 @@ namespace transport{ */ virtual const BrokerError* getException() const = 0; - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/transport/FutureResponse.h b/activemq-cpp/src/main/activemq/transport/FutureResponse.h index a1eb4998f6..f62fbafc33 100644 --- a/activemq-cpp/src/main/activemq/transport/FutureResponse.h +++ b/activemq-cpp/src/main/activemq/transport/FutureResponse.h @@ -50,14 +50,14 @@ namespace transport{ /** * Locks the object. */ - virtual void lock() throw(exceptions::ActiveMQException){ + virtual void lock() throw( exceptions::ActiveMQException ){ mutex.lock(); } /** * Unlocks the object. */ - virtual void unlock() throw(exceptions::ActiveMQException){ + virtual void unlock() throw( exceptions::ActiveMQException ){ mutex.unlock(); } @@ -66,7 +66,7 @@ namespace transport{ * by a call to Notify. Must have this object locked before * calling. */ - virtual void wait() throw(exceptions::ActiveMQException){ + virtual void wait() throw( exceptions::ActiveMQException ){ mutex.wait(); } @@ -78,8 +78,8 @@ namespace transport{ * @param time in millisecsonds to wait, or WAIT_INIFINITE * @throws ActiveMQException */ - virtual void wait(unsigned long millisecs) - throw(exceptions::ActiveMQException) + virtual void wait( unsigned long millisecs ) + throw( exceptions::ActiveMQException ) { mutex.wait( millisecs ); } @@ -89,7 +89,7 @@ namespace transport{ * up and continue. Must have this object locked before * calling. */ - virtual void notify() throw(exceptions::ActiveMQException){ + virtual void notify() throw( exceptions::ActiveMQException ){ mutex.notify(); } @@ -98,7 +98,7 @@ namespace transport{ * up and continue. Must have this object locked before * calling. */ - virtual void notifyAll() throw(exceptions::ActiveMQException){ + virtual void notifyAll() throw( exceptions::ActiveMQException ){ mutex.notifyAll(); } diff --git a/activemq-cpp/src/main/activemq/transport/IOTransport.h b/activemq-cpp/src/main/activemq/transport/IOTransport.h index 9b12e7f66e..01ef3849c1 100644 --- a/activemq-cpp/src/main/activemq/transport/IOTransport.h +++ b/activemq-cpp/src/main/activemq/transport/IOTransport.h @@ -136,13 +136,13 @@ namespace transport{ * @throws UnsupportedOperationException if this method is not implemented * by this transport. */ - virtual void oneway( Command* command ) throw(CommandIOException, exceptions::UnsupportedOperationException); + virtual void oneway( Command* command ) throw( CommandIOException, exceptions::UnsupportedOperationException ); /** * Not supported by this class - throws an exception. * @throws UnsupportedOperationException. */ - virtual Response* request( Command* command ) throw(CommandIOException, exceptions::UnsupportedOperationException){ + virtual Response* request( Command* command ) throw( CommandIOException, exceptions::UnsupportedOperationException ){ throw exceptions::UnsupportedOperationException( __FILE__, __LINE__, "IOTransport::request() - unsupported operation" ); } diff --git a/activemq-cpp/src/main/activemq/transport/Response.h b/activemq-cpp/src/main/activemq/transport/Response.h index 9f1d01d3bc..c5b1afc9e2 100644 --- a/activemq-cpp/src/main/activemq/transport/Response.h +++ b/activemq-cpp/src/main/activemq/transport/Response.h @@ -23,8 +23,8 @@ namespace activemq{ namespace transport{ - class Response : public Command{ - public: + class Response : public Command{ + public: virtual ~Response(void) {} @@ -40,7 +40,7 @@ namespace transport{ */ virtual void setCorrelationId( const unsigned int corrId ) = 0; - }; + }; }} diff --git a/activemq-cpp/src/main/activemq/transport/ResponseCorrelator.h b/activemq-cpp/src/main/activemq/transport/ResponseCorrelator.h index 5346cbf6a3..60bf847bdd 100644 --- a/activemq-cpp/src/main/activemq/transport/ResponseCorrelator.h +++ b/activemq-cpp/src/main/activemq/transport/ResponseCorrelator.h @@ -74,7 +74,7 @@ namespace transport{ /** * Returns the next available command id. */ - unsigned int getNextCommandId() throw (exceptions::ActiveMQException){ + unsigned int getNextCommandId() throw ( exceptions::ActiveMQException ){ try{ synchronized( &commandIdMutex ){ @@ -143,7 +143,7 @@ namespace transport{ * by this transport. */ virtual void oneway( Command* command ) - throw(CommandIOException, exceptions::UnsupportedOperationException) + throw( CommandIOException, exceptions::UnsupportedOperationException ) { try{ @@ -171,7 +171,7 @@ namespace transport{ * @throws CommandIOException if an error occurs with the request. */ virtual Response* request( Command* command ) - throw(CommandIOException, exceptions::UnsupportedOperationException) + throw( CommandIOException, exceptions::UnsupportedOperationException ) { try{ @@ -243,7 +243,7 @@ namespace transport{ // Let's see if the incoming command is a response. Response* response = - dynamic_cast(command); + dynamic_cast( command ); if( response == NULL ){ @@ -271,7 +271,7 @@ namespace transport{ // If it's an exception response, notify the exception listener. ExceptionResponse* exResp = - dynamic_cast(response); + dynamic_cast( response ); if( exResp != NULL ){ const BrokerError* error = exResp->getException(); fire( *error ); diff --git a/activemq-cpp/src/main/activemq/transport/TcpTransport.cpp b/activemq-cpp/src/main/activemq/transport/TcpTransport.cpp index b47d8718e6..24760234c8 100644 --- a/activemq-cpp/src/main/activemq/transport/TcpTransport.cpp +++ b/activemq-cpp/src/main/activemq/transport/TcpTransport.cpp @@ -39,7 +39,7 @@ TcpTransport::TcpTransport( const activemq::util::Properties& properties, // Create the IO device we will be communicating over the // wire with. This may need to change if we add more types // of sockets, such as SSL. - socket = SocketFactory::createSocket(properties); + socket = SocketFactory::createSocket( properties ); // Cast it to an IO transport so we can wire up the socket // input and output streams. diff --git a/activemq-cpp/src/main/activemq/transport/TcpTransportFactory.cpp b/activemq-cpp/src/main/activemq/transport/TcpTransportFactory.cpp index b1ee8849e6..12d568e1d1 100644 --- a/activemq-cpp/src/main/activemq/transport/TcpTransportFactory.cpp +++ b/activemq-cpp/src/main/activemq/transport/TcpTransportFactory.cpp @@ -29,7 +29,7 @@ TransportFactory& TcpTransportFactory::getInstance(void) { // Create the one and only instance of the registrar static TransportFactoryMapRegistrar registrar( - "tcp", new TcpTransportFactory()); + "tcp", new TcpTransportFactory() ); return registrar.getFactory(); } diff --git a/activemq-cpp/src/main/activemq/transport/Transport.h b/activemq-cpp/src/main/activemq/transport/Transport.h index 78d982f3bd..71479a9d47 100644 --- a/activemq-cpp/src/main/activemq/transport/Transport.h +++ b/activemq-cpp/src/main/activemq/transport/Transport.h @@ -30,78 +30,78 @@ namespace activemq{ namespace transport{ - // Forward declarations. - class CommandListener; - class CommandReader; - class CommandWriter; - class TransportExceptionListener; + // Forward declarations. + class CommandListener; + class CommandReader; + class CommandWriter; + class TransportExceptionListener; - /** - * Interface for a transport layer for command objects. Callers can - * send oneway messages or make synchronous requests. Non-response - * messages will be delivered to the specified listener object upon - * receipt. - */ - class Transport - : - public cms::Startable, - public cms::Closeable - { - public: + /** + * Interface for a transport layer for command objects. Callers can + * send oneway messages or make synchronous requests. Non-response + * messages will be delivered to the specified listener object upon + * receipt. + */ + class Transport + : + public cms::Startable, + public cms::Closeable + { + public: - virtual ~Transport(){} + virtual ~Transport(){} - /** - * Sends a one-way command. Does not wait for any response from the - * broker. - * @param command the command to be sent. - * @throws CommandIOException if an exception occurs during writing of - * the command. - * @throws UnsupportedOperationException if this method is not implemented - * by this transport. - */ - virtual void oneway( Command* command ) - throw(CommandIOException, - exceptions::UnsupportedOperationException) = 0; + /** + * Sends a one-way command. Does not wait for any response from the + * broker. + * @param command the command to be sent. + * @throws CommandIOException if an exception occurs during writing of + * the command. + * @throws UnsupportedOperationException if this method is not implemented + * by this transport. + */ + virtual void oneway( Command* command ) + throw( CommandIOException, + exceptions::UnsupportedOperationException ) = 0; - /** - * Sends the given command to the broker and then waits for the response. - * @param command the command to be sent. - * @return the response from the broker. - * @throws CommandIOException if an exception occurs during the read of the - * command. - * @throws UnsupportedOperationException if this method is not implemented - * by this transport. - */ - virtual Response* request( Command* command ) - throw(CommandIOException, - exceptions::UnsupportedOperationException) = 0; + /** + * Sends the given command to the broker and then waits for the response. + * @param command the command to be sent. + * @return the response from the broker. + * @throws CommandIOException if an exception occurs during the read of the + * command. + * @throws UnsupportedOperationException if this method is not implemented + * by this transport. + */ + virtual Response* request( Command* command ) + throw( CommandIOException, + exceptions::UnsupportedOperationException ) = 0; - /** - * Assigns the command listener for non-response commands. - * @param listener the listener. - */ - virtual void setCommandListener( CommandListener* listener ) = 0; + /** + * Assigns the command listener for non-response commands. + * @param listener the listener. + */ + virtual void setCommandListener( CommandListener* listener ) = 0; - /** - * Sets the command reader. - * @param reader the object that will be used for reading command objects. - */ - virtual void setCommandReader( CommandReader* reader ) = 0; + /** + * Sets the command reader. + * @param reader the object that will be used for reading command objects. + */ + virtual void setCommandReader( CommandReader* reader ) = 0; - /** - * Sets the command writer. - * @param writer the object that will be used for writing command objects. - */ - virtual void setCommandWriter( CommandWriter* writer ) = 0; + /** + * Sets the command writer. + * @param writer the object that will be used for writing command objects. + */ + virtual void setCommandWriter( CommandWriter* writer ) = 0; - /** - * Sets the observer of asynchronous exceptions from this transport. - * @param listener the listener of transport exceptions. - */ - virtual void setTransportExceptionListener( - TransportExceptionListener* listener ) = 0; - }; + /** + * Sets the observer of asynchronous exceptions from this transport. + * @param listener the listener of transport exceptions. + */ + virtual void setTransportExceptionListener( + TransportExceptionListener* listener ) = 0; + }; }} diff --git a/activemq-cpp/src/main/activemq/transport/TransportExceptionListener.h b/activemq-cpp/src/main/activemq/transport/TransportExceptionListener.h index 68a18b61b5..f60477b991 100644 --- a/activemq-cpp/src/main/activemq/transport/TransportExceptionListener.h +++ b/activemq-cpp/src/main/activemq/transport/TransportExceptionListener.h @@ -23,26 +23,27 @@ namespace activemq{ namespace transport{ - // Forward declarations. - class Transport; + // Forward declarations. + class Transport; - /** - * A listener of asynchronous exceptions from a command transport object. - */ - class TransportExceptionListener{ - public: + /** + * A listener of asynchronous exceptions from a command transport object. + */ + class TransportExceptionListener{ + public: - virtual ~TransportExceptionListener(){} + virtual ~TransportExceptionListener(){} - /** - * Event handler for an exception from a command transport. - * @param source The source of the exception - * @param ex The exception. - */ - virtual void onTransportException( - Transport* source, - const exceptions::ActiveMQException& ex ) = 0; - }; + /** + * Event handler for an exception from a command transport. + * @param source The source of the exception + * @param ex The exception. + */ + virtual void onTransportException( + Transport* source, + const exceptions::ActiveMQException& ex ) = 0; + + }; }} diff --git a/activemq-cpp/src/main/activemq/transport/TransportFactoryMap.cpp b/activemq-cpp/src/main/activemq/transport/TransportFactoryMap.cpp index 446dad6042..af427fc4ee 100644 --- a/activemq-cpp/src/main/activemq/transport/TransportFactoryMap.cpp +++ b/activemq-cpp/src/main/activemq/transport/TransportFactoryMap.cpp @@ -39,7 +39,7 @@ void TransportFactoryMap::registerTransportFactory( const string& name, //////////////////////////////////////////////////////////////////////////////// void TransportFactoryMap::unregisterTransportFactory( const string& name ){ - factoryMap.erase(name); + factoryMap.erase( name ); } //////////////////////////////////////////////////////////////////////////////// @@ -48,7 +48,7 @@ TransportFactory* TransportFactoryMap::lookup( const string& name ){ map::const_iterator itr = factoryMap.find(name); - if(itr != factoryMap.end()) + if( itr != factoryMap.end() ) { return itr->second; } @@ -58,13 +58,13 @@ TransportFactory* TransportFactoryMap::lookup( const string& name ){ } //////////////////////////////////////////////////////////////////////////////// -size_t TransportFactoryMap::getFactoryNames(vector& factoryList){ +size_t TransportFactoryMap::getFactoryNames( vector< string >& factoryList ){ map::const_iterator itr = factoryMap.begin(); for(; itr != factoryMap.end(); ++itr) { - factoryList.insert(factoryList.end(), itr->first); + factoryList.insert( factoryList.end(), itr->first ); } return factoryMap.size(); diff --git a/activemq-cpp/src/main/activemq/transport/TransportFactoryMap.h b/activemq-cpp/src/main/activemq/transport/TransportFactoryMap.h index efd35113df..52524432b3 100644 --- a/activemq-cpp/src/main/activemq/transport/TransportFactoryMap.h +++ b/activemq-cpp/src/main/activemq/transport/TransportFactoryMap.h @@ -46,10 +46,10 @@ namespace transport{ virtual ~TransportFactoryMap() {}; // Hidden Copy Constructore - TransportFactoryMap(const TransportFactoryMap& factoryMap){}; + TransportFactoryMap( const TransportFactoryMap& factoryMap ){}; // Hidden Assignment operator - TransportFactoryMap& operator=(const TransportFactoryMap& factoryMap){ + TransportFactoryMap& operator=( const TransportFactoryMap& factoryMap ){ return *this; } @@ -66,7 +66,7 @@ namespace transport{ * @param factory to store. */ void registerTransportFactory( const std::string& name, - TransportFactory* factory ); + TransportFactory* factory ); /** * Unregisters a Transport Factory with this map @@ -86,7 +86,7 @@ namespace transport{ * @param vector object to receive the list * @returns count of factories. */ - std::size_t getFactoryNames(std::vector& factoryList); + std::size_t getFactoryNames( std::vector& factoryList ); }; diff --git a/activemq-cpp/src/main/activemq/transport/TransportFactoryMapRegistrar.h b/activemq-cpp/src/main/activemq/transport/TransportFactoryMapRegistrar.h index c244e243fd..1237a012be 100644 --- a/activemq-cpp/src/main/activemq/transport/TransportFactoryMapRegistrar.h +++ b/activemq-cpp/src/main/activemq/transport/TransportFactoryMapRegistrar.h @@ -38,7 +38,7 @@ namespace transport{ * @param boolean indicating if this object manages the lifetime of * the factory that is being registered. */ - TransportFactoryMapRegistrar(const std::string& name, + TransportFactoryMapRegistrar( const std::string& name, TransportFactory* factory, bool manageLifetime = true) { @@ -58,9 +58,9 @@ namespace transport{ { // UnRegister it in the map. TransportFactoryMap::getInstance(). - unregisterTransportFactory(name); + unregisterTransportFactory( name ); - if(manageLifetime) + if( manageLifetime ) { delete factory; } diff --git a/activemq-cpp/src/main/activemq/util/Boolean.h b/activemq-cpp/src/main/activemq/util/Boolean.h index e7b1a5ce7f..4939324ee9 100644 --- a/activemq-cpp/src/main/activemq/util/Boolean.h +++ b/activemq-cpp/src/main/activemq/util/Boolean.h @@ -27,15 +27,15 @@ namespace util{ { public: - Boolean(void) {} - virtual ~Boolean(void) {} + Boolean(void) {} + virtual ~Boolean(void) {} /** * Parses the String passed and extracts an bool. * @param String to parse * @return bool value */ - static int parseBoolean(const std::string& value){ + static int parseBoolean( const std::string& value ){ bool ret = 0; std::istringstream istream(value); istream.clear(); @@ -48,7 +48,7 @@ namespace util{ * @param bool to convert * @return string representation */ - static std::string toString(bool value){ + static std::string toString( bool value ){ std::ostringstream ostream; ostream << std::boolalpha << value; return ostream.str(); diff --git a/activemq-cpp/src/main/activemq/util/Endian.h b/activemq-cpp/src/main/activemq/util/Endian.h index eec7dc95a1..74962e20b6 100644 --- a/activemq-cpp/src/main/activemq/util/Endian.h +++ b/activemq-cpp/src/main/activemq/util/Endian.h @@ -103,7 +103,7 @@ // Macros and helpers for endian conversion namespace activemq{ namespace util{ - + /*#ifdef IFR_IS_BIGENDIAN inline unsigned int htoni (unsigned int i) { return i; } inline unsigned long long htonll (unsigned long long ll) { return ll; } @@ -117,18 +117,18 @@ inline double ntohd (double d) { return d; } inline unsigned int htoni (unsigned int i) { return ( i << 8 ) & 0xFF00 | - ( i >> 8 ) & 0x00FF; + ( i >> 8 ) & 0x00FF; } inline unsigned long long htonll (unsigned long long ll) { return ( ll << 56 ) & 0xFF00000000000000ULL | - ( ll << 40 ) & 0x00FF000000000000ULL | - ( ll << 24 ) & 0x0000FF0000000000ULL | - ( ll << 8 ) & 0x000000FF00000000ULL | + ( ll << 40 ) & 0x00FF000000000000ULL | + ( ll << 24 ) & 0x0000FF0000000000ULL | + ( ll << 8 ) & 0x000000FF00000000ULL | ( ll >> 8 ) & 0x00000000FF000000ULL | - ( ll >> 24 ) & 0x0000000000FF0000ULL | - ( ll >> 40 ) & 0x000000000000FF00ULL | - ( ll >> 56 ) & 0x00000000000000FFULL; + ( ll >> 24 ) & 0x0000000000FF0000ULL | + ( ll >> 40 ) & 0x000000000000FF00ULL | + ( ll >> 56 ) & 0x00000000000000FFULL; } @@ -145,53 +145,53 @@ inline unsigned long long ntohll (unsigned long long ll) { return htonll (ll); inline float ntohf (float f) { return htonf (f); } inline double ntohd (double d) { return htond (d); } */ - class Endian{ - public: - - static void byteSwap(unsigned char* data, int dataLength) { - - #ifdef IFR_IS_BIGENDIAN - return; - #endif - - for (int i = 0; i(&uuid))) == 1 ? true : false; - #else - RPC_STATUS status; + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + // Check the uuid APIs is null method + return uuid_is_null(*(const_cast(&uuid))) == 1 ? true : false; + #else + RPC_STATUS status; - BOOL result = ::UuidIsNil( const_cast( &uuid ), &status ); + BOOL result = ::UuidIsNil( const_cast( &uuid ), &status ); - return (result == TRUE) ? true : false; + return (result == TRUE) ? true : false; #endif } //////////////////////////////////////////////////////////////////////////////// void Guid::setNull(void) { - #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - // use the uuid function to clear - uuid_clear(uuid); - #else - ::UuidCreateNil(&uuid); - #endif + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + // use the uuid function to clear + uuid_clear(uuid); + #else + ::UuidCreateNil(&uuid); + #endif } //////////////////////////////////////////////////////////////////////////////// Guid& Guid::createGUID(void) throw( RuntimeException ) { - #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - // Use the uuid_generate method to create a new GUID - uuid_generate(uuid); - #else - // Create a uuid with the Co Create GUID - RPC_STATUS lhResult = ::UuidCreate( &uuid ); + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + // Use the uuid_generate method to create a new GUID + uuid_generate(uuid); + #else + // Create a uuid with the Co Create GUID + RPC_STATUS lhResult = ::UuidCreate( &uuid ); - if ( lhResult == RPC_S_UUID_NO_ADDRESS ) - { - throw RuntimeException( - __FILE__, __LINE__, - "GUIG::createGUID - Failed Creating GUID"); - } - #endif + if ( lhResult == RPC_S_UUID_NO_ADDRESS ) + { + throw RuntimeException( + __FILE__, __LINE__, + "GUIG::createGUID - Failed Creating GUID"); + } + #endif - return *this; + return *this; } //////////////////////////////////////////////////////////////////////////////// std::string Guid::toString(void) const throw( RuntimeException ) { - std::string uuid_str = ""; + std::string uuid_str = ""; - #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - // Create storage for the string buffer - char buffer[36] = {0}; + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + // Create storage for the string buffer + char buffer[36] = {0}; - // parse the uuid to the string - uuid_unparse(*(const_cast(&uuid)), buffer); + // parse the uuid to the string + uuid_unparse(*(const_cast(&uuid)), buffer); - // Store it in a string - uuid_str = buffer; - #else - // Convert the GUID object to a string. - unsigned char* guidStr = 0; + // Store it in a string + uuid_str = buffer; + #else + // Convert the GUID object to a string. + unsigned char* guidStr = 0; - RPC_STATUS result = ::UuidToString( - const_cast(&uuid), - &guidStr); + RPC_STATUS result = ::UuidToString( + const_cast(&uuid), &guidStr); - if(result == RPC_S_OUT_OF_MEMORY) - { - throw RuntimeException( - __FILE__, __LINE__, - "GUIG::createGUID - Failed Creating GUID"); - } + if(result == RPC_S_OUT_OF_MEMORY) + { + throw RuntimeException( + __FILE__, __LINE__, + "GUIG::createGUID - Failed Creating GUID"); + } - uuid_str = (char*)guidStr; + uuid_str = (char*)guidStr; - // Dispose of the GUID string. - ::RpcStringFree(&guidStr); - #endif + // Dispose of the GUID string. + ::RpcStringFree(&guidStr); + #endif - return uuid_str; + return uuid_str; } //////////////////////////////////////////////////////////////////////////////// Guid::operator std::string() const { - return toString(); + return toString(); } //////////////////////////////////////////////////////////////////////////////// const unsigned char* Guid::toBytes(void) const { - unsigned char* buffer = new unsigned char[getRawBytesSize()]; + unsigned char* buffer = new unsigned char[getRawBytesSize()]; - // copy our buffer - #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - uuid_copy(buffer, *(const_cast(&uuid))); - #else - memcpy(buffer, &uuid, getRawBytesSize()); - #endif + // copy our buffer + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + uuid_copy(buffer, *(const_cast(&uuid))); + #else + memcpy(buffer, &uuid, getRawBytesSize()); + #endif - return &buffer[0]; + return &buffer[0]; } //////////////////////////////////////////////////////////////////////////////// -Guid& Guid::fromBytes(const unsigned char* bytes) +Guid& Guid::fromBytes( const unsigned char* bytes ) throw ( IllegalArgumentException ) { - if(bytes == NULL) - { - throw IllegalArgumentException( - __FILE__, __LINE__, - "GUID::fromBytes - bytes pointer was NULL"); - } + if(bytes == NULL) + { + throw IllegalArgumentException( + __FILE__, __LINE__, + "GUID::fromBytes - bytes pointer was NULL"); + } - // Copy the data - #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - memcpy(uuid, bytes, getRawBytesSize()); - #else - memcpy(&uuid, bytes, getRawBytesSize()); - #endif + // Copy the data + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + memcpy(uuid, bytes, getRawBytesSize()); + #else + memcpy(&uuid, bytes, getRawBytesSize()); + #endif - return *this; + return *this; } //////////////////////////////////////////////////////////////////////////////// int Guid::getRawBytesSize(void) const { - #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - return sizeof(uuid_t); - #else - return sizeof(::GUID); - #endif + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + return sizeof(uuid_t); + #else + return sizeof(::GUID); + #endif } //////////////////////////////////////////////////////////////////////////////// Guid::operator const unsigned char*() const { - #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - return &uuid[0]; - #else - return reinterpret_cast(&uuid); - #endif + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + return &uuid[0]; + #else + return reinterpret_cast(&uuid); + #endif } //////////////////////////////////////////////////////////////////////////////// -Guid& Guid::operator=(const Guid& source) +Guid& Guid::operator=( const Guid& source ) throw ( IllegalArgumentException ) { - #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - // Use the uuid method to copy - uuid_copy(uuid, *(const_cast(&source.uuid))); - #else - // Use mem copy - memcpy(&uuid, &source.uuid, getRawBytesSize()); - #endif + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + // Use the uuid method to copy + uuid_copy(uuid, *(const_cast(&source.uuid))); + #else + // Use mem copy + memcpy(&uuid, &source.uuid, getRawBytesSize()); + #endif - return *this; + return *this; } //////////////////////////////////////////////////////////////////////////////// -Guid& Guid::operator=(const std::string& source) - throw ( IllegalArgumentException ) +Guid& Guid::operator=( const std::string& source ) + throw ( IllegalArgumentException ) { - #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - // Parse a uuid from the passed in string - uuid_parse( const_cast(source.c_str()), uuid ); - #else - if ( source.empty() ) - { - ::UuidCreateNil( &uuid ); - } - else - { - RPC_STATUS hResult = - ::UuidFromString( (unsigned char*)source.c_str(), &uuid ); + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + // Parse a uuid from the passed in string + uuid_parse( const_cast(source.c_str()), uuid ); + #else + if ( source.empty() ) + { + ::UuidCreateNil( &uuid ); + } + else + { + RPC_STATUS hResult = + ::UuidFromString( (unsigned char*)source.c_str(), &uuid ); - if ( hResult == RPC_S_INVALID_STRING_UUID ) - { - throw IllegalArgumentException( - __FILE__, __LINE__, - "GUID::fromBytes - Invalid GUID String"); - } - } - #endif + if ( hResult == RPC_S_INVALID_STRING_UUID ) + { + throw IllegalArgumentException( + __FILE__, __LINE__, + "GUID::fromBytes - Invalid GUID String"); + } + } + #endif - return *this; + return *this; } //////////////////////////////////////////////////////////////////////////////// -bool Guid::operator==(const Guid& source) const +bool Guid::operator==( const Guid& source ) const { - #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - // uuid_compare returns 0 for equal - return uuid_compare( - *(const_cast(&uuid)), - *(const_cast(&source.uuid))) == 0 ? true : false; - #else - RPC_STATUS status; + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + // uuid_compare returns 0 for equal + return uuid_compare( + *(const_cast(&uuid)), + *(const_cast(&source.uuid))) == 0 ? true : false; + #else + RPC_STATUS status; - BOOL result = ::UuidEqual( - const_cast( &uuid ), - const_cast( &source.uuid ), - &status ); + BOOL result = ::UuidEqual( + const_cast( &uuid ), + const_cast( &source.uuid ), + &status ); - return ( result == TRUE ) ? true : false; - #endif + return ( result == TRUE ) ? true : false; + #endif } //////////////////////////////////////////////////////////////////////////////// -bool Guid::operator==(const std::string& source) const +bool Guid::operator==( const std::string& source ) const { - return *this == Guid(source); + return *this == Guid(source); } //////////////////////////////////////////////////////////////////////////////// -bool Guid::operator!=(const Guid& source) const +bool Guid::operator!=( const Guid& source ) const { - return !(*this == source); + return !(*this == source); } //////////////////////////////////////////////////////////////////////////////// -bool Guid::operator!=(const std::string& source) const +bool Guid::operator!=( const std::string& source ) const { - return !(*this == source); + return !( *this == source ); } //////////////////////////////////////////////////////////////////////////////// -bool Guid::operator<(const Guid& source) const +bool Guid::operator<( const Guid& source ) const { - #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - // uuid_compare returns 0 for equal - return uuid_compare( - *(const_cast(&uuid)), - *(const_cast(&source.uuid))) < 0 ? true : false; - #else - RPC_STATUS status; + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + // uuid_compare returns 0 for equal + return uuid_compare( + *(const_cast(&uuid)), + *(const_cast(&source.uuid))) < 0 ? true : false; + #else + RPC_STATUS status; - int result = ::UuidCompare( - const_cast( &uuid ), - const_cast( &source.uuid ), - &status ); + int result = ::UuidCompare( + const_cast( &uuid ), + const_cast( &source.uuid ), + &status ); - return ( result < 0 ) ? true : false; - #endif + return ( result < 0 ) ? true : false; + #endif } //////////////////////////////////////////////////////////////////////////////// -bool Guid::operator<(const std::string& source) const +bool Guid::operator<( const std::string& source ) const { - return *this < Guid(source); + return *this < Guid(source); } //////////////////////////////////////////////////////////////////////////////// -bool Guid::operator<=(const Guid& source) const +bool Guid::operator<=( const Guid& source ) const { - #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - // uuid_compare returns 0 for equal - return uuid_compare( - *(const_cast(&uuid)), - *(const_cast(&source.uuid))) <= 0 ? true : false; - #else - RPC_STATUS status; + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + // uuid_compare returns 0 for equal + return uuid_compare( + *(const_cast(&uuid)), + *(const_cast(&source.uuid))) <= 0 ? true : false; + #else + RPC_STATUS status; - int result = ::UuidCompare( - const_cast( &uuid ), - const_cast( &source.uuid ), - &status ); + int result = ::UuidCompare( + const_cast( &uuid ), + const_cast( &source.uuid ), + &status ); - return ( result <= 0 ) ? true : false; - #endif + return ( result <= 0 ) ? true : false; + #endif } //////////////////////////////////////////////////////////////////////////////// -bool Guid::operator<=(const std::string& source) const +bool Guid::operator<=( const std::string& source ) const { - return *this <= Guid(source); + return *this <= Guid(source); } //////////////////////////////////////////////////////////////////////////////// -bool Guid::operator>(const Guid& source) const +bool Guid::operator>( const Guid& source ) const { - #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - // uuid_compare returns 0 for equal - return uuid_compare( - *(const_cast(&uuid)), - *(const_cast(&source.uuid))) > 0 ? true : false; - #else - RPC_STATUS status; + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + // uuid_compare returns 0 for equal + return uuid_compare( + *(const_cast(&uuid)), + *(const_cast(&source.uuid))) > 0 ? true : false; + #else + RPC_STATUS status; - int result = ::UuidCompare( - const_cast( &uuid ), - const_cast( &source.uuid ), - &status ); + int result = ::UuidCompare( + const_cast( &uuid ), + const_cast( &source.uuid ), + &status ); - return ( result > 0 ) ? true : false; - #endif + return ( result > 0 ) ? true : false; + #endif } //////////////////////////////////////////////////////////////////////////////// -bool Guid::operator>(const std::string& source) const +bool Guid::operator>( const std::string& source ) const { - return *this > Guid(source); + return *this > Guid(source); } //////////////////////////////////////////////////////////////////////////////// -bool Guid::operator>=(const Guid& source) const +bool Guid::operator>=( const Guid& source ) const { - #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) - // uuid_compare returns 0 for equal - return uuid_compare( - *(const_cast(&uuid)), - *(const_cast(&source.uuid))) >= 0 ? true : false; - #else - RPC_STATUS status; + #if (defined( unix ) || defined(__APPLE__)) && !defined( __CYGWIN__ ) + // uuid_compare returns 0 for equal + return uuid_compare( + *(const_cast(&uuid)), + *(const_cast(&source.uuid))) >= 0 ? true : false; + #else + RPC_STATUS status; - int result = ::UuidCompare( - const_cast(&uuid), - const_cast(&source.uuid), - &status); + int result = ::UuidCompare( + const_cast(&uuid), + const_cast(&source.uuid), + &status); - return (result >= 0) ? true : false; - #endif + return (result >= 0) ? true : false; + #endif } //////////////////////////////////////////////////////////////////////////////// -bool Guid::operator>=(const std::string& source) const +bool Guid::operator>=( const std::string& source ) const { - return *this >= Guid(source); + return *this >= Guid(source); } //////////////////////////////////////////////////////////////////////////////// std::string Guid::createGUIDString(void) { - return Guid().createGUID().toString(); + return Guid().createGUID().toString(); } //////////////////////////////////////////////////////////////////////////////// const unsigned char* createGUIDBytes(void) { - return Guid().createGUID().toBytes(); + return Guid().createGUID().toBytes(); } diff --git a/activemq-cpp/src/main/activemq/util/Guid.h b/activemq-cpp/src/main/activemq/util/Guid.h index 95caeb1e6e..fb1319a466 100644 --- a/activemq-cpp/src/main/activemq/util/Guid.h +++ b/activemq-cpp/src/main/activemq/util/Guid.h @@ -18,12 +18,12 @@ #define ACTIVEMQ_UTIL_GUID_H #if defined( unix ) || defined(__APPLE__) && !defined( __CYGWIN__ ) - #include + #include #elif defined(_WIN32) || defined( __CYGWIN__ ) - #include - #include + #include + #include #else // defined MACOSX - #include "uuid.h" + #include "uuid.h" #endif #include @@ -34,165 +34,150 @@ namespace activemq{ namespace util{ - class Guid - { - public: + class Guid + { + public: - /** - * Constructor - */ - Guid(void); + Guid(void); + Guid(const Guid& source); + Guid(const std::string& source) + throw ( exceptions::IllegalArgumentException ); + virtual ~Guid(void); - /** - * Copy Constructor - */ - Guid(const Guid& source); + /** + * Determines if this GUID is null, if so it can be initialized with a + * call to createGUID. + * @return true for Null GUID, false otherwise. + */ + bool isNull(void) const; + + /** + * Clears the GUID's current value and sets it to a NULL GUID value + * will now pass isNull. + */ + void setNull(void); - /** - * Constructor - Create a GUID from a String - */ - Guid(const std::string& source) - throw ( exceptions::IllegalArgumentException ); - - /** - * Destructor - */ - virtual ~Guid(void); + /** + * Generate a new GUID which will overwrite any current GUID value + * @return Reference to this object that now has a new GUID + */ + Guid& createGUID(void) throw( exceptions::RuntimeException ); - /** - * Determines if this GUID is null, if so it can be initialized with a - * call to createGUID. - * @return true for Null GUID, false otherwise. - */ - bool isNull(void) const; + /** + * Converts the GUID to a string and returns that string + * @return a string with this GUID's stringified value + */ + std::string toString(void) const throw( exceptions::RuntimeException ); - /** - * Clears the GUID's current value and sets it to a NULL GUID value - * will now pass isNull. - */ - void setNull(void); + /** + * Converts the GUID to a byte array and return a pointer to the + * new array, called takes ownership and must delete this array + * when done. + * @return a byte array with the GUID byte value, size = 16 + */ + const unsigned char* toBytes(void) const; + + /** + * Initializes this GUID with the GUID specified in the bytes parameter + * @return reference to this object. + */ + Guid& fromBytes( const unsigned char* bytes ) + throw ( exceptions::IllegalArgumentException ); + + /** + * Returns the Size in Bytes of the Raw bytes representation of the + * GUID. + * @return size of the Raw bytes representation + */ + int getRawBytesSize(void) const; - /** - * Generate a new GUID which will overwrite any current GUID value - * @return Reference to this object that now has a new GUID - */ - Guid& createGUID(void) throw( exceptions::RuntimeException ); + /** + * string type cast operator + * @returns string representation of this GUID + */ + operator std::string() const; + + /** + * byte array cast operator, caller does not own this memeory + * @returns byte array with the GUID byte value representation + */ + operator const unsigned char*() const; + + /** + * Assignment operators + * @return Reference to this GUID object + */ + Guid& operator=( const Guid& source ) + throw ( exceptions::IllegalArgumentException ); + Guid& operator=( const std::string& source ) + throw ( exceptions::IllegalArgumentException ); - /** - * Converts the GUID to a string and returns that string - * @return a string with this GUID's stringified value - */ - std::string toString(void) const throw( exceptions::RuntimeException ); + /** + * Equality Comparison Operators + * @return true for equal. false otherwise + */ + bool operator==( const Guid& source ) const; + bool operator==( const std::string& source ) const; - /** - * Converts the GUID to a byte array and return a pointer to the - * new array, called takes ownership and must delete this array - * when done. - * @return a byte array with the GUID byte value, size = 16 - */ - const unsigned char* toBytes(void) const; + /** + * Inequality Comparison Operators + * @return true for equal. false otherwise + */ + bool operator!=( const Guid& source ) const; + bool operator!=( const std::string& source ) const; - /** - * Initializes this GUID with the GUID specified in the bytes parameter - * @return reference to this object. - */ - Guid& fromBytes(const unsigned char* bytes) - throw ( exceptions::IllegalArgumentException ); + /** + * Less than operators + * @return true for equal. false otherwise + */ + bool operator<(const Guid& source) const; + bool operator<(const std::string& source) const; - /** - * Returns the Size in Bytes of the Raw bytes representation of the - * GUID. - * @return size of the Raw bytes representation - */ - int getRawBytesSize(void) const; + /** + * Less than or equal to operators + * @return true for equal. false otherwise + */ + bool operator<=( const Guid& source ) const; + bool operator<=( const std::string& source ) const; - /** - * string type cast operator - * @returns string representation of this GUID - */ - operator std::string() const; - - /** - * byte array cast operator, caller does not own this memeory - * @returns byte array with the GUID byte value representation - */ - operator const unsigned char*() const; - - /** - * Assignment operators - * @return Reference to this GUID object - */ - Guid& operator=(const Guid& source) - throw ( exceptions::IllegalArgumentException ); - Guid& operator=(const std::string& source) - throw ( exceptions::IllegalArgumentException ); + /** + * Greater than operators + * @return true for equal. false otherwise + */ + bool operator>( const Guid& source ) const; + bool operator>( const std::string& source ) const; - /** - * Equality Comparison Operators - * @return true for equal. false otherwise - */ - bool operator==(const Guid& source) const; - bool operator==(const std::string& source) const; + /** + * Greater than or equal to operators + * @return true for equal. false otherwise + */ + bool operator>=( const Guid& source ) const; + bool operator>=( const std::string& source ) const; - /** - * Inequality Comparison Operators - * @return true for equal. false otherwise - */ - bool operator!=(const Guid& source) const; - bool operator!=(const std::string& source) const; - - /** - * Less than operators - * @return true for equal. false otherwise - */ - bool operator<(const Guid& source) const; - bool operator<(const std::string& source) const; - - /** - * Less than or equal to operators - * @return true for equal. false otherwise - */ - bool operator<=(const Guid& source) const; - bool operator<=(const std::string& source) const; - - /** - * Greater than operators - * @return true for equal. false otherwise - */ - bool operator>(const Guid& source) const; - bool operator>(const std::string& source) const; - - /** - * Greater than or equal to operators - * @return true for equal. false otherwise - */ - bool operator>=(const Guid& source) const; - bool operator>=(const std::string& source) const; - - public: + public: - /** - * Static Guid Creation Method, creates a GUID and returns it as a string - * @return Guid string. - */ - static std::string createGUIDString(void); + /** + * Static Guid Creation Method, creates a GUID and returns it as a string + * @return Guid string. + */ + static std::string createGUIDString(void); - /** - * Static Guid Create Method, create a GUID and returns the byte representation - * of the new GUID. - * @return Guid bytes array, size is 16 - */ - static const unsigned char* createGUIDBytes(void); + /** + * Static Guid Create Method, create a GUID and returns the byte representation + * of the new GUID. + * @return Guid bytes array, size is 16 + */ + static const unsigned char* createGUIDBytes(void); - private: - - // the uuid that this object represents. - #if defined( unix ) || defined(__APPLE__) - uuid_t uuid; - #else - ::GUID uuid; - #endif - + private: + + // the uuid that this object represents. + #if defined( unix ) || defined(__APPLE__) + uuid_t uuid; + #else + ::GUID uuid; + #endif + }; }} diff --git a/activemq-cpp/src/main/activemq/util/Integer.h b/activemq-cpp/src/main/activemq/util/Integer.h index f3b4850fc5..ee484c65ca 100644 --- a/activemq-cpp/src/main/activemq/util/Integer.h +++ b/activemq-cpp/src/main/activemq/util/Integer.h @@ -27,15 +27,15 @@ namespace util{ { public: - Integer(void) {} - virtual ~Integer(void) {} + Integer(void) {} + virtual ~Integer(void) {} /** * Parses the String passed and extracts an int. * @param String to parse * @return int value */ - static int parseInt(const std::string& value){ + static int parseInt( const std::string& value ){ int ret = 0; std::istringstream istream(value); istream.clear(); @@ -48,7 +48,7 @@ namespace util{ * @param int to convert * @return string representation */ - static std::string toString(int value){ + static std::string toString( int value ){ std::ostringstream ostream; ostream << value; return ostream.str(); diff --git a/activemq-cpp/src/main/activemq/util/Long.h b/activemq-cpp/src/main/activemq/util/Long.h index a93a58aa70..0ff117dd7b 100644 --- a/activemq-cpp/src/main/activemq/util/Long.h +++ b/activemq-cpp/src/main/activemq/util/Long.h @@ -27,15 +27,15 @@ namespace util{ { public: - Long(void) {} - virtual ~Long(void) {} + Long(void) {} + virtual ~Long(void) {} /** * Parses the String passed and extracts an long. * @param String to parse * @return long value */ - static long parseLong(const std::string& value){ + static long parseLong( const std::string& value ){ long ret = 0; std::istringstream istream(value); istream.clear(); @@ -48,7 +48,7 @@ namespace util{ * @param long to convert * @return string representation */ - static std::string toString(long value){ + static std::string toString( long value ){ std::ostringstream ostream; ostream << value; return ostream.str(); diff --git a/activemq-cpp/src/main/activemq/util/Number.h b/activemq-cpp/src/main/activemq/util/Number.h index 933fb1d548..eb7cec5338 100644 --- a/activemq-cpp/src/main/activemq/util/Number.h +++ b/activemq-cpp/src/main/activemq/util/Number.h @@ -34,7 +34,7 @@ namespace util{ { public: - virtual ~Number(void) {} + virtual ~Number(void) {} }; diff --git a/activemq-cpp/src/main/activemq/util/Properties.h b/activemq-cpp/src/main/activemq/util/Properties.h index 59466380a6..50a6235acb 100644 --- a/activemq-cpp/src/main/activemq/util/Properties.h +++ b/activemq-cpp/src/main/activemq/util/Properties.h @@ -24,73 +24,82 @@ namespace activemq{ namespace util{ - /** - * Interface for a Java-like properties object. This is essentially - * a map of key-value string pairs. - */ - class Properties{ - public: + /** + * Interface for a Java-like properties object. This is essentially + * a map of key-value string pairs. + */ + class Properties{ + public: - virtual ~Properties(){} + virtual ~Properties(){} + + /** + * Returns true if the properties object is empty + * @return true if empty + */ + virtual bool isEmpty() const = 0; + + /** + * Looks up the value for the given property. + * @param name The name of the property to be looked up. + * @return the value of the property with the given name, if it + * exists. If it does not exist, returns NULL. + */ + virtual const char* getProperty( const std::string& name ) const = 0; - /** - * Looks up the value for the given property. - * @param name The name of the property to be looked up. - * @return the value of the property with the given name, if it - * exists. If it does not exist, returns NULL. - */ - virtual const char* getProperty( const std::string& name ) const = 0; + /** + * Looks up the value for the given property. + * @param name the name of the property to be looked up. + * @param defaultValue The value to be returned if the given + * property does not exist. + * @return The value of the property specified by name, if it + * exists, otherwise the defaultValue. + */ + virtual std::string getProperty( + const std::string& name, + const std::string& defaultValue ) const = 0; - /** - * Looks up the value for the given property. - * @param name the name of the property to be looked up. - * @param defaultValue The value to be returned if the given - * property does not exist. - * @return The value of the property specified by name, if it - * exists, otherwise the defaultValue. - */ - virtual std::string getProperty( const std::string& name, - const std::string& defaultValue ) const = 0; + /** + * Sets the value for a given property. If the property already + * exists, overwrites the value. + * @param name The name of the value to be written. + * @param value The value to be written. + */ + virtual void setProperty( + const std::string& name, + const std::string& value ) = 0; - /** - * Sets the value for a given property. If the property already - * exists, overwrites the value. - * @param name The name of the value to be written. - * @param value The value to be written. - */ - virtual void setProperty( const std::string& name, - const std::string& value ) = 0; - - /** - * Check to see if the Property exists in the set - * @return true if property exists, false otherwise. - */ - virtual bool hasProperty( const std::string& name ) const = 0; + /** + * Check to see if the Property exists in the set + * @return true if property exists, false otherwise. + */ + virtual bool hasProperty( const std::string& name ) const = 0; - /** - * Method that serializes the contents of the property map to - * an arryay. - * @return list of pairs where the first is the name and the second - * is the value. - */ - virtual std::vector< std::pair > toArray() const = 0; + /** + * Method that serializes the contents of the property map to + * an arryay. + * @return list of pairs where the first is the name and the second + * is the value. + */ + virtual std::vector< std::pair< std::string, std::string > > toArray() const = 0; - /** - * Copies the contents of the given properties object to this one. - * @param source The source properties object. - */ - virtual void copy( const Properties* source ) = 0; + /** + * Copies the contents of the given properties object to this one. + * @param source The source properties object. + */ + virtual void copy( const Properties* source ) = 0; - /** - * Clones this object. - * @returns a replica of this object. - */ - virtual Properties* clone() const = 0; + /** + * Clones this object. + * @returns a replica of this object. + */ + virtual Properties* clone() const = 0; - /** - * Clears all properties from the map. - */ - virtual void clear() = 0; + /** + * Clears all properties from the map. + */ + virtual void clear() = 0; + }; }} diff --git a/activemq-cpp/src/main/activemq/util/Queue.h b/activemq-cpp/src/main/activemq/util/Queue.h index 551b373d78..fe4edd07d3 100644 --- a/activemq-cpp/src/main/activemq/util/Queue.h +++ b/activemq-cpp/src/main/activemq/util/Queue.h @@ -24,284 +24,277 @@ namespace activemq{ namespace util{ - /** - * The Queue class accepts messages with an psuh(m) command - * where m is the message to be queued. It destructively - * returns the message with pop(). pop() returns messages in - * the order they were enqueued. - * - * Queue is implemented with an instance of the STL queue object. - * The interface is essentially the same as that of the STL queue - * except that the pop method actually reaturns a reference to the - * element popped. This frees the app from having to call the - * front method before calling pop. - * - * Queue sq; // make a queue to hold string messages - * sq.push(s); // enqueues a message m - * string s = sq.pop(); // dequeues a message - * - * = DESIGN CONSIDERATIONS - * - * The Queue class inherits from the Synchronizable interface and - * provides methods for locking and unlocking this queue as well as - * waiting on this queue. In a multi-threaded app this can allow - * for multiple threads to be reading from and writing to the same - * Queue. - * - * Clients should consider that in a multiple threaded app it is - * possible that items could be placed on the queue faster than - * you are taking them off, so protection should be placed in your - * polling loop to ensure that you don't get stuck there. - */ + /** + * The Queue class accepts messages with an psuh(m) command + * where m is the message to be queued. It destructively + * returns the message with pop(). pop() returns messages in + * the order they were enqueued. + * + * Queue is implemented with an instance of the STL queue object. + * The interface is essentially the same as that of the STL queue + * except that the pop method actually reaturns a reference to the + * element popped. This frees the app from having to call the + * front method before calling pop. + * + * Queue sq; // make a queue to hold string messages + * sq.push(s); // enqueues a message m + * string s = sq.pop(); // dequeues a message + * + * = DESIGN CONSIDERATIONS + * + * The Queue class inherits from the Synchronizable interface and + * provides methods for locking and unlocking this queue as well as + * waiting on this queue. In a multi-threaded app this can allow + * for multiple threads to be reading from and writing to the same + * Queue. + * + * Clients should consider that in a multiple threaded app it is + * possible that items could be placed on the queue faster than + * you are taking them off, so protection should be placed in your + * polling loop to ensure that you don't get stuck there. + */ - template class Queue : public concurrent::Synchronizable - { - public: + template class Queue : public concurrent::Synchronizable + { + public: - /** - * Constructor - */ - Queue(void); + Queue(void); + virtual ~Queue(void); - /** - * Destructor - */ - virtual ~Queue(void); + /** + * Returns a Reference to the element at the head of the queue + * @return reference to a queue type object or (safe) + */ + T& front(void); - /** - * Returns a Reference to the element at the head of the queue - * @return reference to a queue type object or (safe) - */ - T& front(void); + /** + * Returns a Reference to the element at the head of the queue + * @return reference to a queue type object or (safe) + */ + const T& front(void) const; - /** - * Returns a Reference to the element at the head of the queue - * @return reference to a queue type object or (safe) - */ - const T& front(void) const; + /** + * Returns a Reference to the element at the tail of the queue + * @return reference to a queue type object or (safe) + */ + T& back(void); - /** - * Returns a Reference to the element at the tail of the queue - * @return reference to a queue type object or (safe) - */ - T& back(void); + /** + * Returns a Reference to the element at the tail of the queue + * @return reference to a queue type object or (safe) + */ + const T& back(void) const; - /** - * Returns a Reference to the element at the tail of the queue - * @return reference to a queue type object or (safe) - */ - const T& back(void) const; + /** + * Places a new Object at the Tail of the queue + * @param Queue Object Type reference. + */ + void push( const T &t ); - /** - * Places a new Object at the Tail of the queue - * @param Queue Object Type reference. - */ - void push(const T &t); + /** + * Removes and returns the element that is at the Head of the queue + * @return reference to a queue type object or (safe) + */ + T pop(void); - /** - * Removes and returns the element that is at the Head of the queue - * @return reference to a queue type object or (safe) - */ - T pop(void); + /** + * Gets the Number of elements currently in the Queue + * @return Queue Size + */ + size_t size(void) const; - /** - * Gets the Number of elements currently in the Queue - * @return Queue Size - */ - size_t size(void) const; - - /** - * Checks if this Queue is currently empty - * @return boolean indicating queue emptiness - */ - bool empty(void) const; + /** + * Checks if this Queue is currently empty + * @return boolean indicating queue emptiness + */ + bool empty(void) const; - /** - * Locks the object. - */ - virtual void lock() throw(exceptions::ActiveMQException){ - mutex.lock(); - } + /** + * Locks the object. + */ + virtual void lock() throw( exceptions::ActiveMQException ){ + mutex.lock(); + } - /** - * Unlocks the object. - */ - virtual void unlock() throw(exceptions::ActiveMQException){ - mutex.unlock(); - } + /** + * Unlocks the object. + */ + virtual void unlock() throw( exceptions::ActiveMQException ){ + mutex.unlock(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. - */ - virtual void wait() throw(exceptions::ActiveMQException){ - mutex.wait(); - } + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. + */ + virtual void wait() throw( exceptions::ActiveMQException ){ + mutex.wait(); + } - /** - * Waits on a signal from this object, which is generated - * by a call to Notify. Must have this object locked before - * calling. This wait will timeout after the specified time - * interval. - * @param time in millisecsonds to wait, or WAIT_INIFINITE - * @throws ActiveMQException - */ - virtual void wait(unsigned long millisecs) - throw(exceptions::ActiveMQException) { + /** + * Waits on a signal from this object, which is generated + * by a call to Notify. Must have this object locked before + * calling. This wait will timeout after the specified time + * interval. + * @param time in millisecsonds to wait, or WAIT_INIFINITE + * @throws ActiveMQException + */ + virtual void wait( unsigned long millisecs ) + throw( exceptions::ActiveMQException ) { - mutex.wait(millisecs); - } + mutex.wait(millisecs); + } - /** - * Signals a waiter on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - */ - virtual void notify() throw(exceptions::ActiveMQException){ - mutex.notify(); - } + /** + * Signals a waiter on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + */ + virtual void notify() throw( exceptions::ActiveMQException ){ + mutex.notify(); + } - /** - * Signals the waiters on this object that it can now wake - * up and continue. Must have this object locked before - * calling. - */ - virtual void notifyAll() throw(exceptions::ActiveMQException){ - mutex.notifyAll(); - } + /** + * Signals the waiters on this object that it can now wake + * up and continue. Must have this object locked before + * calling. + */ + virtual void notifyAll() throw( exceptions::ActiveMQException ){ + mutex.notifyAll(); + } - public: // Statics + public: // Statics - /** - * Fetch a reference to the safe value this object will return - * when there is nothing to fetch from the queue. - * @return Reference to this Queues safe object - */ - static const T& getSafeValue(void) { return safe; } + /** + * Fetch a reference to the safe value this object will return + * when there is nothing to fetch from the queue. + * @return Reference to this Queues safe object + */ + static const T& getSafeValue(void) { return safe; } - private: - - // The real queue - std::queue queue; + private: - // Object used for sync - concurrent::Mutex mutex; + // The real queue + std::queue queue; - // Safe value used when pop, front or back are - // called and the queue is empty. - static T safe; + // Object used for sync + concurrent::Mutex mutex; + + // Safe value used when pop, front or back are + // called and the queue is empty. + static T safe; - }; + }; - //-----{ Static Init }-----------------------------------------------------// - template - T Queue::safe; + //-----{ Static Init }----------------------------------------------------// + template + T Queue::safe; - //-----{ Retrieve current length of Queue }--------------------------------// + //-----{ Retrieve current length of Queue }-------------------------------// - template inline size_t Queue::size() const - { - return queue.size(); - } + template inline size_t Queue::size() const + { + return queue.size(); + } - //-----{ Retrieve whether Queue is empty or not }--------------------------// + //-----{ Retrieve whether Queue is empty or not }-------------------------// - template inline bool Queue::empty(void) const - { - return queue.empty(); - } + template inline bool Queue::empty(void) const + { + return queue.empty(); + } - //-----{ Defulat Constructor }---------------------------------------------// + //-----{ Defulat Constructor }--------------------------------------------// - template - Queue::Queue() - { - } + template + Queue::Queue() + { + } - //-----{ Default Destructor }----------------------------------------------// + //-----{ Default Destructor }---------------------------------------------// - template Queue::~Queue() - { - } + template Queue::~Queue() + { + } - //-----{ Add Elements to Back of Queue }-----------------------------------// + //-----{ Add Elements to Back of Queue }----------------------------------// - template - void Queue::push(const T &t) - { - queue.push(t); - } + template + void Queue::push( const T &t ) + { + queue.push( t ); + } - //-----{ Remove Elements from Front of Queue }-----------------------------// + //-----{ Remove Elements from Front of Queue }----------------------------// - template - T Queue::pop(void) - { - if(queue.empty()) - { - return safe; - } + template + T Queue::pop(void) + { + if(queue.empty()) + { + return safe; + } - // Pop the element into a temp, since we need to remain locked. - // this means getting front and then popping. - T temp = queue.front(); - queue.pop(); + // Pop the element into a temp, since we need to remain locked. + // this means getting front and then popping. + T temp = queue.front(); + queue.pop(); - return temp; - } + return temp; + } - //-----{ Returnreference to element at front of Queue }--------------------// + //-----{ Returnreference to element at front of Queue }-------------------// - template - T& Queue::front(void) - { - if(queue.empty()) - { - return safe; - } + template + T& Queue::front(void) + { + if( queue.empty() ) + { + return safe; + } - return queue.front(); - } + return queue.front(); + } - //-----{ Returnreference to element at front of Queue }--------------------// + //-----{ Returnreference to element at front of Queue }-------------------// - template - const T& Queue::front(void) const - { - if(queue.empty()) - { - return safe; - } + template + const T& Queue::front(void) const + { + if( queue.empty() ) + { + return safe; + } - return queue.front(); - } + return queue.front(); + } - //-----{ Returnreference to element at back of Queue }---------------------// + //-----{ Returnreference to element at back of Queue }--------------------// - template - T& Queue::back(void) - { - if(queue.empty()) - { - return safe; - } + template + T& Queue::back(void) + { + if( queue.empty() ) + { + return safe; + } - return queue.back(); - } + return queue.back(); + } - //-----{ Returnreference to element at back of Queue }---------------------// + //-----{ Returnreference to element at back of Queue }--------------------// - template - const T& Queue::back(void) const - { - if(queue.empty()) - { - return safe; - } + template + const T& Queue::back(void) const + { + if( queue.empty() ) + { + return safe; + } - return queue.back(); - } + return queue.back(); + } }} diff --git a/activemq-cpp/src/main/activemq/util/SimpleProperties.h b/activemq-cpp/src/main/activemq/util/SimpleProperties.h index cf210e9d7e..a6b8769033 100644 --- a/activemq-cpp/src/main/activemq/util/SimpleProperties.h +++ b/activemq-cpp/src/main/activemq/util/SimpleProperties.h @@ -23,67 +23,75 @@ namespace activemq{ namespace util{ - - /** - * Basic implementation of the Properties interface. - */ - class SimpleProperties : public Properties{ - private: - - std::map< std::string, std::string > properties; - - public: - - virtual ~SimpleProperties(){} - - /** - * Looks up the value for the given property. - * @param name The name of the property to be looked up. - * @return the value of the property with the given name, if it - * exists. If it does not exist, returns NULL. - */ - virtual const char* getProperty( const std::string& name ) const{ - - std::map< std::string, std::string >::const_iterator iter = + + /** + * Basic implementation of the Properties interface. + */ + class SimpleProperties : public Properties{ + private: + + std::map< std::string, std::string > properties; + + public: + + virtual ~SimpleProperties(){} + + /** + * Returns true if the properties object is empty + * @return true if empty + */ + virtual bool isEmpty() const { + return properties.empty(); + } + + /** + * Looks up the value for the given property. + * @param name The name of the property to be looked up. + * @return the value of the property with the given name, if it + * exists. If it does not exist, returns NULL. + */ + virtual const char* getProperty( const std::string& name ) const{ + + std::map< std::string, std::string >::const_iterator iter = properties.find( name ); - if( iter == properties.end() ){ - return NULL; - } - - return iter->second.c_str(); - } - - /** - * Looks up the value for the given property. - * @param name the name of the property to be looked up. - * @param defaultValue The value to be returned if the given - * property does not exist. - * @return The value of the property specified by name, if it - * exists, otherwise the defaultValue. - */ - virtual std::string getProperty( const std::string& name, - const std::string& defaultValue ) const { - - std::map< std::string, std::string >::const_iterator iter = + if( iter == properties.end() ){ + return NULL; + } + + return iter->second.c_str(); + } + + /** + * Looks up the value for the given property. + * @param name the name of the property to be looked up. + * @param defaultValue The value to be returned if the given + * property does not exist. + * @return The value of the property specified by name, if it + * exists, otherwise the defaultValue. + */ + virtual std::string getProperty( const std::string& name, + const std::string& defaultValue ) const { + + std::map< std::string, std::string >::const_iterator iter = properties.find( name ); - if( iter == properties.end() ){ - return defaultValue; - } - - return iter->second; - } - - /** - * Sets the value for a given property. If the property already - * exists, overwrites the value. - * @param name The name of the value to be written. - * @param value The value to be written. - */ - virtual void setProperty( const std::string& name, - const std::string& value ){ - properties[name] = value; - } - + if( iter == properties.end() ){ + return defaultValue; + } + + return iter->second; + } + + /** + * Sets the value for a given property. If the property already + * exists, overwrites the value. + * @param name The name of the value to be written. + * @param value The value to be written. + */ + virtual void setProperty( const std::string& name, + const std::string& value ){ + properties[name] = value; + } + /** * Check to see if the Property exists in the set * @return true if property exists, false otherwise. @@ -98,64 +106,64 @@ namespace util{ return false; } - /** - * Method that serializes the contents of the property map to - * an arryay. - * @return list of pairs where the first is the name and the second - * is the value. - */ - virtual std::vector< std::pair > toArray() const{ - - // Create a vector big enough to hold all the elements in the map. - std::vector< std::pair > vec( properties.size() ); - - // Get an iterator at the beginning of the map. - std::map< std::string, std::string >::const_iterator iter = properties.begin(); - - // Copy all of the elements from the map to the vector. - for( int ix=0; iter != properties.end(); ++iter, ++ix ){ - vec[ix] = *iter; - } - - return vec; - } - - /** - * Copies the contents of the given properties object to this one. - * @param source The source properties object. - */ - virtual void copy( const Properties* source ){ - - clear(); - - std::vector< std::pair< std::string, std::string > > vec = - source->toArray(); - for( unsigned int ix=0; ix > toArray() const{ + + // Create a vector big enough to hold all the elements in the map. + std::vector< std::pair > vec( properties.size() ); + + // Get an iterator at the beginning of the map. + std::map< std::string, std::string >::const_iterator iter = properties.begin(); + + // Copy all of the elements from the map to the vector. + for( int ix=0; iter != properties.end(); ++iter, ++ix ){ + vec[ix] = *iter; + } + + return vec; + } + + /** + * Copies the contents of the given properties object to this one. + * @param source The source properties object. + */ + virtual void copy( const Properties* source ){ + + clear(); + + std::vector< std::pair< std::string, std::string > > vec = + source->toArray(); + for( unsigned int ix=0; ixproperties = properties; - - return props; - } - - /** - * Clears all properties from the map. - */ - virtual void clear(){ - properties.clear(); - } - }; - + + return props; + } + + /** + * Clears all properties from the map. + */ + virtual void clear(){ + properties.clear(); + } + }; + }} #endif /*ACTIVEMQ_UTIL_SIMPLEPROPERTIES_H_*/ diff --git a/activemq-cpp/src/main/activemq/util/StringTokenizer.cpp b/activemq-cpp/src/main/activemq/util/StringTokenizer.cpp index 5f5c8f4aee..e0000cebf0 100644 --- a/activemq-cpp/src/main/activemq/util/StringTokenizer.cpp +++ b/activemq-cpp/src/main/activemq/util/StringTokenizer.cpp @@ -22,17 +22,17 @@ using namespace activemq::util; using namespace activemq::exceptions; //////////////////////////////////////////////////////////////////////////////// -StringTokenizer::StringTokenizer(const std::string& str, - const std::string& delim, - bool returnDelims) +StringTokenizer::StringTokenizer( const std::string& str, + const std::string& delim, + bool returnDelims ) { - // store off the data - this->str = str; - this->delim = delim; - this->returnDelims = returnDelims; + // store off the data + this->str = str; + this->delim = delim; + this->returnDelims = returnDelims; - // Start and the beginning - pos = 0; + // Start and the beginning + pos = 0; } //////////////////////////////////////////////////////////////////////////////// @@ -43,31 +43,31 @@ StringTokenizer::~StringTokenizer(void) //////////////////////////////////////////////////////////////////////////////// int StringTokenizer::countTokens(void) const { - int count = 0; - string::size_type localPos = pos; - string::size_type lastPos = pos; + int count = 0; + string::size_type localPos = pos; + string::size_type lastPos = pos; - while(localPos != string::npos) - { - if(returnDelims && str.find_first_of(delim, localPos) == localPos) - { - count += 1; - localPos += 1; + while(localPos != string::npos) + { + if(returnDelims && str.find_first_of(delim, localPos) == localPos) + { + count += 1; + localPos += 1; - continue; - } + continue; + } - // Find first token by spanning the fist non-delimiter, to the - // next delimiter, skipping any delimiters that are at the curret - // location. - lastPos = str.find_first_not_of(delim, localPos); - localPos = str.find_first_of(delim, lastPos); + // Find first token by spanning the fist non-delimiter, to the + // next delimiter, skipping any delimiters that are at the curret + // location. + lastPos = str.find_first_not_of(delim, localPos); + localPos = str.find_first_of(delim, lastPos); - if(lastPos != string::npos) - { - count++; - } - } + if(lastPos != string::npos) + { + count++; + } + } return count; } @@ -75,60 +75,60 @@ int StringTokenizer::countTokens(void) const //////////////////////////////////////////////////////////////////////////////// bool StringTokenizer::hasMoreTokens(void) const { - string::size_type nextpos = - returnDelims ? str.find_first_of(delim, pos) : - str.find_first_not_of(delim, pos); + string::size_type nextpos = + returnDelims ? str.find_first_of(delim, pos) : + str.find_first_not_of(delim, pos); - return (nextpos != string::npos); + return (nextpos != string::npos); } //////////////////////////////////////////////////////////////////////////////// std::string StringTokenizer::nextToken(void) throw ( exceptions::NoSuchElementException ) { - if(pos == string::npos) - { - throw NoSuchElementException( - __FILE__, __LINE__, - "StringTokenizer::nextToken - No more Tokens available"); - } + if(pos == string::npos) + { + throw NoSuchElementException( + __FILE__, __LINE__, + "StringTokenizer::nextToken - No more Tokens available"); + } - if(returnDelims) - { - // if char at current pos is a delim return it and advance pos - if(str.find_first_of(delim, pos) == pos) - { - return str.substr(pos++, 1); - } - } + if(returnDelims) + { + // if char at current pos is a delim return it and advance pos + if(str.find_first_of(delim, pos) == pos) + { + return str.substr(pos++, 1); + } + } - // Skip delimiters at beginning. - string::size_type lastPos = str.find_first_not_of(delim, pos); + // Skip delimiters at beginning. + string::size_type lastPos = str.find_first_not_of(delim, pos); - // Find the next delimiter in the string, the charactors in between - // will be the token to return. If this returns string::npos then - // there are no more delimiters in the string. - pos = str.find_first_of(delim, lastPos); + // Find the next delimiter in the string, the charactors in between + // will be the token to return. If this returns string::npos then + // there are no more delimiters in the string. + pos = str.find_first_of(delim, lastPos); - if(string::npos != lastPos) - { - // Found a token, count it, if the pos of the next delim is npos - // then we set length to copy to npos so that all the remianing - // portion of the string is copied, otherwise we set it to the - return str.substr(lastPos, - pos == string::npos ? pos : pos-lastPos); - } - else - { - throw NoSuchElementException( - __FILE__, __LINE__, - "StringTokenizer::nextToken - No more Tokens available"); - } + if(string::npos != lastPos) + { + // Found a token, count it, if the pos of the next delim is npos + // then we set length to copy to npos so that all the remianing + // portion of the string is copied, otherwise we set it to the + return str.substr( lastPos, + pos == string::npos ? pos : pos-lastPos ); + } + else + { + throw NoSuchElementException( + __FILE__, __LINE__, + "StringTokenizer::nextToken - No more Tokens available"); + } } //////////////////////////////////////////////////////////////////////////////// -std::string StringTokenizer::nextToken(const std::string& delim) - throw ( exceptions::NoSuchElementException ) +std::string StringTokenizer::nextToken( const std::string& delim ) + throw ( exceptions::NoSuchElementException ) { this->delim = delim; @@ -136,13 +136,13 @@ std::string StringTokenizer::nextToken(const std::string& delim) } //////////////////////////////////////////////////////////////////////////////// -unsigned int StringTokenizer::toArray(std::vector& array) +unsigned int StringTokenizer::toArray( std::vector& array ) { int count = 0; while(hasMoreTokens()) { - array.push_back(nextToken()); + array.push_back( nextToken() ); count++; } @@ -150,9 +150,9 @@ unsigned int StringTokenizer::toArray(std::vector& array) } //////////////////////////////////////////////////////////////////////////////// -void StringTokenizer::reset(const std::string& str, - const std::string& delim, - bool returnDelims) +void StringTokenizer::reset( const std::string& str, + const std::string& delim, + bool returnDelims ) { if(str != "") { diff --git a/activemq-cpp/src/main/activemq/util/StringTokenizer.h b/activemq-cpp/src/main/activemq/util/StringTokenizer.h index 5ddf2ea175..b3de11f43c 100644 --- a/activemq-cpp/src/main/activemq/util/StringTokenizer.h +++ b/activemq-cpp/src/main/activemq/util/StringTokenizer.h @@ -23,116 +23,113 @@ namespace activemq{ namespace util{ - class StringTokenizer - { - private: + class StringTokenizer + { + private: - // String to tokenize - std::string str; + // String to tokenize + std::string str; - // The delimiter string - std::string delim; + // The delimiter string + std::string delim; - // The current pos in the string - std::string::size_type pos; + // The current pos in the string + std::string::size_type pos; - // Are we returning delimiters - bool returnDelims; + // Are we returning delimiters + bool returnDelims; - public: + public: - /** - * Constructs a string tokenizer for the specified string. All - * characters in the delim argument are the delimiters for separating - * tokens. - * - * If the returnDelims flag is true, then the delimiter characters are - * also returned as tokens. Each delimiter is returned as a string of - * length one. If the flag is false, the delimiter characters are - * skipped and only serve as separators between tokens. - * - * Note that if delim is "", this constructor does not throw an - * exception. However, trying to invoke other methods on the resulting - * StringTokenizer may result in an Exception. - * @param string to tokenize - * @param String containing the delimiters - * @param boolean indicating if the delimiters are returned as tokens - */ - StringTokenizer(const std::string& str, - const std::string& delim = " \t\n\r\f", - bool returnDelims = false); - - /** - * Destructor - */ - virtual ~StringTokenizer(void); - - /** - * Calculates the number of times that this tokenizer's nextToken - * method can be called before it generates an exception. The current - * position is not advanced. - * @return Count of remaining tokens - */ - virtual int countTokens(void) const; - - /** - * Tests if there are more tokens available from this tokenizer's - * string. - * @return true if there are more tokens remaining - */ - virtual bool hasMoreTokens(void) const; - - /** - * Returns the next token from this string tokenizer. - * @return string value of next token - * @thorws NoSuchElementException - */ - virtual std::string nextToken(void) - throw ( exceptions::NoSuchElementException ); - - /** - * Returns the next token in this string tokenizer's string. First, - * the set of characters considered to be delimiters by this - * StringTokenizer object is changed to be the characters in the - * string delim. Then the next token in the string after the current - * position is returned. The current position is advanced beyond the - * recognized token. The new delimiter set remains the default after - * this call. - * @param string containing the new set of delimiters - * @return next string in the token list - * @throw NoSuchElementException - */ - virtual std::string nextToken(const std::string& delim) - throw ( exceptions::NoSuchElementException ); - - /** - * Grab all remaining tokens in the String and return them - * in the vector that is passed in by reference. - * @param vector to place token strings in - * @return number of string placed into the vector - */ - virtual unsigned int toArray(std::vector& array); - - /** - * Resets the Tokenizer's position in the String to the Beginning - * calls to countToken and nextToken now start back at the beginning. - * This allows this object to be reused, the caller need not create - * a new instance every time a String needs tokenizing. - * If set the string param will reset the string that this Tokenizer - * is working on. If set to "" no change is made. - * If set the delim param will reset the string that this Tokenizer - * is using to tokenizer the string. If set to "", no change is made - * If set the return Delims will set if this Tokenizer will return - * delimiters as tokens. Defaults to false. - * @param New String to tokenize or "", defaults to "" - * @param New Delimiter String to use or "", defaults to "" - * @param Should the Tokenizer return delimiters as Tokens, default false - */ - virtual void reset(const std::string& str = "", - const std::string& delim = "", + /** + * Constructs a string tokenizer for the specified string. All + * characters in the delim argument are the delimiters for separating + * tokens. + * + * If the returnDelims flag is true, then the delimiter characters are + * also returned as tokens. Each delimiter is returned as a string of + * length one. If the flag is false, the delimiter characters are + * skipped and only serve as separators between tokens. + * + * Note that if delim is "", this constructor does not throw an + * exception. However, trying to invoke other methods on the resulting + * StringTokenizer may result in an Exception. + * @param string to tokenize + * @param String containing the delimiters + * @param boolean indicating if the delimiters are returned as tokens + */ + StringTokenizer( const std::string& str, + const std::string& delim = " \t\n\r\f", bool returnDelims = false); + + virtual ~StringTokenizer(void); + + /** + * Calculates the number of times that this tokenizer's nextToken + * method can be called before it generates an exception. The current + * position is not advanced. + * @return Count of remaining tokens + */ + virtual int countTokens(void) const; + + /** + * Tests if there are more tokens available from this tokenizer's + * string. + * @return true if there are more tokens remaining + */ + virtual bool hasMoreTokens(void) const; + + /** + * Returns the next token from this string tokenizer. + * @return string value of next token + * @thorws NoSuchElementException + */ + virtual std::string nextToken(void) + throw ( exceptions::NoSuchElementException ); + + /** + * Returns the next token in this string tokenizer's string. First, + * the set of characters considered to be delimiters by this + * StringTokenizer object is changed to be the characters in the + * string delim. Then the next token in the string after the current + * position is returned. The current position is advanced beyond the + * recognized token. The new delimiter set remains the default after + * this call. + * @param string containing the new set of delimiters + * @return next string in the token list + * @throw NoSuchElementException + */ + virtual std::string nextToken(const std::string& delim) + throw ( exceptions::NoSuchElementException ); + + /** + * Grab all remaining tokens in the String and return them + * in the vector that is passed in by reference. + * @param vector to place token strings in + * @return number of string placed into the vector + */ + virtual unsigned int toArray( std::vector< std::string >& array ); + + /** + * Resets the Tokenizer's position in the String to the Beginning + * calls to countToken and nextToken now start back at the beginning. + * This allows this object to be reused, the caller need not create + * a new instance every time a String needs tokenizing. + * If set the string param will reset the string that this Tokenizer + * is working on. If set to "" no change is made. + * If set the delim param will reset the string that this Tokenizer + * is using to tokenizer the string. If set to "", no change is made + * If set the return Delims will set if this Tokenizer will return + * delimiters as tokens. Defaults to false. + * @param New String to tokenize or "", defaults to "" + * @param New Delimiter String to use or "", defaults to "" + * @param Should the Tokenizer return delimiters as Tokens, default false + */ + virtual void reset( const std::string& str = "", + const std::string& delim = "", + bool returnDelims = false); - }; + }; }} diff --git a/activemq-cpp/src/main/cms/BytesMessage.h b/activemq-cpp/src/main/cms/BytesMessage.h index c2b940c258..6935f89244 100644 --- a/activemq-cpp/src/main/cms/BytesMessage.h +++ b/activemq-cpp/src/main/cms/BytesMessage.h @@ -26,9 +26,6 @@ namespace cms{ public: - /** - * Destructor - */ virtual ~BytesMessage(){} /** diff --git a/activemq-cpp/src/main/cms/CMSException.h b/activemq-cpp/src/main/cms/CMSException.h index 351bbe899e..51d897986d 100644 --- a/activemq-cpp/src/main/cms/CMSException.h +++ b/activemq-cpp/src/main/cms/CMSException.h @@ -24,28 +24,27 @@ #include namespace cms{ - - /** - * This class represents an error that has occurred in - * cms. - */ - class CMSException{ - - public: - - /** - * Destruction - */ - virtual ~CMSException(){} - - /** + + /** + * This class represents an error that has occurred in + * cms. + */ + class CMSException{ + + public: + + virtual ~CMSException(){} + + /** * Gets the cause of the error. - */ - virtual const char* getMessage() const = 0; + * @return string errors message + */ + virtual const char* getMessage() const = 0; /** * Provides the stack trace for every point where * this exception was caught, marked, and rethrown. + * @return vector containing stack trace strings */ virtual std::vector< std::pair< std::string, int> > getStackTrace() const = 0; @@ -59,7 +58,8 @@ namespace cms{ * @param stream the target output stream. */ virtual void printStackTrace( std::ostream& stream ) const = 0; - }; + + }; } diff --git a/activemq-cpp/src/main/cms/Closeable.h b/activemq-cpp/src/main/cms/Closeable.h index 10f7b259af..fe79896b85 100644 --- a/activemq-cpp/src/main/cms/Closeable.h +++ b/activemq-cpp/src/main/cms/Closeable.h @@ -21,21 +21,24 @@ #include namespace cms{ - - /** - * Interface for a class that implements the close method. - */ - class Closeable{ - - public: - - virtual ~Closeable(void){} - - /** - * Closes this object and deallocates the appropriate resources. - */ - virtual void close() throw( CMSException ) = 0; - }; + + /** + * Interface for a class that implements the close method. + */ + class Closeable{ + + public: + + virtual ~Closeable(void){} + + /** + * Closes this object and deallocates the appropriate resources. + * The object is generally no longer usable after calling close. + * @throws CMSException + */ + virtual void close() throw( CMSException ) = 0; + + }; } #endif /*CMS_CLOSEABLE_H*/ diff --git a/activemq-cpp/src/main/cms/Connection.h b/activemq-cpp/src/main/cms/Connection.h index 81d5070e88..45857a5d03 100644 --- a/activemq-cpp/src/main/cms/Connection.h +++ b/activemq-cpp/src/main/cms/Connection.h @@ -34,41 +34,41 @@ namespace cms { public: - /** - * Destructor - */ virtual ~Connection(void) {} /** * Creates a new Session to work for this Connection + * @throws CMSException */ virtual Session* createSession(void) throw ( CMSException ) = 0; - + /** * Creates a new Session to work for this Connection using the * specified acknowledgment mode * @param the Acknowledgement Mode to use. + * @throws CMSException */ - virtual Session* createSession(Session::AcknowledgeMode ackMode) + virtual Session* createSession( Session::AcknowledgeMode ackMode ) throw ( CMSException ) = 0; - + /** * Get the Client Id for this session + * @return Client Id String */ virtual std::string getClientId(void) const = 0; - + /** * Gets the registered Exception Listener for this connection * @return pointer to an exception listnener or NULL */ virtual ExceptionListener* getExceptionListener(void) const = 0; - + /** * Sets the registed Exception Listener for this connection * @param pointer to and ExceptionListener */ - virtual void setExceptionListener(ExceptionListener* listener) = 0; - + virtual void setExceptionListener( ExceptionListener* listener ) = 0; + }; } diff --git a/activemq-cpp/src/main/cms/ConnectionFactory.h b/activemq-cpp/src/main/cms/ConnectionFactory.h index aeaeea0e4a..fe3400de94 100644 --- a/activemq-cpp/src/main/cms/ConnectionFactory.h +++ b/activemq-cpp/src/main/cms/ConnectionFactory.h @@ -25,36 +25,38 @@ namespace cms { - class ConnectionFactory - { - public: + /** + * Defines the interface for a factory that creates connection objects + */ + class ConnectionFactory + { + public: - /** - * Destructor - */ - virtual ~ConnectionFactory(void) {} + virtual ~ConnectionFactory(void) {} - /** - * Creates a connection with the default user identity. The - * connection is created in stopped mode. No messages will be - * delivered until the Connection.start method is explicitly - * called. - * @throws CMSException - */ - virtual Connection* createConnection(void) throw ( CMSException ) = 0; + /** + * Creates a connection with the default user identity. The + * connection is created in stopped mode. No messages will be + * delivered until the Connection.start method is explicitly + * called. + * @return Pointer to a connection object, caller owns the pointer + * @throws CMSException + */ + virtual Connection* createConnection(void) throw ( CMSException ) = 0; - /** - * Creates a connection with the specified user identity. The - * connection is created in stopped mode. No messages will be - * delivered until the Connection.start method is explicitly called. - * @throw CMSException. - */ - virtual Connection* createConnection(const std::string& username, - const std::string& password, - const std::string& clientId) - throw ( CMSException ) = 0; + /** + * Creates a connection with the specified user identity. The + * connection is created in stopped mode. No messages will be + * delivered until the Connection.start method is explicitly called. + * @return Pointer to a connection object, caller owns the pointer + * @throw CMSException. + */ + virtual Connection* createConnection( const std::string& username, + const std::string& password, + const std::string& clientId) + throw ( CMSException ) = 0; - }; + }; } diff --git a/activemq-cpp/src/main/cms/DeliveryMode.h b/activemq-cpp/src/main/cms/DeliveryMode.h new file mode 100644 index 0000000000..6ef87c1074 --- /dev/null +++ b/activemq-cpp/src/main/cms/DeliveryMode.h @@ -0,0 +1,44 @@ +/* + * 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. + */ + +#ifndef _CMS_DELIVERYMODE_H_ +#define _CMS_DELIVERYMODE_H_ + +namespace cms +{ + + /** + * This is an Abstract class whose purpose is to provide a container + * for the delivery mode enumeration for CMS messages. + */ + class DeliveryMode + { + public: + + virtual ~DeliveryMode() {} + + /** + * Enumeration values for Message Delivery Mode + */ + static const int PERSISTANT = 0; + static const int NON_PERSISTANT = 1; + + }; + +} + +#endif /*DELIVERYMODE_H_*/ diff --git a/activemq-cpp/src/main/cms/Destination.h b/activemq-cpp/src/main/cms/Destination.h index 035f005cda..7008d43c1f 100644 --- a/activemq-cpp/src/main/cms/Destination.h +++ b/activemq-cpp/src/main/cms/Destination.h @@ -18,6 +18,8 @@ #ifndef _CMS_DESTINATION_H_ #define _CMS_DESTINATION_H_ +#include + #include namespace cms{ @@ -76,6 +78,14 @@ namespace cms{ */ virtual void copy( const cms::Destination& source ) = 0; + /** + * Retrieve any properties that might be part of the destination + * that was specified. This is a deviation from the JMS spec + * but necessary due to C++ restrictions. + * @return const reference to a properties object. + */ + virtual const activemq::util::Properties& getProperties(void) const = 0; + }; } diff --git a/activemq-cpp/src/main/cms/ExceptionListener.h b/activemq-cpp/src/main/cms/ExceptionListener.h index 11dadfb9f3..cfed1e05c8 100644 --- a/activemq-cpp/src/main/cms/ExceptionListener.h +++ b/activemq-cpp/src/main/cms/ExceptionListener.h @@ -22,22 +22,19 @@ namespace cms{ - class ExceptionListener - { - public: + class ExceptionListener + { + public: - /** - * Destructor - */ - virtual ~ExceptionListener(void) {} + virtual ~ExceptionListener(void) {} - /** - * Called when an exception occurs. - * @param Exception Object that occurred. - */ - virtual void onException(const cms::CMSException& ex) = 0; + /** + * Called when an exception occurs. + * @param Exception Object that occurred. + */ + virtual void onException(const cms::CMSException& ex) = 0; - }; + }; } diff --git a/activemq-cpp/src/main/cms/MapMessage.h b/activemq-cpp/src/main/cms/MapMessage.h index 751aa85057..0e32ce385d 100644 --- a/activemq-cpp/src/main/cms/MapMessage.h +++ b/activemq-cpp/src/main/cms/MapMessage.h @@ -22,16 +22,197 @@ namespace cms { - class MapMessage : public Message - { - public: + /** + * A MapMessage object is used to send a set of name-value pairs. The + * names are String objects, and the values are primitive data types in + * the Java programming language. The names must have a value that is + * not null, and not an empty string. The entries can be accessed + * sequentially or randomly by name. The order of the entries is + * undefined. MapMessage inherits from the Message interface and adds + * a message body that contains a Map. + * + * When a client receives a MapMessage, it is in read-only mode. If a + * client attempts to write to the message at this point, a + * CMSException is thrown. + */ + class MapMessage : public Message + { + public: - /** - * Destructor - */ - virtual ~MapMessage(void) {} + virtual ~MapMessage(void) {} + + /** + * Returns an Enumeration of all the names in the MapMessage + * object. + * @return STL Vector of String values, each of which is the + * name of an item in the MapMessage + * @throws CMSException + */ + virtual std::vector< std::string > getMapNames(void) const = 0; - }; + /** + * Indicates whether an item exists in this MapMessage object. + * @param name - String name of the Object in question + * @return boolean value indicating if the name is in the map + */ + virtual bool itemExists( const std::string& name ) const = 0; + + /** + * Returns the Boolean value of the Specified name + * @param name of the value to fetch from the map + * @throws CMSException + */ + virtual bool getBoolean( const std::string& name ) = 0; + + /** + * Sets a boolean value with the specified name into the Map. + * @param name - the name of the boolean + * @param value - the boolean value to set in the Map + * @throws CMSException + */ + virtual void setBoolean( const std::string& name, + bool value ) = 0; + + /** + * Returns the Byte value of the Specified name + * @param name of the value to fetch from the map + * @throws CMSException + */ + virtual unsigned char getByte( const std::string& name ) = 0; + + /** + * Sets a Byte value with the specified name into the Map. + * @param name - the name of the Byte + * @param value - the Byte value to set in the Map + * @throws CMSException + */ + virtual void setByte( const std::string& name, + unsigned char value ) = 0; + + /** + * Returns the Bytes value of the Specified name + * @param name of the value to fetch from the map + * @throws CMSException + */ + virtual unsigned char* getBytes( const std::string& name ) = 0; + + /** + * Sets a Bytes value with the specified name into the Map. + * @param name - the name of the Bytes + * @param value - the Bytes value to set in the Map + * @throws CMSException + */ + virtual void setBytes( const std::string& name, + unsigned char* value ) = 0; + + /** + * Returns the Char value of the Specified name + * @param name of the value to fetch from the map + * @throws CMSException + */ + virtual char getChar( const std::string& name ) = 0; + + /** + * Sets a Char value with the specified name into the Map. + * @param name - the name of the Char + * @param value - the Char value to set in the Map + * @throws CMSException + */ + virtual void setChar( const std::string& name, char value ) = 0; + + /** + * Returns the Double value of the Specified name + * @param name of the value to fetch from the map + * @throws CMSException + */ + virtual double getDouble( const std::string& name ) = 0; + + /** + * Sets a Double value with the specified name into the Map. + * @param name - the name of the Double + * @param value - the Double value to set in the Map + * @throws CMSException + */ + virtual void setDouble( const std::string& name, + double value ) = 0; + + /** + * Returns the Float value of the Specified name + * @param name of the value to fetch from the map + * @throws CMSException + */ + virtual float getFloat( const std::string& name ) = 0; + + /** + * Sets a Float value with the specified name into the Map. + * @param name - the name of the Float + * @param value - the Float value to set in the Map + * @throws CMSException + */ + virtual void setFloat( const std::string& name, float value ) = 0; + + /** + * Returns the Int value of the Specified name + * @param name of the value to fetch from the map + * @throws CMSException + */ + virtual int getInt( const std::string& name ) = 0; + + /** + * Sets a Int value with the specified name into the Map. + * @param name - the name of the Int + * @param value - the Int value to set in the Map + * @throws CMSException + */ + virtual void setInt( const std::string& name, int value ) = 0; + + /** + * Returns the Long value of the Specified name + * @param name of the value to fetch from the map + * @throws CMSException + */ + virtual long getLong( const std::string& name ) = 0; + + /** + * Sets a Long value with the specified name into the Map. + * @param name - the name of the Long + * @param value - the Long value to set in the Map + * @throws CMSException + */ + virtual void setLong( const std::string& name, long value ) = 0; + + /** + * Returns the Short value of the Specified name + * @param name of the value to fetch from the map + * @throws CMSException + */ + virtual short getShort( const std::string& name ) = 0; + + /** + * Sets a Short value with the specified name into the Map. + * @param name - the name of the Short + * @param value - the Short value to set in the Map + * @throws CMSException + */ + virtual void setShort( const std::string& name, short value ) = 0; + + /** + * Returns the String value of the Specified name + * @param name of the value to fetch from the map + * @throws CMSException + */ + virtual std::string getString( const std::string& name ) = 0; + + /** + * Sets a String value with the specified name into the Map. + * @param name - the name of the String + * @param value - the String value to set in the Map + * @throws CMSException + */ + virtual void setString( const std::string& name, + const std::string& value ) = 0; + + }; } diff --git a/activemq-cpp/src/main/cms/Message.h b/activemq-cpp/src/main/cms/Message.h index 49f00f2fc8..08081951a3 100644 --- a/activemq-cpp/src/main/cms/Message.h +++ b/activemq-cpp/src/main/cms/Message.h @@ -22,24 +22,15 @@ #include #include +#include namespace cms{ /** * Root of all messages. */ - class Message{ - public: - - /** - * Enumeration value for Message Delivery Mode - */ - enum DeliveryMode - { - PERSISTANT, - NONPERSISTANT - }; - + class Message + { public: virtual ~Message(void){} @@ -75,31 +66,31 @@ namespace cms{ * Sets the Correlation Id used by this message * @param String representing the correlation id. */ - virtual void setCMSCorrelationId(const std::string& correlationId) = 0; + virtual void setCMSCorrelationId( const std::string& correlationId ) = 0; /** * Sets the DeliveryMode for this message * @return DeliveryMode enumerated value. */ - virtual DeliveryMode getCMSDeliveryMode(void) const = 0; + virtual int getCMSDeliveryMode(void) const = 0; /** * Sets the DeliveryMode for this message * @param DeliveryMode enumerated value. */ - virtual void setCMSDeliveryMode(DeliveryMode mode) = 0; + virtual void setCMSDeliveryMode( int mode ) = 0; /** * Gets the Destination for this Message, returns a * @return Destination object */ - virtual const Destination& getCMSDestination(void) const = 0; + virtual const Destination* getCMSDestination(void) const = 0; /** * Sets the Destination for this message * @param Destination Object */ - virtual void setCMSDestination(const Destination& destination) = 0; + virtual void setCMSDestination( const Destination* destination ) = 0; /** * Gets the Expiration Time for this Message @@ -111,7 +102,7 @@ namespace cms{ * Sets the Expiration Time for this message * @param time value */ - virtual void setCMSExpiration(long expireTime) = 0; + virtual void setCMSExpiration( long expireTime ) = 0; /** * Gets the CMS Message Id for this Message @@ -123,7 +114,7 @@ namespace cms{ * Sets the CMS Message Id for this message * @param time value */ - virtual void setCMSMessageId(const std::string& id) = 0; + virtual void setCMSMessageId( const std::string& id ) = 0; /** * Gets the Priority Value for this Message @@ -135,7 +126,7 @@ namespace cms{ * Sets the Priority Value for this message * @param priority value */ - virtual void setCMSPriority(int priority) = 0; + virtual void setCMSPriority( int priority ) = 0; /** * Gets the Redelivered Flag for this Message @@ -147,7 +138,7 @@ namespace cms{ * Sets the Redelivered Flag for this message * @param redelivered value */ - virtual void setCMSRedelivered(bool redelivered) = 0; + virtual void setCMSRedelivered( bool redelivered ) = 0; /** * Gets the CMS Reply To Address for this Message @@ -159,7 +150,7 @@ namespace cms{ * Sets the CMS Reply To Address for this message * @param Reply To value */ - virtual void setCMSReplyTo(const std::string& id) = 0; + virtual void setCMSReplyTo( const std::string& id ) = 0; /** * Gets the Time Stamp for this Message @@ -171,7 +162,7 @@ namespace cms{ * Sets the Time Stamp for this message * @param time stamp value */ - virtual void setCMSTimeStamp(long timeStamp) = 0; + virtual void setCMSTimeStamp( long timeStamp ) = 0; /** * Gets the CMS Message Type for this Message @@ -183,7 +174,7 @@ namespace cms{ * Sets the CMS Message Type for this message * @param type value */ - virtual void setCMSMessageType(const std::string& type) = 0; + virtual void setCMSMessageType( const std::string& type ) = 0; }; } diff --git a/activemq-cpp/src/main/cms/MessageConsumer.h b/activemq-cpp/src/main/cms/MessageConsumer.h index ba69888d5a..a4902a76b3 100644 --- a/activemq-cpp/src/main/cms/MessageConsumer.h +++ b/activemq-cpp/src/main/cms/MessageConsumer.h @@ -24,59 +24,56 @@ namespace cms { - class MessageConsumer - { - public: + class MessageConsumer + { + public: - /** - * Destructor - */ - virtual ~MessageConsumer(void) {} + virtual ~MessageConsumer(void) {} - /** - * Synchronously Receive a Message - * @return new message - * @throws CMSException - */ - virtual Message* receive(void) throw ( CMSException ) = 0; + /** + * Synchronously Receive a Message + * @return new message + * @throws CMSException + */ + virtual Message* receive(void) throw ( CMSException ) = 0; - /** - * Synchronously Receive a Message, time out after defined interval. - * Returns null if nothing read. - * @return new message - * @throws CMSException - */ - virtual Message* receive(int millisecs) throw ( CMSException ) = 0; + /** + * Synchronously Receive a Message, time out after defined interval. + * Returns null if nothing read. + * @return new message + * @throws CMSException + */ + virtual Message* receive( int millisecs ) throw ( CMSException ) = 0; - /** - * Receive a Message, does not wait if there isn't a new message - * to read, returns NULL if nothing read. - * @return new message - * @throws CMSException - */ - virtual Message* receiveNoWait(void) throw ( CMSException ) = 0; + /** + * Receive a Message, does not wait if there isn't a new message + * to read, returns NULL if nothing read. + * @return new message + * @throws CMSException + */ + virtual Message* receiveNoWait(void) throw ( CMSException ) = 0; - /** - * Sets the MessageListener that this class will send notifs on - * @param MessageListener interface pointer - */ - virtual void setMessageListener(MessageListener* listener) = 0; + /** + * Sets the MessageListener that this class will send notifs on + * @param MessageListener interface pointer + */ + virtual void setMessageListener( MessageListener* listener ) = 0; - /** - * Gets the MessageListener that this class will send notifs on - * @param MessageListener interface pointer - */ - virtual MessageListener* getMessageListener(void) const = 0; + /** + * Gets the MessageListener that this class will send notifs on + * @param MessageListener interface pointer + */ + virtual MessageListener* getMessageListener(void) const = 0; - /** - * Gets this message consumer's message selector expression. - * @return This Consumer's selector expression or "". - * @throws cms::CMSException - */ - virtual std::string getMessageSelector(void) const - throw ( cms::CMSException ) = 0; + /** + * Gets this message consumer's message selector expression. + * @return This Consumer's selector expression or "". + * @throws cms::CMSException + */ + virtual std::string getMessageSelector(void) const + throw ( cms::CMSException ) = 0; - }; + }; } diff --git a/activemq-cpp/src/main/cms/MessageListener.h b/activemq-cpp/src/main/cms/MessageListener.h index 611ab5d674..ef65f33b33 100644 --- a/activemq-cpp/src/main/cms/MessageListener.h +++ b/activemq-cpp/src/main/cms/MessageListener.h @@ -41,9 +41,9 @@ namespace cms{ * It is considered a programming error for this method to throw and * exception. * - * @param Message object reference + * @param Message object const pointer recipient does not own. */ - virtual void onMessage( const Message& message ) = 0; + virtual void onMessage( const Message* message ) = 0; }; diff --git a/activemq-cpp/src/main/cms/MessageProducer.h b/activemq-cpp/src/main/cms/MessageProducer.h index 5fd9ea370a..811c076aa5 100644 --- a/activemq-cpp/src/main/cms/MessageProducer.h +++ b/activemq-cpp/src/main/cms/MessageProducer.h @@ -21,99 +21,102 @@ #include #include #include +#include namespace cms { - /** - * defines the MEssageProducer interface that is used - * by all MessageProducer derivations. This class defines the JMS - * spec'd interface for a MessageProducer. - */ - class MessageProducer - { - public: + /** + * defines the MessageProducer interface that is used + * by all MessageProducer derivations. This class defines the JMS + * spec'd interface for a MessageProducer. + */ + class MessageProducer + { + public: - /** - * Destructor - */ - virtual ~MessageProducer(void) {} + /** + * Destructor + */ + virtual ~MessageProducer(void) {} - /** - * Sends the message to the default producer destination. - * @param a Message Object Pointer - * @throws CMSException - */ - virtual void send(Message& message) throw ( CMSException ) = 0; + /** + * Sends the message to the default producer destination, but does + * not take ownership of the message, caller must still destroy it. + * @param a Message Object Pointer + * @throws CMSException + */ + virtual void send( Message* message ) throw ( CMSException ) = 0; - /** - * Sends the message to the designated destination. - * @param a Message Object Pointer - * @throws CMSException - */ - virtual void send(const Destination& destination, - Message& message) throw ( CMSException ) = 0; + /** + * Sends the message to the designated destination, but does + * not take ownership of the message, caller must still destroy it. + * @param a Message Object Pointer + * @throws CMSException + */ + virtual void send( const Destination* destination, + Message* message ) throw ( CMSException ) = 0; - /** - * Sets the delivery mode for this Producer - * @param The DeliveryMode - */ - virtual void setDeliveryMode(Message::DeliveryMode mode) = 0; + /** + * Sets the delivery mode for this Producer + * @param The DeliveryMode + */ + virtual void setDeliveryMode( int mode ) = 0; - /** - * Gets the delivery mode for this Producer - * @return The DeliveryMode - */ - virtual Message::DeliveryMode getDeliveryMode(void) const = 0; + /** + * Gets the delivery mode for this Producer + * @return The DeliveryMode + */ + virtual int getDeliveryMode(void) const = 0; - /** - * Sets if Message Ids are disbled for this Producer - * @param boolean indicating enable / disable (true / false) - */ - virtual void setDisableMessageId(bool value) = 0; + /** + * Sets if Message Ids are disbled for this Producer + * @param boolean indicating enable / disable (true / false) + */ + virtual void setDisableMessageId( bool value ) = 0; - /** - * Sets if Message Ids are disbled for this Producer - * @param boolean indicating enable / disable (true / false) - */ - virtual bool getDisableMessageId(void) const = 0; + /** + * Sets if Message Ids are disbled for this Producer + * @param boolean indicating enable / disable (true / false) + */ + virtual bool getDisableMessageId(void) const = 0; - /** - * Sets if Message Time Stamps are disbled for this Producer - * @param boolean indicating enable / disable (true / false) - */ - virtual void setDisableMessageTimeStamp(bool value) = 0; + /** + * Sets if Message Time Stamps are disbled for this Producer + * @param boolean indicating enable / disable (true / false) + */ + virtual void setDisableMessageTimeStamp( bool value ) = 0; - /** - * Sets if Message Time Stamps are disbled for this Producer - * @param boolean indicating enable / disable (true / false) - */ - virtual bool getDisableMessageTimeStamp(void) const = 0; + /** + * Sets if Message Time Stamps are disbled for this Producer + * @param boolean indicating enable / disable (true / false) + */ + virtual bool getDisableMessageTimeStamp(void) const = 0; - /** - * Sets the Priority that this Producers sends messages at - * @param int value for Priority level - */ - virtual void setPriority(int priority) = 0; + /** + * Sets the Priority that this Producers sends messages at + * @param int value for Priority level + */ + virtual void setPriority( int priority ) = 0; - /** - * Gets the Priority level that this producer sends messages at - * @return int based priority level - */ - virtual int getPriority(void) const = 0; + /** + * Gets the Priority level that this producer sends messages at + * @return int based priority level + */ + virtual int getPriority(void) const = 0; - /** - * Sets the Time to Live that this Producers sends messages with - * @param int value for time to live - */ - virtual void setTimeToLive(int time) = 0; + /** + * Sets the Time to Live that this Producers sends messages with + * @param int value for time to live + */ + virtual void setTimeToLive( int time ) = 0; - /** - * Gets the Time to Live that this producer sends messages with - * @return int based Time to Live - */ - virtual int getTimeToLive(void) const = 0; + /** + * Gets the Time to Live that this producer sends messages with + * @return int based Time to Live + */ + virtual int getTimeToLive(void) const = 0; - }; + }; } diff --git a/activemq-cpp/src/main/cms/Queue.h b/activemq-cpp/src/main/cms/Queue.h index 07f5774e7b..1ee5426bf0 100644 --- a/activemq-cpp/src/main/cms/Queue.h +++ b/activemq-cpp/src/main/cms/Queue.h @@ -22,24 +22,24 @@ #include namespace cms{ - - /** - * An interface encapsulating a provider-specific queue name. - */ - class Queue : public Destination{ - - public: - - virtual ~Queue(void){} - - /** - * Gets the name of this queue. - * @return The queue name. - */ - virtual std::string getQueueName() const + + /** + * An interface encapsulating a provider-specific queue name. + */ + class Queue : public Destination{ + + public: + + virtual ~Queue(void){} + + /** + * Gets the name of this queue. + * @return The queue name. + */ + virtual std::string getQueueName() const throw( CMSException ) = 0; - }; + }; } diff --git a/activemq-cpp/src/main/cms/Session.h b/activemq-cpp/src/main/cms/Session.h index 5943c9a124..76e9d10a64 100644 --- a/activemq-cpp/src/main/cms/Session.h +++ b/activemq-cpp/src/main/cms/Session.h @@ -40,189 +40,197 @@ namespace cms enum AcknowledgeMode { /** - * With this acknowledgment mode, the session automatically - * acknowledges a client's receipt of a message either when - * the session has successfully returned from a call to receive - * or when the message listener the session has called to - * process the message successfully returns. - */ - AutoAcknowledge, + * With this acknowledgment mode, the session automatically + * acknowledges a client's receipt of a message either when + * the session has successfully returned from a call to receive + * or when the message listener the session has called to + * process the message successfully returns. + */ + AUTO_ACKNOWLEDGE, /** - * With this acknowledgment mode, the session automatically - * acknowledges a client's receipt of a message either when - * the session has successfully returned from a call to receive - * or when the message listener the session has called to - * process the message successfully returns. Acknowlegements - * may be delayed in this mode to increase performance at - * the cost of the message being redelivered this client fails. - */ - DupsOkAcknowledge, + * With this acknowledgment mode, the session automatically + * acknowledges a client's receipt of a message either when + * the session has successfully returned from a call to receive + * or when the message listener the session has called to + * process the message successfully returns. Acknowlegements + * may be delayed in this mode to increase performance at + * the cost of the message being redelivered this client fails. + */ + DUPS_OK_ACKNOWLEDGE, /** - * With this acknowledgment mode, the client acknowledges a - * consumed message by calling the message's acknowledge method. - */ - ClientAcknowledge, + * With this acknowledgment mode, the client acknowledges a + * consumed message by calling the message's acknowledge method. + */ + CLIENT_ACKNOWLEDGE, /** - * Messages will be consumed when the transaction commits. - */ - Transactional + * Messages will be consumed when the transaction commits. + */ + SESSION_TRANSACTED + }; public: - /** - * Destructor - */ virtual ~Session(void) {} /** - * Commits all messages done in this transaction and releases any - * locks currently held. - * @throws CMSException - */ + * Commits all messages done in this transaction and releases any + * locks currently held. + * @throws CMSException + */ virtual void commit(void) throw ( CMSException ) = 0; /** - * Rollsback all messages done in this transaction and releases any - * locks currently held. - * @throws CMSException - */ + * Rollsback all messages done in this transaction and releases any + * locks currently held. + * @throws CMSException + */ virtual void rollback(void) throw ( CMSException ) = 0; /** - * Creates a MessageConsumer for the specified destination. - * @param the Destination that this consumer receiving messages for. - * @throws CMSException - */ + * Creates a MessageConsumer for the specified destination. + * @param the Destination that this consumer receiving messages for. + * @return pointer to a new MessageConsumer that is owned by the + * caller ( caller deletes ) + * @throws CMSException + */ virtual MessageConsumer* createConsumer( - Destination& destination ) + const Destination* destination ) throw ( CMSException ) = 0; /** - * Creates a MessageConsumer for the specified destination, using a - * message selector. - * @param the Destination that this consumer receiving messages for. - * @throws CMSException - */ + * Creates a MessageConsumer for the specified destination, using a + * message selector. + * @param the Destination that this consumer receiving messages for. + * @return pointer to a new MessageConsumer that is owned by the + * caller ( caller deletes ) + * @throws CMSException + */ virtual MessageConsumer* createConsumer( - Destination& destination, + const Destination* destination, const std::string& selector ) throw ( CMSException ) = 0; /** - * Creates a durable subscriber to the specified topic, using a - * message selector - * @param the topic to subscribe to - * @param name used to identify the subscription - * @param only messages matching the selector are received - * @throws CMSException - */ + * Creates a durable subscriber to the specified topic, using a + * message selector + * @param the topic to subscribe to + * @param name used to identify the subscription + * @param only messages matching the selector are received + * @return pointer to a new durable MessageConsumer that is owned by + * the caller ( caller deletes ) + * @throws CMSException + */ virtual MessageConsumer* createDurableConsumer( - Topic& destination, + const Topic* destination, const std::string& name, const std::string& selector, bool noLocal = false ) throw ( CMSException ) = 0; /** - * Creates a MessageProducer to send messages to the specified - * destination. - * @param the Destination to publish on - * @throws CMSException - */ - virtual MessageProducer* createProducer( Destination& destination ) + * Creates a MessageProducer to send messages to the specified + * destination. + * @param the Destination to publish on + * @return New MessageProducer that is owned by the caller. + * @throws CMSException + */ + virtual MessageProducer* createProducer( const Destination* destination ) throw ( CMSException ) = 0; /** - * Creates a queue identity given a Queue name. - * @param the name of the new Queue - * @throws CMSException - */ + * Creates a queue identity given a Queue name. + * @param the name of the new Queue + * @return new Queue pointer that is owned by the caller. + * @throws CMSException + */ virtual Queue* createQueue( const std::string& queueName ) throw ( CMSException ) = 0; /** - * Creates a topic identity given a Queue name. - * @param the name of the new Topic - * @throws CMSException - */ + * Creates a topic identity given a Queue name. + * @param the name of the new Topic + * @return new Topic pointer that is owned by the caller. + * @throws CMSException + */ virtual Topic* createTopic( const std::string& topicName ) throw ( CMSException ) = 0; /** - * Creates a TemporaryQueue object. - * @throws CMSException - */ + * Creates a TemporaryQueue object. + * @return new TemporaryQueue pointer that is owned by the caller. + * @throws CMSException + */ virtual TemporaryQueue* createTemporaryQueue(void) throw ( CMSException ) = 0; /** - * Creates a TemporaryTopic object. - * @throws CMSException - */ + * Creates a TemporaryTopic object. + * @throws CMSException + */ virtual TemporaryTopic* createTemporaryTopic(void) throw ( CMSException ) = 0; /** - * Creates a new Message - * @throws CMSException - */ + * Creates a new Message + * @throws CMSException + */ virtual Message* createMessage(void) throw ( CMSException ) = 0; /** - * Creates a BytesMessage - * @throws CMSException - */ + * Creates a BytesMessage + * @throws CMSException + */ virtual BytesMessage* createBytesMessage(void) throw ( CMSException) = 0; /** - * Creates a BytesMessage and sets the paylod to the passed value - * @param an array of bytes to set in the message - * @param the size of the bytes array, or number of bytes to use - * @throws CMSException - */ + * Creates a BytesMessage and sets the paylod to the passed value + * @param an array of bytes to set in the message + * @param the size of the bytes array, or number of bytes to use + * @throws CMSException + */ virtual BytesMessage* createBytesMessage( const unsigned char* bytes, unsigned long bytesSize ) throw ( CMSException) = 0; /** - * Creates a new TextMessage - * @throws CMSException - */ + * Creates a new TextMessage + * @throws CMSException + */ virtual TextMessage* createTextMessage(void) throw ( CMSException ) = 0; /** - * Creates a new TextMessage and set the text to the value given - * @param the initial text for the message - * @throws CMSException - */ + * Creates a new TextMessage and set the text to the value given + * @param the initial text for the message + * @throws CMSException + */ virtual TextMessage* createTextMessage( const std::string& text ) throw ( CMSException ) = 0; /** - * Creates a new MapMessage - * @throws CMSException - */ + * Creates a new MapMessage + * @throws CMSException + */ virtual MapMessage* createMapMessage(void) throw ( CMSException ) = 0; /** - * Returns the acknowledgement mode of the session. - * @return the Sessions Acknowledge Mode - */ + * Returns the acknowledgement mode of the session. + * @return the Sessions Acknowledge Mode + */ virtual AcknowledgeMode getAcknowledgeMode(void) const = 0; /** - * Gets if the Sessions is a Transacted Session - * @return transacted true - false. - */ + * Gets if the Sessions is a Transacted Session + * @return transacted true - false. + */ virtual bool isTransacted(void) const = 0; }; diff --git a/activemq-cpp/src/main/cms/Startable.h b/activemq-cpp/src/main/cms/Startable.h index 01c6110441..b83ef3f3e1 100644 --- a/activemq-cpp/src/main/cms/Startable.h +++ b/activemq-cpp/src/main/cms/Startable.h @@ -21,21 +21,22 @@ #include namespace cms{ - - /** - * Interface for a class that implements the start method. - */ - class Startable{ - - public: - - virtual ~Startable(){} - - /** - * Starts the service. - */ - virtual void start() throw( CMSException ) = 0; - }; + + /** + * Interface for a class that implements the start method. + */ + class Startable{ + + public: + + virtual ~Startable(){} + + /** + * Starts the service. + */ + virtual void start() throw( CMSException ) = 0; + + }; } #endif /*CMS_STARTABLE_H*/ diff --git a/activemq-cpp/src/main/cms/Stoppable.h b/activemq-cpp/src/main/cms/Stoppable.h index 9ba4f3e8c6..50accbd5b3 100644 --- a/activemq-cpp/src/main/cms/Stoppable.h +++ b/activemq-cpp/src/main/cms/Stoppable.h @@ -35,6 +35,7 @@ namespace cms{ * Stops this service. */ virtual void stop() throw( CMSException ) = 0; + }; } diff --git a/activemq-cpp/src/main/cms/TextMessage.h b/activemq-cpp/src/main/cms/TextMessage.h index 5d163a19f4..1c0cd25133 100644 --- a/activemq-cpp/src/main/cms/TextMessage.h +++ b/activemq-cpp/src/main/cms/TextMessage.h @@ -22,28 +22,36 @@ #include namespace cms{ - - /** - * Interface for a text message. - */ - class TextMessage : public Message{ - - public: - - virtual ~TextMessage(){} - - /** - * Gets the message character buffer. - * @return The message character buffer. - */ - virtual const char* getText() const throw( CMSException ) = 0; - - /** - * Sets the message contents. - * @param msg The message buffer. - */ - virtual void setText( const char* msg ) throw( CMSException ) = 0; - }; + + /** + * Interface for a text message. + */ + class TextMessage : public Message{ + + public: + + virtual ~TextMessage(){} + + /** + * Gets the message character buffer. + * @return The message character buffer. + */ + virtual const char* getText() const throw( CMSException ) = 0; + + /** + * Sets the message contents, does not take ownership of the passed + * char*, but copies it instead. + * @param msg The message buffer. + */ + virtual void setText( const char* msg ) throw( CMSException ) = 0; + + /** + * Sets the message contents + * @param msg The message buffer. + */ + virtual void setText( const std::string& msg ) throw( CMSException ) = 0; + + }; } #endif /*_CMS_TEXTMESSAGE_H_*/ diff --git a/activemq-cpp/src/test-integration/integration/common/AbstractTester.cpp b/activemq-cpp/src/test-integration/integration/common/AbstractTester.cpp index a7827a1f97..1e31af818b 100644 --- a/activemq-cpp/src/test-integration/integration/common/AbstractTester.cpp +++ b/activemq-cpp/src/test-integration/integration/common/AbstractTester.cpp @@ -89,7 +89,7 @@ unsigned int AbstractTester::produceTextMessages( stream << text << ix << ends; textMsg->setText( stream.str().c_str() ); stream.str(""); - producer.send( *textMsg ); + producer.send( textMsg ); doSleep(); ++realCount; } @@ -125,7 +125,7 @@ unsigned int AbstractTester::produceBytesMessages( unsigned int realCount = 0; for( unsigned int ix=0; ix(message); + + if( txtMsg != NULL ) { - // Got a text message. - const cms::TextMessage& txtMsg = - dynamic_cast(message); - - std::string text = txtMsg.getText(); + std::string text = txtMsg->getText(); // printf("received text msg: %s\n", txtMsg.getText() ); @@ -189,18 +189,16 @@ void AbstractTester::onMessage( const cms::Message& message ) return; } - catch( std::bad_cast& ex ) - {} - try - { - // Got a bytes msg. - const cms::BytesMessage& bytesMsg = - dynamic_cast(message); + // Got a bytes msg. + const cms::BytesMessage* bytesMsg = + dynamic_cast(message); - const unsigned char* bytes = bytesMsg.getBodyBytes(); + if( bytesMsg != NULL ) + { + const unsigned char* bytes = bytesMsg->getBodyBytes(); - string transcode( (const char*)bytes, bytesMsg.getBodyLength() ); + string transcode( (const char*)bytes, bytesMsg->getBodyLength() ); //printf("received bytes msg: " ); //int numBytes = bytesMsg.getBodyLength(); @@ -219,9 +217,4 @@ void AbstractTester::onMessage( const cms::Message& message ) return; } - catch( std::bad_cast& ex ) - { - bool AbstractTester = false; - CPPUNIT_ASSERT( AbstractTester ); - } } diff --git a/activemq-cpp/src/test-integration/integration/common/AbstractTester.h b/activemq-cpp/src/test-integration/integration/common/AbstractTester.h index 691164dc2a..d7073e59a2 100644 --- a/activemq-cpp/src/test-integration/integration/common/AbstractTester.h +++ b/activemq-cpp/src/test-integration/integration/common/AbstractTester.h @@ -18,7 +18,7 @@ namespace common{ public: AbstractTester( cms::Session::AcknowledgeMode ackMode = - cms::Session::AutoAcknowledge ); + cms::Session::AUTO_ACKNOWLEDGE ); virtual ~AbstractTester(); virtual void doSleep(void); @@ -33,7 +33,7 @@ namespace common{ virtual void waitForMessages( unsigned int count ); virtual void onException( const cms::CMSException& error ); - virtual void onMessage( const cms::Message& message ); + virtual void onMessage( const cms::Message* message ); public: diff --git a/activemq-cpp/src/test-integration/integration/common/Tester.h b/activemq-cpp/src/test-integration/integration/common/Tester.h index db895f1776..a06ed3d349 100644 --- a/activemq-cpp/src/test-integration/integration/common/Tester.h +++ b/activemq-cpp/src/test-integration/integration/common/Tester.h @@ -4,7 +4,6 @@ #include #include - namespace integration{ namespace common{ diff --git a/activemq-cpp/src/test-integration/integration/durable/DurableTester.cpp b/activemq-cpp/src/test-integration/integration/durable/DurableTester.cpp index b44baaf932..4407a21f24 100644 --- a/activemq-cpp/src/test-integration/integration/durable/DurableTester.cpp +++ b/activemq-cpp/src/test-integration/integration/durable/DurableTester.cpp @@ -78,10 +78,10 @@ void DurableTester::test() // Create CMS Object for Comms cms::Topic* topic = session->createTopic("mytopic"); cms::MessageConsumer* consumer = - session->createDurableConsumer( *topic, subName, "" ); + session->createDurableConsumer( topic, subName, "" ); consumer->setMessageListener( this ); cms::MessageProducer* producer = - session->createProducer( *topic ); + session->createProducer( topic ); unsigned int sent; @@ -100,7 +100,7 @@ void DurableTester::test() // Send some text messages sent += this->produceTextMessages( *producer, 3 ); - consumer = session->createDurableConsumer( *topic, subName, "" ); + consumer = session->createDurableConsumer( topic, subName, "" ); // Send some text messages sent += this->produceTextMessages( *producer, 3 ); diff --git a/activemq-cpp/src/test-integration/integration/simple/SimpleTester.cpp b/activemq-cpp/src/test-integration/integration/simple/SimpleTester.cpp index 5e69c5827e..3f655057ec 100644 --- a/activemq-cpp/src/test-integration/integration/simple/SimpleTester.cpp +++ b/activemq-cpp/src/test-integration/integration/simple/SimpleTester.cpp @@ -79,10 +79,10 @@ void SimpleTester::test() // Create CMS Object for Comms cms::Topic* topic = session->createTopic("mytopic"); cms::MessageConsumer* consumer = - session->createConsumer( *topic ); + session->createConsumer( topic ); consumer->setMessageListener( this ); cms::MessageProducer* producer = - session->createProducer( *topic ); + session->createProducer( topic ); // Send some text messages this->produceTextMessages( diff --git a/activemq-cpp/src/test-integration/integration/transactional/TransactionTester.cpp b/activemq-cpp/src/test-integration/integration/transactional/TransactionTester.cpp index 5a8a398907..60280272fd 100644 --- a/activemq-cpp/src/test-integration/integration/transactional/TransactionTester.cpp +++ b/activemq-cpp/src/test-integration/integration/transactional/TransactionTester.cpp @@ -56,7 +56,7 @@ using namespace integration; using namespace integration::transactional; using namespace integration::common; -TransactionTester::TransactionTester() : AbstractTester( cms::Session::Transactional ) +TransactionTester::TransactionTester() : AbstractTester( cms::Session::SESSION_TRANSACTED ) {} TransactionTester::~TransactionTester() @@ -76,10 +76,10 @@ void TransactionTester::test() // Create CMS Object for Comms cms::Topic* topic = session->createTopic("mytopic"); cms::MessageConsumer* consumer = - session->createConsumer( *topic ); + session->createConsumer( topic ); consumer->setMessageListener( this ); cms::MessageProducer* producer = - session->createProducer( *topic ); + session->createProducer( topic ); // Send some text messages this->produceTextMessages( @@ -105,11 +105,11 @@ void TransactionTester::test() // Send some text messages this->produceTextMessages( *producer, IntegrationCommon::defaultMsgCount ); - + session->rollback(); // Wait till we get all the messages - waitForMessages( IntegrationCommon::defaultMsgCount * 2 ); + waitForMessages( IntegrationCommon::defaultMsgCount ); printf("received: %d\n", numReceived ); CPPUNIT_ASSERT( diff --git a/activemq-cpp/src/test-integration/integration/various/SimpleRollbackTest.cpp b/activemq-cpp/src/test-integration/integration/various/SimpleRollbackTest.cpp new file mode 100644 index 0000000000..a1f89e29eb --- /dev/null +++ b/activemq-cpp/src/test-integration/integration/various/SimpleRollbackTest.cpp @@ -0,0 +1,236 @@ +#include "SimpleRollbackTest.h" + +#include + +CPPUNIT_TEST_SUITE_REGISTRATION( integration::various::SimpleRollbackTest ); + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace activemq::connector::stomp; +using namespace activemq::transport; +using namespace activemq::util; +using namespace std; +using namespace cms; +using namespace activemq; +using namespace activemq::core; +using namespace activemq::util; +using namespace activemq::connector; +using namespace activemq::exceptions; +using namespace activemq::network; +using namespace activemq::transport; +using namespace activemq::concurrent; + +using namespace std; +using namespace integration; +using namespace integration::various; +using namespace integration::common; + +SimpleRollbackTest::SimpleRollbackTest() +{ + try + { + string url = IntegrationCommon::defaultURL; + numReceived = 0; + + // Default amount to send and receive + msgCount = 1; + + // Create a Factory + connectionFactory = new ActiveMQConnectionFactory( url ); + + // Now create the connection + connection = connectionFactory->createConnection( + "", "", Guid().createGUIDString() ); + + // Set ourself as a recipient of Exceptions + connection->setExceptionListener( this ); + connection->start(); + + // Create a Session + session = connection->createSession( + cms::Session::SESSION_TRANSACTED ); + } + AMQ_CATCH_RETHROW( ActiveMQException ) + AMQ_CATCHALL_THROW( ActiveMQException ) +} + +SimpleRollbackTest::~SimpleRollbackTest() +{ + try + { + session->close(); + connection->close(); + + delete session; + delete connection; + delete connectionFactory; + } + AMQ_CATCH_NOTHROW( ActiveMQException ) + AMQ_CATCHALL_NOTHROW( ) +} + +void SimpleRollbackTest::test() +{ + try + { + // Create CMS Object for Comms + cms::Topic* topic = session->createTopic("mytopic"); + cms::MessageConsumer* consumer = + session->createConsumer( topic ); + consumer->setMessageListener( this ); + cms::MessageProducer* producer = + session->createProducer( topic ); + + cms::TextMessage* textMsg = + session->createTextMessage(); + + for( size_t ix = 0; ix < msgCount; ++ix ) + { + ostringstream lcStream; + lcStream << "SimpleTest - Message #" << ix << ends; + textMsg->setText( lcStream.str() ); + producer->send( textMsg ); + } + + delete textMsg; + + Thread::sleep( 100 ); + + session->commit(); + + textMsg = session->createTextMessage(); + + for( size_t ix = 0; ix < msgCount; ++ix ) + { + ostringstream lcStream; + lcStream << "SimpleTest - Message #" << ix << ends; + textMsg->setText( lcStream.str() ); + producer->send( textMsg ); + } + + delete textMsg; + + Thread::sleep( 500 ); + + session->rollback(); + + Thread::sleep( 500 ); + + textMsg = session->createTextMessage(); + textMsg->setText( "SimpleTest - Message after Rollback" ); + producer->send( textMsg ); + delete textMsg; + + Thread::sleep( 15000 ); + + CPPUNIT_ASSERT( true ); + + printf( "Shutting Down\n" ); + + delete producer; + delete consumer; + } + AMQ_CATCH_RETHROW( ActiveMQException ) + AMQ_CATCHALL_THROW( ActiveMQException ) +} + +void SimpleRollbackTest::onException( const cms::CMSException& error ) +{ + bool AbstractTester = false; + CPPUNIT_ASSERT( AbstractTester ); +} + +void SimpleRollbackTest::onMessage( const cms::Message* message ) +{ + try + { + // Got a text message. + const cms::TextMessage* txtMsg = + dynamic_cast(message); + + if( txtMsg != NULL ) + { + std::string text = txtMsg->getText(); + + // printf("received text msg: %s\n", txtMsg.getText() ); + + numReceived++; + + // Signal that we got one + synchronized( &mutex ) + { + mutex.notifyAll(); + } + + return; + } + + // Got a bytes msg. + const cms::BytesMessage* bytesMsg = + dynamic_cast(message); + + if( bytesMsg != NULL ) + { + const unsigned char* bytes = bytesMsg->getBodyBytes(); + + string transcode( (const char*)bytes, bytesMsg->getBodyLength() ); + + //printf("received bytes msg: " ); + //int numBytes = bytesMsg.getBodyLength(); + //for( int ix=0; ix +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace integration{ +namespace various{ + + class SimpleRollbackTest : public CppUnit::TestFixture, + public cms::ExceptionListener, + public cms::MessageListener + { + CPPUNIT_TEST_SUITE( SimpleRollbackTest ); + CPPUNIT_TEST( test ); + CPPUNIT_TEST_SUITE_END(); + + public: + + SimpleRollbackTest(); + virtual ~SimpleRollbackTest(); + + virtual void test(void); + + virtual void onException( const cms::CMSException& error ); + virtual void onMessage( const cms::Message* message ); + + private: + + cms::ConnectionFactory* connectionFactory; + cms::Connection* connection; + cms::Session* session; + + unsigned int numReceived; + unsigned int msgCount; + activemq::concurrent::Mutex mutex; + + }; + +}} + +#endif /*_INTEGRATION_VARIOUS_SIMPLEROLLBACKTEST_H_*/ diff --git a/activemq-cpp/src/test/activemq/concurrent/MutexTest.h b/activemq-cpp/src/test/activemq/concurrent/MutexTest.h index 6bb467cec2..087671a8da 100644 --- a/activemq-cpp/src/test/activemq/concurrent/MutexTest.h +++ b/activemq-cpp/src/test/activemq/concurrent/MutexTest.h @@ -184,11 +184,18 @@ namespace concurrent{ bool done; Mutex* mutex; + Mutex* started; + Mutex* completed; public: int value; - MyNotifiedThread(Mutex* mutex){ this->mutex = mutex; done = false; } + MyNotifiedThread(Mutex* mutex, Mutex* started, Mutex* completed ){ + this->mutex = mutex; + this->started = started; + this->completed = completed; + this->done = false; + } virtual ~MyNotifiedThread(){} virtual void lock() throw(exceptions::ActiveMQException){ mutex->lock(); @@ -215,9 +222,19 @@ namespace concurrent{ { done = false; synchronized(this) - { + { + synchronized( started ) + { + started->notify(); + } + this->wait(); done = true; + + synchronized( completed ) + { + completed->notify(); + } } } catch(exceptions::ActiveMQException& ex) @@ -401,17 +418,28 @@ namespace concurrent{ { try{ Mutex mutex; + Mutex started; + Mutex completed; + const int numThreads = 30; MyNotifiedThread* threads[numThreads]; // Create and start all the threads. for( int ix=0; ixstart(); } - // Sleep so all the threads can get to the wait. - Thread::sleep( 1000 ); + synchronized( &started ) + { + int count = 0; + + while( count < ( numThreads ) ) + { + started.wait( 30 ); + count++; + } + } synchronized(&mutex) { @@ -438,8 +466,16 @@ namespace concurrent{ } } - // Sleep to give the threads time to wake up. - Thread::sleep( 1000 ); + synchronized( &started ) + { + int count = 0; + + while( count < ( numThreads ) ) + { + started.wait( 30 ); + count++; + } + } int numComplete = 0; for( int ix=0; ixstart(); } - // Sleep so all the threads can get to the wait. - Thread::sleep( 1000 ); + synchronized( &started ) + { + int count = 0; + + while( count < ( numThreads ) ) + { + started.wait( 30 ); + count++; + } + } for( int ix=0; ixjoin(); + delete threads[ix]; + } + }catch( exceptions::ActiveMQException& ex ){ ex.setMark( __FILE__, __LINE__ ); } @@ -554,6 +619,12 @@ namespace concurrent{ } CPPUNIT_ASSERT( threads[ix]->done == true ); } + + // Delete all the threads. + for( int ix=0; ixgetBodyLength() ); CPPUNIT_ASSERT( bytesText == "123456789" ); + delete command; } }; diff --git a/activemq-cpp/src/test/activemq/connector/stomp/StompCommandWriterTest.h b/activemq-cpp/src/test/activemq/connector/stomp/StompCommandWriterTest.h index 12d52f5c77..1eb58ace08 100644 --- a/activemq-cpp/src/test/activemq/connector/stomp/StompCommandWriterTest.h +++ b/activemq-cpp/src/test/activemq/connector/stomp/StompCommandWriterTest.h @@ -57,14 +57,16 @@ namespace stomp{ connectedCommand.setSessionId( "test" ); // Sync to expected output - textCommand.setCMSDestination( StompTopic("a") ); + StompTopic topic1("a"); + textCommand.setCMSDestination( &topic1 ); textCommand.setCMSMessageId( "123" ); textCommand.getProperties().setProperty( "sampleProperty", "testvalue" ); textCommand.setText( "testMessage" ); // Sync to expected output - bytesCommand.setCMSDestination( StompTopic("a") ); + StompTopic topic2("a"); + bytesCommand.setCMSDestination( &topic2 ); bytesCommand.setCMSMessageId( "123" ); bytesCommand.getProperties().setProperty( "sampleProperty", "testvalue" ); diff --git a/activemq-cpp/src/test/activemq/connector/stomp/StompConnectorTest.h b/activemq-cpp/src/test/activemq/connector/stomp/StompConnectorTest.h index 9105feca59..4314eb2628 100644 --- a/activemq-cpp/src/test/activemq/connector/stomp/StompConnectorTest.h +++ b/activemq-cpp/src/test/activemq/connector/stomp/StompConnectorTest.h @@ -65,6 +65,8 @@ namespace stomp{ core::ActiveMQMessage* msg ) { consumers.push_back( consumer ); + + delete msg; } }; @@ -77,20 +79,20 @@ namespace stomp{ StompConnector connector( &transport, properties ); connector.start(); - SessionInfo* info1 = connector.createSession( cms::Session::AutoAcknowledge ); - CPPUNIT_ASSERT( info1->getAckMode() == cms::Session::AutoAcknowledge ); + SessionInfo* info1 = connector.createSession( cms::Session::AUTO_ACKNOWLEDGE ); + CPPUNIT_ASSERT( info1->getAckMode() == cms::Session::AUTO_ACKNOWLEDGE ); CPPUNIT_ASSERT( info1->getConnectionId() == connectionId ); - SessionInfo* info2 = connector.createSession( cms::Session::DupsOkAcknowledge ); - CPPUNIT_ASSERT( info2->getAckMode() == cms::Session::DupsOkAcknowledge ); + SessionInfo* info2 = connector.createSession( cms::Session::DUPS_OK_ACKNOWLEDGE ); + CPPUNIT_ASSERT( info2->getAckMode() == cms::Session::DUPS_OK_ACKNOWLEDGE ); CPPUNIT_ASSERT( info2->getConnectionId() == connectionId ); - SessionInfo* info3 = connector.createSession( cms::Session::ClientAcknowledge ); - CPPUNIT_ASSERT( info3->getAckMode() == cms::Session::ClientAcknowledge ); + SessionInfo* info3 = connector.createSession( cms::Session::CLIENT_ACKNOWLEDGE ); + CPPUNIT_ASSERT( info3->getAckMode() == cms::Session::CLIENT_ACKNOWLEDGE ); CPPUNIT_ASSERT( info3->getConnectionId() == connectionId ); - SessionInfo* info4 = connector.createSession( cms::Session::Transactional ); - CPPUNIT_ASSERT( info4->getAckMode() == cms::Session::Transactional ); + SessionInfo* info4 = connector.createSession( cms::Session::SESSION_TRANSACTED ); + CPPUNIT_ASSERT( info4->getAckMode() == cms::Session::SESSION_TRANSACTED ); CPPUNIT_ASSERT( info4->getConnectionId() == connectionId ); connector.destroyResource( info1 ); @@ -109,7 +111,7 @@ namespace stomp{ StompConnector connector( &transport, properties ); connector.start(); - SessionInfo* info1 = connector.createSession( cms::Session::AutoAcknowledge ); + SessionInfo* info1 = connector.createSession( cms::Session::AUTO_ACKNOWLEDGE ); std::string sel1 = ""; StompTopic dest1( "dummy.topic.1" ); ConsumerInfo* cinfo1 = connector.createConsumer( &dest1, info1, sel1 ); @@ -117,7 +119,7 @@ namespace stomp{ CPPUNIT_ASSERT( cinfo1->getDestination().toString() == dest1.toString() ); CPPUNIT_ASSERT( cinfo1->getMessageSelector() == sel1 ); - SessionInfo* info2 = connector.createSession( cms::Session::DupsOkAcknowledge ); + SessionInfo* info2 = connector.createSession( cms::Session::DUPS_OK_ACKNOWLEDGE ); std::string sel2 = "mysel2"; StompTopic dest2( "dummy.topic.2" ); ConsumerInfo* cinfo2 = connector.createConsumer( &dest2, info2, sel2 ); @@ -125,7 +127,7 @@ namespace stomp{ CPPUNIT_ASSERT( cinfo2->getDestination().toString() == dest2.toString() ); CPPUNIT_ASSERT( cinfo2->getMessageSelector() == sel2 ); - SessionInfo* info3 = connector.createSession( cms::Session::ClientAcknowledge ); + SessionInfo* info3 = connector.createSession( cms::Session::CLIENT_ACKNOWLEDGE ); std::string sel3 = "mysel3"; StompQueue dest3( "dummy.queue.1" ); ConsumerInfo* cinfo3 = connector.createConsumer( &dest3, info3, sel3 ); @@ -133,7 +135,7 @@ namespace stomp{ CPPUNIT_ASSERT( cinfo3->getDestination().toString() == dest3.toString() ); CPPUNIT_ASSERT( cinfo3->getMessageSelector() == sel3 ); - SessionInfo* info4 = connector.createSession( cms::Session::Transactional ); + SessionInfo* info4 = connector.createSession( cms::Session::SESSION_TRANSACTED ); std::string sel4 = ""; StompTopic dest4( "dummy.queue.2" ); ConsumerInfo* cinfo4 = connector.createConsumer( &dest4, info4, sel4 ); @@ -161,25 +163,25 @@ namespace stomp{ StompConnector connector( &transport, properties ); connector.start(); - SessionInfo* info1 = connector.createSession( cms::Session::AutoAcknowledge ); + SessionInfo* info1 = connector.createSession( cms::Session::AUTO_ACKNOWLEDGE ); StompTopic dest1( "dummy.topic.1" ); ProducerInfo* pinfo1 = connector.createProducer( &dest1, info1 ); CPPUNIT_ASSERT( pinfo1->getSessionInfo() == info1 ); CPPUNIT_ASSERT( pinfo1->getDestination().toString() == dest1.toString() ); - SessionInfo* info2 = connector.createSession( cms::Session::DupsOkAcknowledge ); + SessionInfo* info2 = connector.createSession( cms::Session::DUPS_OK_ACKNOWLEDGE ); StompTopic dest2( "dummy.topic.2" ); ProducerInfo* pinfo2 = connector.createProducer( &dest2, info2 ); CPPUNIT_ASSERT( pinfo2->getSessionInfo() == info2 ); CPPUNIT_ASSERT( pinfo2->getDestination().toString() == dest2.toString() ); - SessionInfo* info3 = connector.createSession( cms::Session::ClientAcknowledge ); + SessionInfo* info3 = connector.createSession( cms::Session::CLIENT_ACKNOWLEDGE ); StompQueue dest3( "dummy.queue.1" ); ProducerInfo* pinfo3 = connector.createProducer( &dest3, info3 ); CPPUNIT_ASSERT( pinfo3->getSessionInfo() == info3 ); CPPUNIT_ASSERT( pinfo3->getDestination().toString() == dest3.toString() ); - SessionInfo* info4 = connector.createSession( cms::Session::Transactional ); + SessionInfo* info4 = connector.createSession( cms::Session::SESSION_TRANSACTED ); StompTopic dest4( "dummy.queue.2" ); ProducerInfo* pinfo4 = connector.createProducer( &dest4, info4 ); CPPUNIT_ASSERT( pinfo4->getSessionInfo() == info4 ); @@ -208,16 +210,16 @@ namespace stomp{ StompTopic dest1( "dummy.topic" ); StompTopic dest2( "dummy.topic2" ); - SessionInfo* info1 = connector.createSession( cms::Session::AutoAcknowledge ); + SessionInfo* info1 = connector.createSession( cms::Session::AUTO_ACKNOWLEDGE ); ConsumerInfo* cinfo1 = connector.createConsumer( &dest1, info1, "" ); - SessionInfo* info2 = connector.createSession( cms::Session::DupsOkAcknowledge ); + SessionInfo* info2 = connector.createSession( cms::Session::DUPS_OK_ACKNOWLEDGE ); ConsumerInfo* cinfo2 = connector.createConsumer( &dest1, info2, "" ); - SessionInfo* info3 = connector.createSession( cms::Session::ClientAcknowledge ); + SessionInfo* info3 = connector.createSession( cms::Session::CLIENT_ACKNOWLEDGE ); ConsumerInfo* cinfo3 = connector.createConsumer( &dest2, info3, "" ); - SessionInfo* info4 = connector.createSession( cms::Session::Transactional ); + SessionInfo* info4 = connector.createSession( cms::Session::SESSION_TRANSACTED ); ConsumerInfo* cinfo4 = connector.createConsumer( &dest2, info4, "" ); MyMessageListener listener; @@ -285,13 +287,13 @@ namespace stomp{ MyCommandListener cmdListener; transport.setOutgoingCommandListener( &cmdListener ); - SessionInfo* info1 = connector->createSession( cms::Session::AutoAcknowledge ); + SessionInfo* info1 = connector->createSession( cms::Session::AUTO_ACKNOWLEDGE ); ConsumerInfo* cinfo1 = connector->createConsumer( &dest1, info1, "" ); CPPUNIT_ASSERT( cmdListener.cmd != NULL ); cmdListener.cmd = NULL; - SessionInfo* info2 = connector->createSession( cms::Session::DupsOkAcknowledge ); + SessionInfo* info2 = connector->createSession( cms::Session::DUPS_OK_ACKNOWLEDGE ); ConsumerInfo* cinfo2 = connector->createConsumer( &dest1, info2, "" ); CPPUNIT_ASSERT( cmdListener.cmd == NULL ); diff --git a/activemq-cpp/src/test/activemq/connector/stomp/StompResponseBuilder.h b/activemq-cpp/src/test/activemq/connector/stomp/StompResponseBuilder.h index e5cd129dfe..d1cf899abb 100644 --- a/activemq-cpp/src/test/activemq/connector/stomp/StompResponseBuilder.h +++ b/activemq-cpp/src/test/activemq/connector/stomp/StompResponseBuilder.h @@ -31,7 +31,16 @@ namespace stomp{ if( connectCommand != NULL ){ commands::ConnectedCommand* resp = new commands::ConnectedCommand(); resp->setCorrelationId( connectCommand->getCommandId() ); - resp->setSessionId( sessionId ); + + if( connectCommand->getClientId() == NULL ) + { + resp->setSessionId( sessionId ); + } + else + { + resp->setSessionId( connectCommand->getClientId() ); + } + return resp; } diff --git a/activemq-cpp/src/test/activemq/connector/stomp/StompSessionManagerTest.h b/activemq-cpp/src/test/activemq/connector/stomp/StompSessionManagerTest.h index baea196801..645413bfd0 100644 --- a/activemq-cpp/src/test/activemq/connector/stomp/StompSessionManagerTest.h +++ b/activemq-cpp/src/test/activemq/connector/stomp/StompSessionManagerTest.h @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -26,24 +27,47 @@ namespace stomp{ CPPUNIT_TEST( testConsumers ); CPPUNIT_TEST( testCommand ); CPPUNIT_TEST( testSendingCommands ); + CPPUNIT_TEST( testSubscribeOptions ); CPPUNIT_TEST_SUITE_END(); public: + typedef std::pair< std::string, std::string > MyProperty; + class MyCommandListener : public transport::CommandListener{ public: transport::Command* cmd; + commands::SubscribeCommand* subscribe; + + // Properties that should be in an command + std::vector< MyProperty > expected; public: MyCommandListener(){ cmd = NULL; + subscribe = NULL; } virtual ~MyCommandListener(){} virtual void onCommand( transport::Command* command ){ cmd = command; + + subscribe = dynamic_cast< commands::SubscribeCommand* >( command ); + if( subscribe ) + { + const util::Properties& properties = + subscribe->getProperties(); + + for( size_t ix = 0; ix < expected.size(); ++ix ) + { + std::string value = + properties.getProperty( expected[ix].first, "" ); + + CPPUNIT_ASSERT( value == expected[ix].second ); + } + } } }; @@ -59,6 +83,8 @@ namespace stomp{ core::ActiveMQMessage* msg ) { consumers.push_back( consumer ); + + delete msg; } }; @@ -71,20 +97,20 @@ namespace stomp{ transport::DummyTransport transport( &responseBuilder ); StompSessionManager manager( connectionId, &transport ); - SessionInfo* info1 = manager.createSession( cms::Session::AutoAcknowledge ); - CPPUNIT_ASSERT( info1->getAckMode() == cms::Session::AutoAcknowledge ); + SessionInfo* info1 = manager.createSession( cms::Session::AUTO_ACKNOWLEDGE ); + CPPUNIT_ASSERT( info1->getAckMode() == cms::Session::AUTO_ACKNOWLEDGE ); CPPUNIT_ASSERT( info1->getConnectionId() == connectionId ); - SessionInfo* info2 = manager.createSession( cms::Session::DupsOkAcknowledge ); - CPPUNIT_ASSERT( info2->getAckMode() == cms::Session::DupsOkAcknowledge ); + SessionInfo* info2 = manager.createSession( cms::Session::DUPS_OK_ACKNOWLEDGE ); + CPPUNIT_ASSERT( info2->getAckMode() == cms::Session::DUPS_OK_ACKNOWLEDGE ); CPPUNIT_ASSERT( info2->getConnectionId() == connectionId ); - SessionInfo* info3 = manager.createSession( cms::Session::ClientAcknowledge ); - CPPUNIT_ASSERT( info3->getAckMode() == cms::Session::ClientAcknowledge ); + SessionInfo* info3 = manager.createSession( cms::Session::CLIENT_ACKNOWLEDGE ); + CPPUNIT_ASSERT( info3->getAckMode() == cms::Session::CLIENT_ACKNOWLEDGE ); CPPUNIT_ASSERT( info3->getConnectionId() == connectionId ); - SessionInfo* info4 = manager.createSession( cms::Session::Transactional ); - CPPUNIT_ASSERT( info4->getAckMode() == cms::Session::Transactional ); + SessionInfo* info4 = manager.createSession( cms::Session::SESSION_TRANSACTED ); + CPPUNIT_ASSERT( info4->getAckMode() == cms::Session::SESSION_TRANSACTED ); CPPUNIT_ASSERT( info4->getConnectionId() == connectionId ); delete info1; @@ -100,7 +126,7 @@ namespace stomp{ transport::DummyTransport transport( &responseBuilder ); StompSessionManager manager( connectionId, &transport ); - SessionInfo* info1 = manager.createSession( cms::Session::AutoAcknowledge ); + SessionInfo* info1 = manager.createSession( cms::Session::AUTO_ACKNOWLEDGE ); std::string sel1 = ""; StompTopic dest1( "dummy.topic.1" ); ConsumerInfo* cinfo1 = manager.createConsumer( &dest1, info1, sel1 ); @@ -108,7 +134,7 @@ namespace stomp{ CPPUNIT_ASSERT( cinfo1->getDestination().toString() == dest1.toString() ); CPPUNIT_ASSERT( cinfo1->getMessageSelector() == sel1 ); - SessionInfo* info2 = manager.createSession( cms::Session::DupsOkAcknowledge ); + SessionInfo* info2 = manager.createSession( cms::Session::DUPS_OK_ACKNOWLEDGE ); std::string sel2 = "mysel2"; StompTopic dest2( "dummy.topic.2" ); ConsumerInfo* cinfo2 = manager.createConsumer( &dest2, info2, sel2 ); @@ -116,7 +142,7 @@ namespace stomp{ CPPUNIT_ASSERT( cinfo2->getDestination().toString() == dest2.toString() ); CPPUNIT_ASSERT( cinfo2->getMessageSelector() == sel2 ); - SessionInfo* info3 = manager.createSession( cms::Session::ClientAcknowledge ); + SessionInfo* info3 = manager.createSession( cms::Session::CLIENT_ACKNOWLEDGE ); std::string sel3 = "mysel3"; StompQueue dest3( "dummy.queue.1" ); ConsumerInfo* cinfo3 = manager.createConsumer( &dest3, info3, sel3 ); @@ -124,7 +150,7 @@ namespace stomp{ CPPUNIT_ASSERT( cinfo3->getDestination().toString() == dest3.toString() ); CPPUNIT_ASSERT( cinfo3->getMessageSelector() == sel3 ); - SessionInfo* info4 = manager.createSession( cms::Session::Transactional ); + SessionInfo* info4 = manager.createSession( cms::Session::SESSION_TRANSACTED ); std::string sel4 = ""; StompTopic dest4( "dummy.queue.2" ); ConsumerInfo* cinfo4 = manager.createConsumer( &dest4, info4, sel4 ); @@ -153,23 +179,23 @@ namespace stomp{ StompTopic dest1( "dummy.topic" ); StompTopic dest2( "dummy.topic2" ); - SessionInfo* info1 = manager.createSession( cms::Session::AutoAcknowledge ); + SessionInfo* info1 = manager.createSession( cms::Session::AUTO_ACKNOWLEDGE ); ConsumerInfo* cinfo1 = manager.createConsumer( &dest1, info1, "" ); - SessionInfo* info2 = manager.createSession( cms::Session::DupsOkAcknowledge ); + SessionInfo* info2 = manager.createSession( cms::Session::DUPS_OK_ACKNOWLEDGE ); ConsumerInfo* cinfo2 = manager.createConsumer( &dest1, info2, "" ); - SessionInfo* info3 = manager.createSession( cms::Session::ClientAcknowledge ); + SessionInfo* info3 = manager.createSession( cms::Session::CLIENT_ACKNOWLEDGE ); ConsumerInfo* cinfo3 = manager.createConsumer( &dest2, info3, "" ); - SessionInfo* info4 = manager.createSession( cms::Session::Transactional ); + SessionInfo* info4 = manager.createSession( cms::Session::SESSION_TRANSACTED ); ConsumerInfo* cinfo4 = manager.createConsumer( &dest2, info4, "" ); MyMessageListener listener; manager.setConsumerMessageListener( &listener ); commands::TextMessageCommand* msg = new commands::TextMessageCommand(); - msg->setCMSDestination( dest1 ); + msg->setCMSDestination( &dest1 ); msg->setText( "hello world" ); manager.onStompCommand( msg ); @@ -183,7 +209,7 @@ namespace stomp{ listener.consumers.clear(); msg = new commands::TextMessageCommand(); - msg->setCMSDestination( dest2 ); + msg->setCMSDestination( &dest2 ); msg->setText( "hello world" ); manager.onStompCommand( msg ); @@ -192,7 +218,7 @@ namespace stomp{ CPPUNIT_ASSERT( listener.consumers[ix] == cinfo3 || listener.consumers[ix] == cinfo4 ); } - + delete info1; delete info2; delete info3; @@ -218,13 +244,13 @@ namespace stomp{ MyCommandListener cmdListener; transport.setOutgoingCommandListener( &cmdListener ); - SessionInfo* info1 = manager.createSession( cms::Session::AutoAcknowledge ); + SessionInfo* info1 = manager.createSession( cms::Session::AUTO_ACKNOWLEDGE ); ConsumerInfo* cinfo1 = manager.createConsumer( &dest1, info1, "" ); CPPUNIT_ASSERT( cmdListener.cmd != NULL ); cmdListener.cmd = NULL; - SessionInfo* info2 = manager.createSession( cms::Session::DupsOkAcknowledge ); + SessionInfo* info2 = manager.createSession( cms::Session::DUPS_OK_ACKNOWLEDGE ); ConsumerInfo* cinfo2 = manager.createConsumer( &dest1, info2, "" ); CPPUNIT_ASSERT( cmdListener.cmd == NULL ); @@ -245,6 +271,97 @@ namespace stomp{ delete cinfo2; } + void testSubscribeOptions(){ + + std::string connectionId = "testConnectionId"; + StompResponseBuilder responseBuilder("testSessionId"); + transport::DummyTransport transport( &responseBuilder ); + StompSessionManager manager( connectionId, &transport ); + + MyProperty retroactive = + std::make_pair( "activemq.retroactive", "true" ); + MyProperty prefetchSize = + std::make_pair( "activemq.prefetchSize", "1000" ); + MyProperty maxPendingMsgLimit = + std::make_pair( "activemq.maximumPendingMessageLimit", "0" ); + MyProperty noLocal = + std::make_pair( "activemq.noLocal", "true" ); + MyProperty dispatchAsync = + std::make_pair( "activemq.dispatchAsync", "true" ); + MyProperty selector = + std::make_pair( "selector", "test" ); + MyProperty exclusive = + std::make_pair( "activemq.exclusive", "true" ); + MyProperty priority = + std::make_pair( "activemq.priority", "1" ); + + SessionInfo* session = NULL; + ConsumerInfo* consumer = NULL; + + MyCommandListener cmdListener; + transport.setOutgoingCommandListener( &cmdListener ); + + session = manager.createSession( cms::Session::AUTO_ACKNOWLEDGE ); + + cmdListener.expected.clear(); + StompTopic dest1( "dummy.topic.1" ); + consumer = manager.createConsumer( &dest1, session, "" ); + CPPUNIT_ASSERT( consumer != NULL ); + CPPUNIT_ASSERT( cmdListener.subscribe != NULL ); + + manager.removeConsumer( consumer ); + CPPUNIT_ASSERT( cmdListener.cmd != NULL ); + delete consumer; + cmdListener.cmd = NULL; + cmdListener.subscribe = NULL; + + cmdListener.expected.clear(); + cmdListener.expected.push_back( retroactive ); + StompTopic dest2( "dummy.topic.1?consumer.retroactive=true" ); + consumer = manager.createConsumer( &dest2, session, "" ); + CPPUNIT_ASSERT( consumer != NULL ); + CPPUNIT_ASSERT( cmdListener.subscribe != NULL ); + + manager.removeConsumer( consumer ); + CPPUNIT_ASSERT( cmdListener.cmd != NULL ); + delete consumer; + cmdListener.cmd = NULL; + cmdListener.subscribe = NULL; + + cmdListener.expected.clear(); + cmdListener.expected.push_back( retroactive ); + cmdListener.expected.push_back( prefetchSize ); + cmdListener.expected.push_back( maxPendingMsgLimit ); + cmdListener.expected.push_back( noLocal ); + cmdListener.expected.push_back( dispatchAsync ); + cmdListener.expected.push_back( selector ); + cmdListener.expected.push_back( exclusive ); + cmdListener.expected.push_back( priority ); + StompTopic dest3( + std::string( "dummy.topic.1?" ) + + "consumer.retroactive=" + retroactive.second + "&" + + "consumer.prefetchSize=" + prefetchSize.second + "&" + + "consumer.maximumPendingMessageLimit=" + maxPendingMsgLimit.second + "&" + + "consumer.noLocal=" + noLocal.second + "&" + + "consumer.dispatchAsync=" + dispatchAsync.second + "&" + + "consumer.selector=" + selector.second + "&" + + "consumer.exclusive=" + exclusive.second + "&" + + "consumer.priority=" + priority.second ); + consumer = manager.createConsumer( &dest3, session, "" ); + CPPUNIT_ASSERT( consumer != NULL ); + CPPUNIT_ASSERT( cmdListener.subscribe != NULL ); + + manager.removeConsumer( consumer ); + CPPUNIT_ASSERT( cmdListener.cmd != NULL ); + delete consumer; + cmdListener.cmd = NULL; + cmdListener.subscribe = NULL; + + // Done + delete session; + + } + }; }}} diff --git a/activemq-cpp/src/test/activemq/connector/stomp/commands/BytesMessageCommandTest.h b/activemq-cpp/src/test/activemq/connector/stomp/commands/BytesMessageCommandTest.h index 40868ca25c..71146c82c8 100644 --- a/activemq-cpp/src/test/activemq/connector/stomp/commands/BytesMessageCommandTest.h +++ b/activemq-cpp/src/test/activemq/connector/stomp/commands/BytesMessageCommandTest.h @@ -65,8 +65,8 @@ namespace commands{ CPPUNIT_ASSERT( std::string( cmd.getTransactionId() ) == "ID:123456" ); StompTopic topic("testTopic"); - cmd.setCMSDestination( topic ); - CPPUNIT_ASSERT( cmd.getCMSDestination().toString() == + cmd.setCMSDestination( &topic ); + CPPUNIT_ASSERT( cmd.getCMSDestination()->toString() == "testTopic" ); StompFrame* frame = cmd.marshal().clone(); @@ -98,12 +98,12 @@ namespace commands{ CPPUNIT_ASSERT( std::string( cmd.getCMSCorrelationId() ) == "ID:1234567" ); CPPUNIT_ASSERT( cmd.getCMSDeliveryMode() == - cms::Message::PERSISTANT ); - cmd.setCMSDeliveryMode( cms::Message::NONPERSISTANT ); + cms::DeliveryMode::PERSISTANT ); + cmd.setCMSDeliveryMode( cms::DeliveryMode::NON_PERSISTANT ); CPPUNIT_ASSERT( cmd.getCMSDeliveryMode() == - cms::Message::NONPERSISTANT ); - cmd.setCMSDestination( topic ); - CPPUNIT_ASSERT( cmd.getCMSDestination().toString() == + cms::DeliveryMode::NON_PERSISTANT ); + cmd.setCMSDestination( &topic ); + CPPUNIT_ASSERT( cmd.getCMSDestination()->toString() == "testTopic" ); CPPUNIT_ASSERT( cmd.getCMSExpiration() == 0 ); cmd.setCMSExpiration( 123 ); diff --git a/activemq-cpp/src/test/activemq/connector/stomp/commands/MessageCommandTest.h b/activemq-cpp/src/test/activemq/connector/stomp/commands/MessageCommandTest.h index aae0662e8e..c796684bdd 100644 --- a/activemq-cpp/src/test/activemq/connector/stomp/commands/MessageCommandTest.h +++ b/activemq-cpp/src/test/activemq/connector/stomp/commands/MessageCommandTest.h @@ -66,7 +66,7 @@ namespace commands{ CPPUNIT_ASSERT( std::string( cmd.getTransactionId() ) == "ID:123456" ); StompTopic topic("testTopic"); - cmd.setCMSDestination( topic ); + cmd.setCMSDestination( &topic ); StompFrame* frame = cmd.marshal().clone(); @@ -98,11 +98,11 @@ namespace commands{ CPPUNIT_ASSERT( std::string( cmd.getCMSCorrelationId() ) == "ID:1234567" ); CPPUNIT_ASSERT( cmd.getCMSDeliveryMode() == - cms::Message::PERSISTANT ); - cmd.setCMSDeliveryMode( cms::Message::NONPERSISTANT ); + cms::DeliveryMode::PERSISTANT ); + cmd.setCMSDeliveryMode( cms::DeliveryMode::NON_PERSISTANT ); CPPUNIT_ASSERT( cmd.getCMSDeliveryMode() == - cms::Message::NONPERSISTANT ); - CPPUNIT_ASSERT( cmd.getCMSDestination().toString() == + cms::DeliveryMode::NON_PERSISTANT ); + CPPUNIT_ASSERT( cmd.getCMSDestination()->toString() == "testTopic" ); CPPUNIT_ASSERT( cmd.getCMSExpiration() == 0 ); cmd.setCMSExpiration( 123 ); diff --git a/activemq-cpp/src/test/activemq/connector/stomp/commands/TextMessageCommandTest.h b/activemq-cpp/src/test/activemq/connector/stomp/commands/TextMessageCommandTest.h index 29818fd857..61406ee905 100644 --- a/activemq-cpp/src/test/activemq/connector/stomp/commands/TextMessageCommandTest.h +++ b/activemq-cpp/src/test/activemq/connector/stomp/commands/TextMessageCommandTest.h @@ -65,7 +65,7 @@ namespace commands{ CPPUNIT_ASSERT( std::string( cmd.getTransactionId() ) == "ID:123456" ); StompTopic topic("testTopic"); - cmd.setCMSDestination( topic ); + cmd.setCMSDestination( &topic ); StompFrame* frame = cmd.marshal().clone(); @@ -97,11 +97,11 @@ namespace commands{ CPPUNIT_ASSERT( std::string( cmd.getCMSCorrelationId() ) == "ID:1234567" ); CPPUNIT_ASSERT( cmd.getCMSDeliveryMode() == - cms::Message::PERSISTANT ); - cmd.setCMSDeliveryMode( cms::Message::NONPERSISTANT ); + cms::DeliveryMode::PERSISTANT ); + cmd.setCMSDeliveryMode( cms::DeliveryMode::NON_PERSISTANT ); CPPUNIT_ASSERT( cmd.getCMSDeliveryMode() == - cms::Message::NONPERSISTANT ); - CPPUNIT_ASSERT( cmd.getCMSDestination().toString() == + cms::DeliveryMode::NON_PERSISTANT ); + CPPUNIT_ASSERT( cmd.getCMSDestination()->toString() == "testTopic" ); CPPUNIT_ASSERT( cmd.getCMSExpiration() == 0 ); cmd.setCMSExpiration( 123 ); diff --git a/activemq-cpp/src/test/activemq/connector/stomp/marshal/MarshalerTest.h b/activemq-cpp/src/test/activemq/connector/stomp/marshal/MarshalerTest.h index 95be0f0ac0..afdef15e9f 100644 --- a/activemq-cpp/src/test/activemq/connector/stomp/marshal/MarshalerTest.h +++ b/activemq-cpp/src/test/activemq/connector/stomp/marshal/MarshalerTest.h @@ -38,15 +38,17 @@ namespace marshal{ // Sync to expected output connectedCommand.setSessionId( "test" ); + StompTopic myTopic( "a" ); + // Sync to expected output - textCommand.setCMSDestination( StompTopic("a") ); + textCommand.setCMSDestination( &myTopic ); textCommand.setCMSMessageId( "123" ); textCommand.getProperties().setProperty( "sampleProperty", "testvalue" ); textCommand.setText( "testMessage" ); // Sync to expected output - bytesCommand.setCMSDestination( StompTopic("a") ); + bytesCommand.setCMSDestination( &myTopic ); bytesCommand.setCMSMessageId( "123" ); bytesCommand.getProperties().setProperty( "sampleProperty", "testvalue" ); diff --git a/activemq-cpp/src/test/activemq/core/ActiveMQConnectionFactoryTest.h b/activemq-cpp/src/test/activemq/core/ActiveMQConnectionFactoryTest.h index 2f95392c0e..635daf705e 100644 --- a/activemq-cpp/src/test/activemq/core/ActiveMQConnectionFactoryTest.h +++ b/activemq-cpp/src/test/activemq/core/ActiveMQConnectionFactoryTest.h @@ -10,9 +10,11 @@ #include #include #include +#include #include #include #include +#include namespace activemq{ namespace core{ @@ -21,11 +23,20 @@ namespace core{ { CPPUNIT_TEST_SUITE( ActiveMQConnectionFactoryTest ); CPPUNIT_TEST( test ); + CPPUNIT_TEST( test2 ); CPPUNIT_TEST_SUITE_END(); public: - - ActiveMQConnectionFactoryTest() {} + + std::string username; + std::string password; + std::string clientId; + + ActiveMQConnectionFactoryTest(){ + username = "timmy"; + password = "auth"; + clientId = "12345"; + } virtual ~ActiveMQConnectionFactoryTest() {} void test() @@ -38,11 +49,10 @@ namespace core{ std::string URI = "dummy://127.0.0.1:23232&wireFormat=stomp"; - ActiveMQConnectionFactory connectionFactory(URI); + ActiveMQConnectionFactory connectionFactory( URI ); cms::Connection* connection = - - connectionFactory.createConnection(); + connectionFactory.createConnection(); CPPUNIT_ASSERT( connection != NULL ); @@ -56,6 +66,45 @@ namespace core{ CPPUNIT_ASSERT( false ); } + void test2() + { + try + { + transport::TransportFactoryMapRegistrar registrar( + "dummy", new transport::DummyTransportFactory() ); + + std::string URI = std::string() + + "dummy://127.0.0.1:23232&wireFormat=stomp?" + "username=" + username + "?password=" + password + + "?client-id=" + clientId; + + ActiveMQConnectionFactory connectionFactory( URI ); + + cms::Connection* connection = + connectionFactory.createConnection(); + CPPUNIT_ASSERT( connection != NULL ); + + ActiveMQConnection* amqConnection = + dynamic_cast< ActiveMQConnection* >( connection ); + CPPUNIT_ASSERT( amqConnection != NULL ); + + connector::Connector* connector = + dynamic_cast< connector::Connector* >( + amqConnection->getConnectionData()->getConnector() ); + CPPUNIT_ASSERT( connector != NULL ); + + CPPUNIT_ASSERT( username == connector->getUsername() ); + CPPUNIT_ASSERT( password == connector->getPassword() ); + CPPUNIT_ASSERT( clientId == connector->getClientId() ); + + return; + } + AMQ_CATCH_NOTHROW( exceptions::ActiveMQException ) + AMQ_CATCHALL_NOTHROW( ) + + CPPUNIT_ASSERT( false ); + } + }; }} diff --git a/activemq-cpp/src/test/activemq/core/ActiveMQConnectionTest.h b/activemq-cpp/src/test/activemq/core/ActiveMQConnectionTest.h index 073177cdc8..1371f84c0b 100644 --- a/activemq-cpp/src/test/activemq/core/ActiveMQConnectionTest.h +++ b/activemq-cpp/src/test/activemq/core/ActiveMQConnectionTest.h @@ -169,7 +169,7 @@ namespace core{ session.setSessionId( 1 ); session.setConnectionId( "TEST:123" ); - session.setAckMode( cms::Session::AutoAcknowledge ); + session.setAckMode( cms::Session::AUTO_ACKNOWLEDGE ); consumer.setConsumerId( 1 ); consumer.setSessionInfo( &session ); @@ -180,9 +180,8 @@ namespace core{ connector::stomp::commands::TextMessageCommand* cmd = new connector::stomp::commands::TextMessageCommand; - - cmd->setCMSDestination( - connector::stomp::StompTopic( "test" ) ); + connector::stomp::StompTopic topic1( "test" ); + cmd->setCMSDestination( &topic1 ); connector::ConsumerMessageListener* consumerListener = dynamic_cast< connector::ConsumerMessageListener* >( @@ -212,8 +211,8 @@ namespace core{ cmd = new connector::stomp::commands::TextMessageCommand; - cmd->setCMSDestination( - connector::stomp::StompTopic( "test" ) ); + connector::stomp::StompTopic topic2( "test" ); + cmd->setCMSDestination( &topic2 ); consumerListener->onConsumerMessage( &consumer, cmd ); CPPUNIT_ASSERT( msgListener.messages.size() == 1 ); @@ -221,12 +220,20 @@ namespace core{ connection.removeMessageListener( 1 ); msgListener.messages.clear(); + session1->close(); + session2->close(); + session3->close(); connection.close(); consumerListener->onConsumerMessage( &consumer, cmd ); CPPUNIT_ASSERT( exListener.caughtOne == true ); delete cmd; + + delete session1; + delete session2; + delete session3; + } catch(...) { diff --git a/activemq-cpp/src/test/activemq/core/ActiveMQDestinationTest.cpp b/activemq-cpp/src/test/activemq/core/ActiveMQDestinationTest.cpp new file mode 100644 index 0000000000..83bffaedd9 --- /dev/null +++ b/activemq-cpp/src/test/activemq/core/ActiveMQDestinationTest.cpp @@ -0,0 +1,3 @@ +#include "ActiveMQDestinationTest.h" + +CPPUNIT_TEST_SUITE_REGISTRATION( activemq::core::ActiveMQDestinationTest ); diff --git a/activemq-cpp/src/test/activemq/core/ActiveMQDestinationTest.h b/activemq-cpp/src/test/activemq/core/ActiveMQDestinationTest.h new file mode 100644 index 0000000000..6040e6f1e8 --- /dev/null +++ b/activemq-cpp/src/test/activemq/core/ActiveMQDestinationTest.h @@ -0,0 +1,130 @@ +#ifndef ACTIVEMQDESTINATIONTEST_H_ +#define ACTIVEMQDESTINATIONTEST_H_ + +#include +#include + +#include +#include + +namespace activemq{ +namespace core{ + + class ActiveMQDestinationTest : public CppUnit::TestFixture + { + CPPUNIT_TEST_SUITE( ActiveMQDestinationTest ); + CPPUNIT_TEST( test ); + CPPUNIT_TEST_SUITE_END(); + + public: + + class MyDestination : public ActiveMQDestination< cms::Topic > + { + public: + + MyDestination( const cms::Destination* dest ) : + ActiveMQDestination< cms::Topic >( dest ) {} + + MyDestination( const std::string& name ) + : ActiveMQDestination< cms::Topic >( name, cms::Destination::TOPIC ) + {} + + virtual ~MyDestination() {} + + /** + * Converts the Destination Name into a String + * @return string name + */ + virtual std::string toString(void) const { + return getName(); + } + + /** + * Converts the Destination to a String value representing the + * Provider specific name fot this destination, which is not + * necessarily equal to the User Supplied name of the Destination + * @return Provider specific Name + */ + virtual std::string toProviderString(void) const { + return getName(); + } + + /** + * Creates a new instance of this destination type that is a + * copy of this one, and returns it. + * @returns cloned copy of this object + */ + virtual cms::Destination* clone(void) const { + return new MyDestination( this ); + } + + /** + * Gets the name of this topic. + * @return The topic name. + */ + virtual std::string getTopicName(void) + const throw( cms::CMSException ) { return getName(); } + + }; + + ActiveMQDestinationTest() {} + virtual ~ActiveMQDestinationTest() {} + + virtual void test() + { + MyDestination dest( "test" ); + + CPPUNIT_ASSERT( dest.getTopicName() == "test" ); + + MyDestination dest1( "test1?value1=1&value2=2" ); + + CPPUNIT_ASSERT( dest1.getTopicName() == "test1" ); + CPPUNIT_ASSERT( dest1.getProperties().hasProperty( "value1" ) == true ); + CPPUNIT_ASSERT( dest1.getProperties().hasProperty( "value2" ) == true ); + CPPUNIT_ASSERT( dest1.getProperties().hasProperty( "value3" ) != true ); + + std::string value1 = dest1.getProperties().getProperty( "value1" ); + std::string value2 = dest1.getProperties().getProperty( "value2" ); + + CPPUNIT_ASSERT( value1 == "1" ); + CPPUNIT_ASSERT( value2 == "2" ); + + MyDestination* dest2 = + dynamic_cast< MyDestination* >( dest1.clone() ); + + CPPUNIT_ASSERT( dest2 != NULL ); + + CPPUNIT_ASSERT( dest2->getTopicName() == "test1" ); + CPPUNIT_ASSERT( dest2->getProperties().hasProperty( "value1" ) == true ); + CPPUNIT_ASSERT( dest2->getProperties().hasProperty( "value2" ) == true ); + CPPUNIT_ASSERT( dest2->getProperties().hasProperty( "value3" ) != true ); + + value1 = dest2->getProperties().getProperty( "value1" ); + value2 = dest2->getProperties().getProperty( "value2" ); + + CPPUNIT_ASSERT( value1 == "1" ); + CPPUNIT_ASSERT( value2 == "2" ); + + delete dest2; + + MyDestination dest3("dummy"); + dest3.copy( dest1 ); + + CPPUNIT_ASSERT( dest3.getTopicName() == "test1" ); + CPPUNIT_ASSERT( dest3.getProperties().hasProperty( "value1" ) == true ); + CPPUNIT_ASSERT( dest3.getProperties().hasProperty( "value2" ) == true ); + CPPUNIT_ASSERT( dest3.getProperties().hasProperty( "value3" ) != true ); + + value1 = dest3.getProperties().getProperty( "value1" ); + value2 = dest3.getProperties().getProperty( "value2" ); + + CPPUNIT_ASSERT( value1 == "1" ); + CPPUNIT_ASSERT( value2 == "2" ); + + } + + }; + +}} + +#endif /*ACTIVEMQDESTINATIONTEST_H_*/ diff --git a/activemq-cpp/src/test/activemq/core/ActiveMQSessionTest.h b/activemq-cpp/src/test/activemq/core/ActiveMQSessionTest.h index 5cbb4a8b03..e7ab9572d5 100644 --- a/activemq-cpp/src/test/activemq/core/ActiveMQSessionTest.h +++ b/activemq-cpp/src/test/activemq/core/ActiveMQSessionTest.h @@ -112,15 +112,15 @@ namespace core{ messages.clear(); } - virtual void onMessage( const cms::Message& message ) + virtual void onMessage( const cms::Message* message ) { synchronized( &mutex ) { if( ack ){ - message.acknowledge(); + message->acknowledge(); } - messages.push_back( message.clone() ); + messages.push_back( message->clone() ); mutex.notifyAll(); } @@ -186,7 +186,7 @@ namespace core{ // Init Message msg->setText( message.c_str() ); - msg->setCMSDestination( destination ); + msg->setCMSDestination( &destination ); msg->setCMSMessageId( "Id: 123456" ); // Send the Message @@ -219,9 +219,9 @@ namespace core{ // Create a consumer cms::MessageConsumer* consumer1 = - session->createConsumer( *topic1 ); + session->createConsumer( topic1 ); cms::MessageConsumer* consumer2 = - session->createConsumer( *topic2 ); + session->createConsumer( topic2 ); CPPUNIT_ASSERT( consumer1 != NULL ); CPPUNIT_ASSERT( consumer2 != NULL ); @@ -277,6 +277,9 @@ namespace core{ CPPUNIT_ASSERT( text1 == "This is a Test 1" ); CPPUNIT_ASSERT( text2 == "This is a Test 2" ); + delete topic1; + delete topic2; + delete consumer1; delete consumer2; @@ -292,7 +295,7 @@ namespace core{ // Create an Auto Ack Session cms::Session* session = connection->createSession( - cms::Session::ClientAcknowledge ); + cms::Session::CLIENT_ACKNOWLEDGE ); // Create a Topic cms::Topic* topic1 = session->createTopic( "TestTopic1"); @@ -303,9 +306,9 @@ namespace core{ // Create a consumer cms::MessageConsumer* consumer1 = - session->createConsumer( *topic1 ); + session->createConsumer( topic1 ); cms::MessageConsumer* consumer2 = - session->createConsumer( *topic2 ); + session->createConsumer( topic2 ); CPPUNIT_ASSERT( consumer1 != NULL ); CPPUNIT_ASSERT( consumer2 != NULL ); @@ -365,6 +368,9 @@ namespace core{ CPPUNIT_ASSERT( text1 == "This is a Test 1" ); CPPUNIT_ASSERT( text2 == "This is a Test 2" ); + delete topic1; + delete topic2; + delete consumer1; delete consumer2; @@ -380,7 +386,7 @@ namespace core{ // Create an Auto Ack Session cms::Session* session = connection->createSession( - cms::Session::Transactional ); + cms::Session::SESSION_TRANSACTED ); // Create a Topic cms::Topic* topic1 = session->createTopic( "TestTopic1"); @@ -391,9 +397,9 @@ namespace core{ // Create a consumer cms::MessageConsumer* consumer1 = - session->createConsumer( *topic1 ); + session->createConsumer( topic1 ); cms::MessageConsumer* consumer2 = - session->createConsumer( *topic2 ); + session->createConsumer( topic2 ); CPPUNIT_ASSERT( consumer1 != NULL ); CPPUNIT_ASSERT( consumer2 != NULL ); @@ -545,6 +551,9 @@ namespace core{ CPPUNIT_ASSERT( msgListener2.messages.size() == msgCount ); + delete topic1; + delete topic2; + delete consumer1; delete consumer2; diff --git a/activemq-cpp/src/test/activemq/transport/IOTransportTest.h b/activemq-cpp/src/test/activemq/transport/IOTransportTest.h index 44f64f4219..f5b9de8e30 100644 --- a/activemq-cpp/src/test/activemq/transport/IOTransportTest.h +++ b/activemq-cpp/src/test/activemq/transport/IOTransportTest.h @@ -53,6 +53,7 @@ namespace transport{ virtual void onCommand( Command* command ){ const MyCommand* cmd = dynamic_cast(command); str += cmd->c; + delete command; } }; diff --git a/activemq-cpp/todo.txt b/activemq-cpp/todo.txt index 413836745b..76beaf40cb 100644 --- a/activemq-cpp/todo.txt +++ b/activemq-cpp/todo.txt @@ -1,36 +1,39 @@ -Client Side: - -* Work out platform independent build system -* Complete Logging API -* Add Destination URL like parameter processing -* investigate the 999 (1000) messages bug in the broker - - -* integration test against real AMQ broker (DONE) -* finish unit testing of core api (DONE) -* refactoring of core API (DONE) -* Resolve static initialization when used as a library. (DONE) -* Add Message Cloning to the Commands tests. (DONE) -* enforce connected state in stomp connector (DONE) -* Add setting username & password to connect command (DONE) -* Dummy Transport that acts like a broker (DONE) -* Update Session Manager to use Transport not Connector (DONE) -* Add Transport Factory Lookup Method (DONE) -* Connector Interfaces Cleanup (DONE) - -Server Side: - -* Implement Connected as a response (DONE) -* Implement use of JMSType in all messages (DONE) -* Add Content Length to all outgoing messages (DONE) - -Nice to Haves: - -* Add Connection Id support to Stomp Transport on Broker -* Add Consumer Id support to Stomp Transport on Broker -* implement selector algorithm - always pass null selector to broker, - current implementation is limited to using the selector on the - first consumer that is subscribed to a Topic. -* Add Durable Subscriptions to Stomp Connector. (DONE) - - +Client Side: + +* Work out platform independent build system +* Complete Logging API +* Add Destination URL like parameter processing +* investigate the 999 (1000) messages bug in the broker + + +* Make the enumerations have consistant case (DONE) +* Create a DeliveryMode class with enum values (DONE) +* rename Session::Transactional to SESSION_TRANSACTED (DONE) +* integration test against real AMQ broker (DONE) +* finish unit testing of core api (DONE) +* refactoring of core API (DONE) +* Resolve static initialization when used as a library. (DONE) +* Add Message Cloning to the Commands tests. (DONE) +* enforce connected state in stomp connector (DONE) +* Add setting username & password to connect command (DONE) +* Dummy Transport that acts like a broker (DONE) +* Update Session Manager to use Transport not Connector (DONE) +* Add Transport Factory Lookup Method (DONE) +* Connector Interfaces Cleanup (DONE) + +Server Side: + +* Implement Connected as a response (DONE) +* Implement use of JMSType in all messages (DONE) +* Add Content Length to all outgoing messages (DONE) + +Nice to Haves: + +* Add Connection Id support to Stomp Transport on Broker +* Add Consumer Id support to Stomp Transport on Broker +* implement selector algorithm - always pass null selector to broker, + current implementation is limited to using the selector on the + first consumer that is subscribed to a Topic. +* Add Durable Subscriptions to Stomp Connector. (DONE) + + diff --git a/activemq-cpp/unix/pom.xml b/activemq-cpp/unix/pom.xml index ab4e83f37f..c3d5f4202c 100644 --- a/activemq-cpp/unix/pom.xml +++ b/activemq-cpp/unix/pom.xml @@ -53,7 +53,7 @@ - -frtti -pthread -O3 -DNDEBUG -D_REENTRANT + -frtti -O3 -DNDEBUG -D_REENTRANT @@ -68,7 +68,7 @@ - -frtti -g -pthread -DDEBUG -D_DEBUG -D_REENTRANT + -frtti -g -DDEBUG -D_DEBUG -D_REENTRANT diff --git a/activemq-cpp/win32-gcc/pom.xml b/activemq-cpp/win32-gcc/pom.xml index 737e696b8b..8adad7e7dc 100644 --- a/activemq-cpp/win32-gcc/pom.xml +++ b/activemq-cpp/win32-gcc/pom.xml @@ -53,7 +53,7 @@ - -frtti -pthread -O3 -DNDEBUG -D_REENTRANT -D_WIN32 -DWINVER=0x0502 -DWIN32_LEAN_AND_MEAN + -frtti -O3 -DNDEBUG -D_REENTRANT -D_WIN32 -DWINVER=0x0502 -DWIN32_LEAN_AND_MEAN @@ -68,7 +68,7 @@ - -frtti -g -pthread -DDEBUG -D_DEBUG -D_REENTRANT -D_WIN32 -DWINVER=0x0502 -DWIN32_LEAN_AND_MEAN + -frtti -g -DDEBUG -D_DEBUG -D_REENTRANT -D_WIN32 -DWINVER=0x0502 -DWIN32_LEAN_AND_MEAN