Пример #1
0
//send message
void ActiveMqProducer::sendMessage(const std::string& destTopic, const std::string& message)
{
    if(producerMap.find(destTopic) == producerMap.end())
    {
        std::cout << "---------create a new topic-----------" << std::endl;

        Destination* destination = NULL;

        if( m_useTopic )   
        {  
            destination = session->createTopic( destTopic );
        }
        else
        {
            destination = session->createQueue( destTopic );
        }

        destinationVec.push_back(destination);

        MessageProducer* producer = session->createProducer( destination );
        producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );
        producerMap[destTopic] = producer;
    }

    //std::string send_message = destTopic + message;

    std::string threadIdStr = Long::toString( Thread::currentThread()->getId() );
    TextMessage* text = session->createTextMessage(message);
   // std::cout << "Send message from thread: " << threadIdStr << std::endl;
   // std::cout << "send a message: " << send_message << std::endl; // need modify (log file)
    producerMap[destTopic]->send( text );
    delete text;

}
Пример #2
0
/**
 * Send a message over a GOSS channel
 */
void gridpack::goss::GOSSUtils::sendChannelMessage(const char *topic, const char *URI,
    const char *username, const char *passwd, const char *msg)
{
#ifndef GOSS_DEBUG
  Connection *connection;
  Session *session;
  Destination *destination;
  MessageProducer *producer;

  std::string brokerURI = URI;
  std::auto_ptr<ActiveMQConnectionFactory>
    connectionFactory(new ActiveMQConnectionFactory(brokerURI)) ;
  // Create a Connection
  std::string User = username;
  std::string Pass = passwd;
  connection = connectionFactory->createConnection(User, Pass);
  connection->start();
  // Create a Session
  session = connection->createSession(Session::AUTO_ACKNOWLEDGE);
  // Create the destination (Topic or Queue)
  destination = session->createTopic(topic);
  // Create a MessageProducer from the Session to the Topic
  producer = session->createProducer(destination);
  producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);

  std::auto_ptr<TextMessage> message(session->createTextMessage(msg));
  producer->send(message.get());
  // Clean up
  delete connection;
  delete session;
  delete destination;
  delete producer;
#endif
}
Пример #3
0
void ActiveMqProducer::sendMessage(const Destination* destination, const std::string& message, const std::string& correlation_id)
{
	MessageProducer* producer = session->createProducer(destination);
	producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);
	TextMessage* text = session->createTextMessage(message);
	text->setCMSCorrelationID(correlation_id);
	producer->send(text);
}
Пример #4
0
  void setup() {
		try {

			// Create a ConnectionFactory
			auto_ptr<ConnectionFactory> connectionFactory(
				ConnectionFactory::createCMSConnectionFactory(brokerURI));

			// Create a Connection
			connection = connectionFactory->createConnection();
			connection->start();

			// Create a Session
			if (this->sessionTransacted) {
				session = connection->createSession(Session::SESSION_TRANSACTED);
			}
			else {
				session = connection->createSession(Session::AUTO_ACKNOWLEDGE);
			}

			// Create the destination (Topic or Queue)
      destination = session->createQueue("MODALA.RESPONSES");

			// Create a MessageProducer from the Session to the Topic or Queue
			mproducer = session->createProducer(destination);
			mproducer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);
    } catch (CMSException& e) {
			e.printStackTrace();
		}
  }
Пример #5
0
    virtual void run() {

        try {

            // Create a ConnectionFactory
            auto_ptr<ConnectionFactory> connectionFactory(
                ConnectionFactory::createCMSConnectionFactory(brokerURI));

            // Create a Connection
            connection = connectionFactory->createConnection();
            connection->start();

            // Create a Session
            if (this->sessionTransacted) {
                session = connection->createSession(Session::SESSION_TRANSACTED);
            } else {
                session = connection->createSession(Session::AUTO_ACKNOWLEDGE);
            }

            // Create the destination (Topic or Queue)
            if (useTopic) {
                destination = session->createTopic("TEST.FOO");
            } else {
                destination = session->createQueue("TEST.FOO");
            }

            // Create a MessageProducer from the Session to the Topic or Queue
            producer = session->createProducer(destination);
            producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);

            // Create the Thread Id String
            string threadIdStr = Long::toString(Thread::currentThread()->getId());

            // Create a messages
            string text = (string) "Hello world! from thread " + threadIdStr;

            for (int ix = 0; ix < numMessages; ++ix) {
                std::auto_ptr<TextMessage> message(session->createTextMessage(text));
                message->setIntProperty("Integer", ix);
                printf("Sent message #%d from thread %s\n", ix + 1, threadIdStr.c_str());
                producer->send(message.get());
            }

        } catch (CMSException& e) {
            e.printStackTrace();
        }
    }
Пример #6
0
  void send(const std::string& text) {
    try {
      std::auto_ptr<TextMessage> message(session->createTextMessage(text));
      mproducer->send(message.get());
    }	catch (CMSException& e) {
			e.printStackTrace();
		}
  }
void ServiceHandlerI::run() 
{
	Destination replyto;
	try
	{
		replyto = textmessage->getJMSReplyTo();
		if (!replyto)
		{
			serviceimplementor->doService(textmessage->getText());
		}
		else
		{
			if (logger->isLoggable(Level::FINEST)) logger->log(Level::FINEST, L"ServiceHandlerI::run() text: " + textmessage->getText());
			String replytext = serviceimplementor->doService(textmessage->getText());
			if (logger->isLoggable(Level::FINEST)) logger->log(Level::FINEST, L"ServiceHandlerI::run() replytext: " + replytext);
			TextMessage reply = queuesession->createTextMessage(replytext);

			Iterator<MapEntry<String, Anything> > i = serviceimplementor->getOutParameters()->entrySet()->iterator();
			while (i->hasNext())
			{
				MapEntry<String, Anything> current = i->next();
				reply->setStringProperty(current->key, current->value);
			}

			MessageProducer sender = queuesession->createProducer(replyto);
			sender->send(reply);
		}
	}
	catch (const Exception& e)
	{
		logger->log(Level::SEVERE, e->toString());
		if (!!replyto)
		{
			try
			{
				MessageProducer sender = queuesession->createProducer(replyto);
				sender->send(queuesession->createTextMessage(e->toString()));
			}
			catch (const Exception& e)
			{
				logger->log(Level::SEVERE, e->toString());
			}
		}
	}
}
Пример #8
0
    virtual void run()
    {

        try {
            // Create a ConnectionFactory
            auto_ptr<ConnectionFactory> connectionFactory(
                ConnectionFactory::createCMSConnectionFactory( (const char*)brokerURI ) );

            // Create a Connection
            connection = connectionFactory->createConnection();
            connection->start();

            // Create a Session
            if( this->sessionTransacted ) {
                session = connection->createSession( Session::SESSION_TRANSACTED );
            } else {
                session = connection->createSession( Session::AUTO_ACKNOWLEDGE );
            }

            destination = session->createQueue((const char*)queue);
            //destination = session->createQueue("/asev/queue");
            // Create a MessageProducer from the Session to the Topic or Queue
            producer = session->createProducer( destination );
            producer->setDeliveryMode( DeliveryMode::PERSISTENT );

            //cout<<"message:"<<message<<"\n";

			TextMessage* sendmessage = session->createTextMessage( (char*)message );

			//cout<<"producer:"<<sendmessage->getText()<<"\n";
			// Tell the producer to send the message
			//printf( "Sent message #%d from thread %s\n", ix+1, threadIdStr.c_str() );
			producer->send( sendmessage );

			if(this->sessionTransacted)
				session->commit();

			delete sendmessage;


        }catch ( CMSException& e ) {
            e.printStackTrace();
        }
    }
Пример #9
0
/**
 * Shut down GOSS communication
 */
void gridpack::goss::GOSSUtils::terminateGOSS()
{
  if (GA_Nodeid()==0) {
    char topic[128];

#ifndef GOSS_DEBUG
    Connection *connection;
    Session *session;
    Destination *destination;
    MessageProducer *producer;


    std::auto_ptr<ActiveMQConnectionFactory>
      connectionFactory(new ActiveMQConnectionFactory(p_URI)) ;
    // Create a Connection
    connection = connectionFactory->createConnection(p_username, p_passwd);
    connection->start();

    // Create a Session
    session = connection->createSession(Session::AUTO_ACKNOWLEDGE);

    // Create the destination (Topic or Queue)
    sprintf(topic,"topic/goss/gridpack/close_goss");
    destination = session->createTopic(topic);

    // Create a MessageProducer from the Session to the Topic
    producer = session->createProducer(destination);
    producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);

    // Send final message indicating that channel is being close
    std::string buf = "Closing GOSS";
    std::auto_ptr<TextMessage>
      end_message(session->createTextMessage(buf));
    producer->send(end_message.get());
    if (connection) delete connection;
    if (session) delete session;
    if (destination) delete destination;
    if (producer) delete producer;
#endif
  }
}
    // Called from the consumer since this class is a registered MessageListener.
    virtual void
      onMessage (const Message * message)
      throw ()
      {

        static int
          count = 0;

        try
        {
          count++;
          const TextMessage *
            textMessage = dynamic_cast < const
            TextMessage * >(message);

          const BytesMessage *
            bytesMessage = dynamic_cast < const
            BytesMessage * >(message);

          string text = "";

          if (bytesMessage != NULL)
          {
            //std::cout << bytesMessage->getBodyBytes();
            //bytesMessage->reset();

            size_t i = bytesMessage->getBodyLength ();
            printf ("%lu", i);
            ofstream ofs ("message.yaml", ofstream::out);
            for (int x = 1; x <= i; x++)
            {
              ofs << bytesMessage->readByte ();
            }
            ofs.flush ();
            ofs.close ();

            try
            {
              std::ifstream fin ("message.yaml");
              //std::stringstream fin(std::string(bytesMessage->getBodyBytes()));
              YAML::Parser parser (fin);
              YAML::Node doc;
              // We assume only the first doc, need to check with doc.size
              parser.GetNextDocument (doc);

              /*
Key: :agent
Key: :body
Key: :callerid
Key: :collectiv
Key: :filter
Key: :hash
Key: :msgtarget
Key: :msgtime
Key: :requestid
Key: :senderid
*/
              for (YAML::Iterator it = doc.begin (); it != doc.end (); ++it)
              {
                std::string key, value;
                it.first () >> key;
                std::cout << "Key: " << key << std::endl;
              }

              std::string requestid;
              std::string senderid;
              std::string msgtarget;
              doc[":msgtarget"] >> msgtarget;
              doc[":requestid"] >> requestid;
              doc[":senderid"] >> senderid;
              std::cout << msgtarget << std::endl << requestid << std::
                endl << senderid << std::endl;

              // Body seems to be multiline string of yaml
              // Parsing strings http://stackoverflow.com/questions/2813030/yaml-cpp-parsing-strings
              std::string body;
              doc[":body"] >> body;

              std::stringstream bodystream (body);
              YAML::Parser bodyparser (bodystream);
              YAML::Node bodydoc;
              std::string action;
              bodyparser.GetNextDocument (bodydoc);
              bodydoc >> action;
              std::cout << action;


              // Construct YAML body
              YAML::Emitter reply_message_body_yaml;
              reply_message_body_yaml << "pong";

              // Put it in a string
              std::string reply_message_body = reply_message_body_yaml.c_str();
              std::cout << reply_message_body << std::endl;
              // Append PSK to it
              std::string psk = "unset";
              std::string body_psk = reply_message_body;
              body_psk.append(psk);

              std::stringstream md5sumstream;
              // MD5 -  https://gist.github.com/2389719
              // but needs a real string
              // http://social.msdn.microsoft.com/Forums/en/Vsexpressvc/thread/e1774395-ba99-4fe6-98eb-2224a67984b9
              unsigned char md5_result[MD5_DIGEST_LENGTH];
              const unsigned char * constStr = reinterpret_cast<const unsigned char *> (body_psk.c_str());
              MD5(constStr, body_psk.length() , md5_result);
              for (i=0; i < MD5_DIGEST_LENGTH; i++)
              {
                printf("%02x",  md5_result[i]);
                char digit[2];
                sprintf(digit,"%02x",  md5_result[i]);
                md5sumstream << digit;
              }
              printf("\n");

              std::cout << "md5 stream:" << md5sumstream.str() << std::endl;
              std::string hash = md5sumstream.str();
              std::cout << "hash:" << hash << std::endl;

              YAML::Emitter reply_message_yaml;

              reply_message_yaml << YAML::BeginMap;
              reply_message_yaml << YAML::Key << ":msgtime";
              reply_message_yaml << YAML::Value << 1010101;
              reply_message_yaml << YAML::Key << ":requestid";
              reply_message_yaml << YAML::Value << requestid;
              reply_message_yaml << YAML::Key << ":body";
              reply_message_yaml << YAML::Value << reply_message_body;
              reply_message_yaml << YAML::Key << ":senderid";
              reply_message_yaml << YAML::Value << "mcpp";
              reply_message_yaml << YAML::Key << ":senderagent";
              reply_message_yaml << YAML::Value << "discovery";
              reply_message_yaml << YAML::Key << ":msgtarget";
              reply_message_yaml << YAML::Value << "/topic/mcollective.discovery.reply";

              reply_message_yaml << YAML::Key << ":hash";
              reply_message_yaml << YAML::Value << hash;
              reply_message_yaml << YAML::EndMap;


              // Put it in a string
              std::string reply_message = reply_message_yaml.c_str();
              std::cout << reply_message << std::endl;


              // Get ready to send
              try {

                Connection* connection;
                Session* session;
                Destination* destination;
                MessageProducer* producer;
                // Create a ConnectionFactory
                std::string brokerURI = "tcp://127.0.0.1:6163" "?wireFormat=stomp";

                auto_ptr<ConnectionFactory> connectionFactory(
                    ConnectionFactory::createCMSConnectionFactory( brokerURI ) );

                // Create a Connection
                connection = connectionFactory->createConnection ("mcollective", "marionette");
                connection->start();

                // Create a Session
                session = connection->createSession( Session::AUTO_ACKNOWLEDGE );
                // Create the destination (Topic or Queue)
                destination = session->createTopic( "mcollective.discovery.reply" );

                // Create a MessageProducer from the Session to the Topic or Queue
                producer = session->createProducer( destination );
                producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

                // Create a messages
                BytesMessage* reply = session->createBytesMessage();

                reply->writeString(reply_message.c_str());
                producer->send( reply );
                printf("reply send \n");

                delete reply;

              }catch ( CMSException& e ) {
                e.printStackTrace();
              }


            }
            catch (YAML::ParserException & e)
            {
              std::cout << e.what () << "\n";
            }
          }

          if (textMessage != NULL)
          {
            text = textMessage->getText ();
          }
          else
          {
            text = "NOT A TEXTMESSAGE!";
            //std::cout << message->getCMSType();
            std::vector < string > v = message->getPropertyNames ();
            for (std::vector < string >::iterator it = v.begin ();
                it != v.end (); ++it)
            {
              std::cout << *it << std::endl;
            }
          }
          printf ("Message #%d Received: %s\n", count, text.c_str ());




        }
Пример #11
0
/**
 * Initialize goss bus specifying all topics that will be used in this
 * application. This must be called on the world communicator.
 * @param topics list of topics that will be sent by the application
 * @param URI channel URI
 * @param username server username
 * @param passwd server password
 */
void gridpack::goss::GOSSUtils::initGOSS(std::vector<std::string> &topics,
    const char *URI, const char* username, const char *passwd)
{
  char sbuf[128];
  int nvals = topics.size();
  int i;
  // Store channel parameters
  p_URI = URI;
  p_username = username;
  p_passwd = passwd;

  // Concatenate topics into a single string
  if (topics.size() == 0) {
    printf("No topics provided when initializing GOSSUtils\n");
  }
  std::string list = topics[0];
  if (nvals > 0) {
    list = topics[0];
    for (i=1; i<nvals; i++) {
      sprintf(sbuf," %s",topics[i].c_str());
      list.append(sbuf);
    }
  }

  // Send string using topic "topic/goss/gridpack"
  if (GA_Nodeid()==0) {
    char topic[128];

#ifndef GOSS_DEBUG
    Connection *connection;
    Session *session;
    Destination *destination;
    MessageProducer *producer;


    std::auto_ptr<ActiveMQConnectionFactory>
      connectionFactory(new ActiveMQConnectionFactory(p_URI)) ;
    // Create a Connection
    connection = connectionFactory->createConnection(p_username, p_passwd);
    connection->start();

    // Create a Session
    session = connection->createSession(Session::AUTO_ACKNOWLEDGE);
#endif

    // Create the destination (Topic or Queue)
    sprintf(topic,"topic/goss/gridpack/topic_list");
    //destination = session->createQueue(topic);
    printf("topic = %s\n", topic);
#ifndef GOSS_DEBUG
    destination = session->createTopic(topic);

    // Create a MessageProducer from the Session to the Topic
    producer = session->createProducer(destination);
    producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);

    // Send topics
    std::auto_ptr<TextMessage> message_dat(
        session->createTextMessage(list));
#endif
    printf("list: %s\n", list.c_str());
#ifndef GOSS_DEBUG
    producer->send(message_dat.get());
#endif
    // Close data connection
    // Send final message indicating that channel is being close
    std::string buf = "Closing channel";
#ifndef GOSS_DEBUG
    std::auto_ptr<TextMessage>
      end_message(session->createTextMessage(buf));
    producer->send(end_message.get());
    std::string acknowledge_topic("topic.goss.gridpack.acknowledge");
    std::auto_ptr<Destination> dest(session->createTopic(acknowledge_topic));
    std::auto_ptr<MessageConsumer> consumer(session->createConsumer(dest.get()));
    std::cout << "Waiting for messages..."<<std::endl;

    std::auto_ptr<Message> message(consumer->receive());
    const TextMessage *txtMsg = dynamic_cast<const TextMessage*>(message.get());
    if (txtMsg->getText() != "success") {
      std::cout << "Message failure: "<<txtMsg->getText()<<std::endl;
    }

    if (connection) delete connection;
    if (session) delete session;
    if (destination) delete destination;
    if (producer) delete producer;
#endif
  }
  gridpack::parallel::Communicator world;
  world.barrier();
}