Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This article describes the implementation for sending messages to a Java Message Queue Service which:

  • send sends and receive receives messages,
  • add adds an order to a JS7 workflow by a JS7 - REST Web Service API call with a JSON body extracted from a message.

...

The implementation includes the following steps:

  • create creation of a message producer to send messages to a Message Queue Service,
  • create creation of a message consumer to receive messages from a Message Queue Service,
  • use using the message as part of a JS7 REST Web Service API call.

The message is assumed to be a JSON snippet that which is processed by the desired JS7 REST Web Service API. This snippet must be valid JSON and compliant with requests explained with in the Technical Documentation of the REST Web Service API article.

...

A zip file of this example as a complete maven project implementation is available for download: js7-jms-example-js7-project.zip.

Prerequisites

...

  1. create a connection,
  2. create a session,
  3. create a destination,
  4. create a producer,
  5. send a message with the producer,
  6. close the connection.

Methods

The steps are divided into different methods to make the implementation more readable and reusable. 

createConnection(String url)

This method instantiates a ConnectionFactory object with an ActiveMQConnectionFactory object and creates a Connection object through the factory method createConnection().

...

write(String text)

The method is called with the message to be sent to the server. The message is a String object. The method instantiates a Message object with the text to be sent.

Code Block
languagejava
titlewrite(String text
Code Block
languagejava
titlecreateConnection(String url)
linenumberstrue
collapsetrue
    public Connectionvoid createConnectionwrite(String text, String queueName, long urittl) throws Exception {
       ConnectionFactory Connection factoryconnection = new ActiveMQConnectionFactory(uri)null;
     Connection connection   Session session = null;
        try {
         connection   ConnectionFactory factory = new factory.createConnectionActiveMQConnectionFactory(uri);
    } catch (JMSException e) {
     connection =  LOGGERfactory.error("JMSException occurred while trying to connect: " , e);
createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
         }
   Destination destination return connection;
}

createSession(Connection connection)

...

Code Block
languagejava
titlecreateSession(Connection connection)
linenumberstrue
collapsetrue
private Session createSession(Connection connection){
    Session session = null;
    try {
= session.createQueue(queueName);
            MessageProducer producer = session.createProducer(destination);
            // 5 sec time to live for the producer for this showcase
          session = connectionproducer.createSession(false, Session.AUTO_ACKNOWLEDGEsetTimeToLive(ttl);
     } catch (JMSException e)       Message message = null;
            if(text != null){
        LOGGER.error("JMSException occurred while trying to create Session: " , e);
        message = session.createTextMessage(text);
            } else{
      return          message = session;
}

createDestination(Session session, String queueName)

...

Code Block
languagejava
titlecreateDestination(Session session)
linenumberstrue
collapsetrue
public Destination createDestination(Session session, String queueName){
    Destination destination = null;
    try {
        destination = session.createQueue(queueName);
    } catch (JMSException.createTextMessage(TEXT);
            }
            producer.send(message);
        } catch (Throwable e) {
            LOGGER.error("JMSException occurred while trying to createwrite Message to Destination: " ,);
            throw e);
        } finally {
    return destination;
}

createMessageProducer(Session session, Destination destination)

...

Code Block
languagejava
titlecreateProducer(Session session, Destination destination)
linenumberstrue
collapsetrue
private MessageProducer createMessageProducer(Session session, Destination destination)        if(session != null) {
                try {
    MessageProducer producer = null;
    try {
        producer = session.createProducerclose(destination);
                } catch (JMSException e) {
        LOGGER.error("JMSException             LOGGER.warn("JMSException occurred while trying to close createthe MessageProducersession: " , e);
                }
            }
            return producer;
}

write(String text, MessageProducer producer)

...

Code Block
languagejava
titlewrite(String text)
linenumberstrue
collapsetrue
public void write(String text, MessageProducer producer)if (connection != null) {
                try {
    Message message = null;
    try {
        if(text != null){connection.close();
            message = session.createTextMessage(text);
  } catch (JMSException e) {
   }   else{
            message = sessionLOGGER.createTextMessage(DEFAULT_TEXT);
        }warn("JMSException occurred while trying to close the connection: ", e);
        producer.send(message);
    } catch (JMSException e) {}
        LOGGER.error("JMSException occurred while trying to write Message to Destination: " , e);    }
        }
    }
}

close()

The SOSProducer class

The code example below shows the complete class. The code creates a TEXT message consisting of the body for a JS7 /orders/add API requestThis method makes sure that the connection will be closed after a message has been sent.

Code Block
languagejava
titleclose()SOSProducer.java
linenumberstrue
collapsetrue
private void close(Connection connection){
    if (connection != null) {
        try {package com.sos.jms.producer;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.Logger;


public class SOSProducer {

    private static final Logger LOGGER =   connectionLogger.closegetLogger(SOSProducer.class);
    private static final String }TEXT catch (JMSException e) {
            LOGGER.error("JMSException occurred while trying to close the connection: " , e);
        }
    }
}

The SOSProducer class

The below code example slightly differs from the above examples . In the below class the write(String text) method already uses the other methods for instantiation, therefore it requires fewer parameters and it closes the connection.

...

Code Block
languagejava
titleSOSProducer.java
linenumberstrue
collapsetrue
package com.sos.jms.producer;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.Logger;


public class SOSProducer {

    private static final Logger LOGGER = Logger.getLogger(SOSProducer.class);
    private static final String QUEUE_NAME = "test_queue";
    private static final String TEXT = "{\"controllerId\":\"testsuite\",\"orders\":[{\"workflowPath\":\"/JS7Demo/01_HelloWorld/jdHelloWorld\",\"scheduledFor\":\"now\"}],\"auditLog\":{}}";
    private String uri;
    
    public SOSProducer(String uri) {= "{\"controllerId\":\"testsuite\",\"orders\":[{\"workflowPath\":\"/JS7Demo/01_HelloWorld/jdHelloWorld\",\"scheduledFor\":\"now\"}],\"auditLog\":{}}";
    private String uri;
    
    public SOSProducer(String uri) {
        this.uri = uri;
    }
    
    public void write(String text, String queueName) throws Exception {
        write(text, queueName, 5000L);
    }
    
    public void write(String text, String queueName, long ttl) throws Exception {
        Connection connection = null;
        Session session = null;
        try {
            ConnectionFactory factory = new ActiveMQConnectionFactory(uri);
        this.uri = uri;
  connection  }= factory.createConnection();
    
        privatesession Connection= createConnection(){
connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            ConnectionFactoryDestination factorydestination = new ActiveMQConnectionFactory(urisession.createQueue(queueName);
            ConnectionMessageProducer connectionproducer = nullsession.createProducer(destination);
        try {
   // 5 sec time to live for the producer connectionfor = factory.createConnection();
this showcase
          } catch (JMSException e) {producer.setTimeToLive(ttl);
            LOGGER.error("JMSException occurred while trying to connect: " , e)Message message = null;
        }
    if(text != null){
   return connection;
    }
    
    privatemessage Session= createSession(Connection connection){session.createTextMessage(text);
        Session session = null;
 } else{
      try {
          message = session = connection.createSession(false, Session.AUTO_ACKNOWLEDGEcreateTextMessage(TEXT);
        } catch (JMSException e) {}
            LOGGER.producer.send(message);
        } catch (Throwable e) {
            LOGGER.error("JMSException occurred while trying to write Message createto SessionDestination: " , e);
        }
    throw e;
   return session;
    } finally {
     
     private Destination createDestination(Session session){
if(session != null) {
           Destination destination = null;
  try {
     try {
            destination = session.createQueueclose(QUEUE_NAME);
                } catch (JMSException e) {
                    LOGGER.errorwarn("JMSException occurred while trying to close createthe Destinationsession: " , e);
                }
        return destination;
    }
      
     private MessageProducerif createMessageProducer(Sessionconnection session, Destination destination)!= null) {
        MessageProducer    producer = null;
  try {
     try {
            producer = sessionconnection.createProducerclose(destination);
                } catch (JMSException e) {
            LOGGER.error("JMSException occurred        LOGGER.warn("JMSException occurred while trying to close createthe MessageProducerconnection: " , e);
        }        }
        return producer;
    }
    
    public void write(String text){}
       }
 Connection connection = createConnection();
        Session session = createSession(connection);
        Destination destination = createDestination(session);
        MessageProducer producer = createMessageProducer(session, destination);
        Message message = null;
        try {
            if(text != null){
                message = session.createTextMessage(text);
}

The MessageConsumer

This section describes how to establish a connection to a Message Queue Service and receive a message from a queue. Furthermore it shows how to connect to a JOC Cockpit instance via HTTP to send an API request:

  1. create a connection,
  2. create a session,
  3. create a destination.
  4. create a consumer,
  5. receive a message with the consumer,
  6. close the (MQ) connection,
  7. login to a JOC Cockpit instance via a HTTP REST API call,
  8. send a ./orders/add API request to a JOC Cockpit instance,
  9. close the connection.

Methods

read()

The method instantiates a MessageConsumer object to receive a message from the Message Queue Service. It extracts the value from the Message object as a string representation via the Message objects getText() method. 

Code Block
languagejava
titleread()
linenumberstrue
collapsetrue
    public String read(String queueName) throws Exception {
        TextMessage message = null;
   } else{
    String textMessage = null;
        Connection messageconnection = session.createTextMessage(TEXT)null;
        Session session =  }
null;
        try {
      producer.send(message);
      ConnectionFactory factory }= catchnew ActiveMQConnectionFactory(JMSException e) {
uri);
            connection = LOGGERfactory.error("JMSException occurred while trying to write Message to Destination: " , ecreateConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        }  finally {
 Destination destination = session.createQueue(queueName);
        if (connection != null) { connection.start();
            MessageConsumer consumer =  trysession.createConsumer(destination);
            while (true) {
                Message receivedMessage =  connectionconsumer.closereceive(1);
                }if catch (JMSException e(receivedMessage != null) {
                    LOGGER.error("JMSException occurred while trying to close the connection: " , e);
if (receivedMessage instanceof TextMessage) {
                       }
 message = (TextMessage) receivedMessage;
        }
        }
    }
    
}

The MessageConsumer

This section describes how to establish a connection to a MQ server and receive a message from a queue on this server. Furthermore it describes how to establish  a TCP socket connection to send the received message to a JOC Cockpit instance:

  1. create a connection,
  2. create a session,
  3. create a destination.
  4. create a consumer,
  5. receive a message with the consumer,
  6. close the (MQ) connection,
  7. open a TCP connection to a JOC Cockpit instance,
  8. send the Message to a JOC Cockpit instance,
  9. close the TCP connection.

This section shows examples for the last five steps as the first four are similar to the examples explained above for the instantiation of the MessageProducer.

Methods

createMessageConsumer(Session session, Destination destination)

...

Code Block
languagejava
titlecreateMessageConsumer(Session session, Destination destination)
linenumberstrue
collapsetrue
private MessageConsumer createMessageConsumer(Session session, Destination destination) {
    MessageConsumer consumer = null;
    try {
        consumer = session.createConsumer(destination);
    } catch (JMSException e) {
textMessage = message.getText();
                        LOGGER.info("Reading message: " + textMessage);
                        break;
                    }  LOGGER.error("JMSException occurred while trying to create MessageConsumer: ", e);
    }
    return consumer;
}

read(MessageConsumer consumer)

...

Code Block
languagejava
titleread()
linenumberstrue
collapsetrue
private String read(MessageConsumer consumer)else {
                        break;
                    }
                }
            }
        } catch (Throwable e) {
    TextMessage message = null;
    String textMessage = null;
    try { LOGGER.error("JMSException occurred while trying to read from Destination: ");
        while (true) {
  throw e;
        } Message receivedMessage = consumer.receive(1);finally {
            if (receivedMessagesession != null) {
                if (receivedMessage instanceof TextMessage)try {
                    message = (TextMessage) receivedMessagesession.close();
                } catch (JMSException  textMessage = message.getText();e) {
                    LOGGER.infowarn("Reading messageJMSException occurred while trying to close the session: ", + textMessagee);
                }
    break;
        }
         } else {
 if (connection != null) {
               break;
 try {
              }
        connection.close();
    }
        }
    } catch (JMSException e) {
                    LOGGER.errorwarn("JMSException occurred while trying to readclose fromthe Destinationconnection: ", e);
                }
     return textMessage;
}
Note

 Don´t forget to clean up (call close()) after the message has been received.

receiveFromQueue()

       }
         }
        return textMessage;
    }

The SOSConsumer class

The code example below shows the complete class. The receiveFromQueue() method uses the methods described above to connect to a JOC Cockpit instance, read from a message queue, send the received message to the JOC Cockpit instance and close the session in the JOC Cockpit instance.

Code Block
languagejava
titlereceiveFromQueue()SOSConsumer
linenumberstrue
collapsetrue
public String receiveFromQueue() {
    String message = null;
    try {
        connect();
        message = read();
        sendRequest(message);
        disconnect();
    } catch (Exception e) {
        LOGGER.error("Error occurred while publishing to the JOC Cockpit instance host:" + HOST + ", port:" + PORT, e);
    }
    return message;
}

The SOSConsumer class

...

Code Block
languagejava
titleSOSConsumer
linenumberstrue
collapsetrue
package com.sos.jms.consumer;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SOSConsumer {

    private static final Logger LOGGER = LoggerFactory.getLogger(SOSConsumer.class);
    private static final String DEFAULT_QUEUE_NAME = "test_queue";
    private String uri;
    
    public SOSConsumer (String uri) {
package com.sos.jms.consumer;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SOSConsumer {

    private static final Logger LOGGER = LoggerFactory.getLogger(SOSConsumer.class);
    private String uri;
    
    public SOSConsumer (String uri) {
        this.uri = uri;
    }
    
    public String read(String queueName) throws Exception {
        TextMessage message = null;
        String textMessage = null;
        Connection connection = null;
        Session session = null;
        try {
            ConnectionFactory factory = new ActiveMQConnectionFactory(uri);
            connection = factory.createConnection();
            this.urisession = uri connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    }
    
    privateDestination destination Connection= createConnectionsession.createQueue(queueName) {;
        ConnectionFactory factory = new ActiveMQConnectionFactoryconnection.start(uri);
        Connection connection = null;
   MessageConsumer consumer    try {= session.createConsumer(destination);
            connectionwhile = factory.createConnection(true); {
        } catch (JMSException e) {
    Message receivedMessage = consumer.receive(1);
     LOGGER.error("JMSException occurred while trying to connect: ", e);
    if (receivedMessage != null) }{
          return connection;
    }

    private Sessionif createSession(ConnectionreceivedMessage instanceof connectionTextMessage) {
        Session session = null;
        try {
     message = (TextMessage) receivedMessage;
    session                    textMessage = connectionmessage.createSession(false, Session.AUTO_ACKNOWLEDGEgetText();
        } catch (JMSException e) {
            LOGGER.errorinfo("JMSException occurred while trying to create Session: ", e);
Reading message: " + textMessage);
               }
        return sessionbreak;
    }

    private Destination createDestination(Session session) {
        return this.createDestination(session, DEFAULT_QUEUE_NAME);} else {
    }

              private Destination createDestination(Session session, String queueName) {
break;
                 Destination destination = null;}
        try {
        }
          destination = session.createQueue(queueName); }
        } catch (JMSExceptionThrowable e) {
            LOGGER.error("JMSException occurred while trying to createread from Destination: ", e);
        }
    throw e;
   return destination;
    }
 finally {
    private MessageConsumer createMessageConsumer(Session session, Destination destination       if(session != null) {
        MessageConsumer consumer = null;
     try {
  try    {
            consumer = session.createConsumerclose(destination);
                } catch (JMSException e) {
                    LOGGER.errorwarn("JMSException occurred while trying to createclose the MessageConsumersession: ", e);
        }
        return}
 consumer;
    }

    private String read() {}
           TextMessage if message(connection != null;) {
         String  textMessage = null;

    try {
        Connection connection = createConnection();
        try { connection.close();
            Session    session} =catch createSession(connection);JMSException e) {
            Destination destination = createDestination(session);
     LOGGER.warn("JMSException occurred while trying to close the connection.start(: ", e);
            MessageConsumer consumer = createMessageConsumer(session, destination); }
            while}
 (true) {
       }
        return MessagetextMessage;
 receivedMessage = consumer.receive(1);
                if (receivedMessage != null) {
                    if (receivedMessage instanceof TextMessage) {
                        message = (TextMessage) receivedMessage;
                        textMessage = message.getText();
                        LOGGER.info("Reading message: " + textMessage);
                        break;
                    } else {  }

}

Java Class with a main(String[] args) method (example JmsExecute.java)

The Java class makes use of the SOSProducer to create a message and send it to the message queue. It then uses the SOSConsumer class to read the message from the queue. In addition, it creates an HTTP connection to a JS7 JOC Cockpit instance to call the /orders/add API with the JSON body from the message received.

The example class uses the SOSRestApiClient to create the HTTP connection. The SOSRestApiClient is based on the org.apache.httpcomponents::httpclient. Users can use their own HTTP client implementation. 

Code Block
languagejava
titleJmsExecute.java
collapsetrue
package com.sos.jms;

import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Properties;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sos.commons.httpclient.SOSRestApiClient;
import com.sos.jms.consumer.SOSConsumer;
import com.sos.jms.producer.SOSProducer;

public class JmsExecute {

    private static final String DEFAULT_JMS_URI = "tcp://activemq-5-15:61616";
    private static final String DEFAULT_JOC_API_URL = "http://centostest_primary.sos:7446/joc/api/";
    private static final String DEFAULT_JOC_API_REQUEST_BODY = "{\"controllerId\":\"testsuite\",\"orders\""
            + ":[{\"workflowPath\":\"/JS7Demo/01_HelloWorld/jdHelloWorld\",\"scheduledFor\":\"now\"}],\"auditLog\":{}}";
    private static final String DEFAULT_USERNAME =  break"root";
    private static final String DEFAULT_PWD = "root";
          }
      private static final String DEFAULT_QUEUE_NAME = "test_queue";
    private static final String API_ADD_ORDER  }= "orders/add";
    private static final String API_LOGIN    }= "authentication/login";
    private static final String }API_LOGOUT catch (JMSException e) {= "authentication/logout";
    private static final String ACCESS_TOKEN_HEADER = "X-Access-Token";
  LOGGER.error("JMSException occurred whileprivate tryingstatic tofinal readString from Destination: ", e)APPLICATION_JSON = "application/json";
    private static final String }CONTENT_TYPE finally {
      = "Content-Type";
    private static final Logger LOGGER = LoggerFactory.getLogger(JmsExecute.class);
    private static ifString (connectionjmsServerUri != null) {;
    private static String jocApiUri = null;
    private static String controllerId try= {null;
    private static String workflowPath =  null;
    private static String requestBody   connection.close()= null;
    private static String username = null;
    private static String } catch (JMSException e) {
      pwd = null;
    private static String queueName = null;
    private static Long queueTtl = null;

     LOGGER.error("JMSException occurred while trying to close the connection: " , e);
public static void main(String[] args) throws URISyntaxException {
        SOSRestApiClient client = null;
        try }{
            }
URL classUrl = JmsExecute.class.getProtectionDomain().getCodeSource().getLocation();
      }
      Path classPath return textMessage= Paths.get(classUrl.toURI());
      }

     public String receiveFromQueue() { filename = classPath.getFileName().toString().replace(".jar", ".config");
        return read();
    }

}

Java Class with a main(String[] args) method (example JmsExecute.java)

The Java class makes use of the SOSProducer to create a message and send it to the message queue. It uses the SOSConsumer class to read the message from the queue. Additionally it creates an HTTP connection to a JS7 JOC Cockpit instance to call the /orders/add API with the JSON body from the message received.

...

Code Block
languagejava
collapsetrue
package com.sos.jms;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Properties;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sos.commons.httpclient.SOSRestApiClient;
import com.sos.jms.consumer.SOSConsumer;
import com.sos.jms.producer.SOSProducer;

public class JmsExecute {

    private static final String DEFAULT_JMS_URI = "tcp://activemq-5-15:61616";
    private static final String DEFAULT_JOC_API_URL = "http://centostest_primary.sos:7446/joc/api/";
    private static final String DEFAULT_JOC_API_REQUEST_BODY = "{\"controllerId\":\"testsuite\",\"orders\"" 
            + ":[{\"workflowPath\":\"/JS7Demo/01_HelloWorld/jdHelloWorld\",\"scheduledFor\":\"now\"}],\"auditLog\":{}}";
    private static final String DEFAULT_USERNAME = "root";
    private static final String DEFAULT_PWD = "root";
    private static final String API_ADD_ORDER = "orders/add";
    private static final String API_LOGIN = "authentication/login";
    private static final String API_LOGOUT = "authentication/logout";
    private static final String ACCESS_TOKEN_HEADER = "X-Access-Token";
    private static final String APPLICATION_JSON = "application/json";
    private static final String CONTENT_TYPE = "Content-Type";
    private static final Logger LOGGER = LoggerFactory.getLogger(JmsExecute.class);
    private static String jmsServerUri = null;
    private static String jocApiUri = null;
    private static String controllerId = null;
    private static String workflowPath = null;
    private static String requestBody = null;
    private static String username = null;
    private static String pwd = null;


    public static void main(String[] args) {
        if(args[1] != null) {
LOGGER.info(classPath.getParent().resolve(filename).toString());
            readPropertiesFile(classPath.getParent().resolve(filename));
            if ("produce".equals(args[0])) {
                SOSProducer producer = new SOSProducer(jmsServerUri);
                LOGGER.info("message send to queue:");
                LOGGER.info(requestBody);
                producer.write(requestBody, queueName, queueTtl);
            } else if ("consume".equals(args[0])) {
                SOSConsumer consumer = new SOSConsumer(jmsServerUri);
                String consumedMessage = null;
                consumedMessage = consumer.read(queueName);
                LOGGER.info("message received from queue:");
                LOGGER.info(consumedMessage);
                if (consumedMessage != null) {
                    client = setupHttpClient(username, pwd);
                    URI jocUri = URI.create(jocApiUri);
                    LOGGER.info("send login to: " + jocUri.resolve(API_LOGIN).toString());
                    String response = client.postRestService(jocUri.resolve(API_LOGIN), null);
                    LOGGER.info("HTTP status code: " + client.statusCode());
                    if readPropertiesFile(Pathsclient.getstatusCode(args[1]));
) == 200) {
         }   else {
           JsonReader jmsServerUrijsonReader = DEFAULT_JMS_URInull;
            jocApiUri = DEFAULT_JOC_API_URL;
           String requestBodyaccessToken = DEFAULT_JOC_API_REQUEST_BODYnull;
            username = DEFAULT_USERNAME;
            pwd = DEFAULT_PWD;
  try {
      }
        if("produce".equals(args[0])) {
            SOSProducer producerjsonReader = Json.createReader(new SOSProducerStringReader(jmsServerUriresponse));
                    producer.write(requestBody);
        }JsonObject elsejson if ("consume".equals(args[0])) {= jsonReader.readObject();
            SOSConsumer consumer = new SOSConsumer(jmsServerUri);
            String consumedMessageaccessToken = consumerjson.receiveFromQueue(getString("accessToken", "");
            SOSRestApiClient client = setupHttpClient(username, pwd);
         } catch (Exception trye) {
                URI jocUri = URI.create(jocApiUri);
           throw new Exception("Could not determine LOGGERaccessToken.info("send login to: " + jocUri.resolve(API_LOGIN).toString());
", e);
                      String response = client.postRestService(jocUri.resolve(API_LOGIN), null);} finally {
                LOGGER.info("HTTP status code: " + client.statusCode());
            jsonReader.close();
                    if (client.statusCode() == 200) {}
                      JsonReader jsonReader = null;
 client.addHeader(ACCESS_TOKEN_HEADER, accessToken);
                        client.addHeader(CONTENT_TYPE, APPLICATION_JSON);
     String accessToken = null;
                LOGGER.info("REQUEST: "   try {+ API_ADD_ORDER);
                        jsonReader = Json.createReader(new StringReader(response))LOGGER.info("PARAMS: " + consumedMessage);
                        JsonObjectString jsonapiUrl = jsonReader.readObject()null;
                        accessToken = json.getString("accessToken", "");
         if (!API_ADD_ORDER.toLowerCase().startsWith(jocApiUri)) {
           } catch(Exception e) {
              apiUrl = jocApiUri + API_ADD_ORDER;
      LOGGER.warn("Could not determine accessToken.");
               }
     } finally {
                 LOGGER.info("resolvedUri: "      jsonReader.close(+ jocUri.resolve(apiUrl).toString());
                    }
    response                client.addHeader(ACCESS_TOKEN_HEADER, accessToken= client.postRestService(jocUri.resolve(apiUrl), consumedMessage);
                        LOGGER.info("HTTP status code: " + client.addHeader(CONTENT_TYPE, APPLICATION_JSONstatusCode());
                       LOGGER.info("REQUEST: " + API_ADD_ORDER);
 response = client.postRestService(jocUri.resolve(API_LOGOUT), null);
                        LOGGER.info("PARAMSHTTP status code: " + consumedMessageclient.statusCode());
                    String apiUrl = null;
          }
          if (!API_ADD_ORDER.toLowerCase().startsWith(DEFAULT_JOC_API_URL)) {
    }
            }
        apiUrl} = DEFAULT_JOC_API_URL + API_ADD_ORDER;catch (Throwable e) {
            e.printStackTrace();
        }
    System.exit(1);
        } finally {
      LOGGER.info("resolvedUri: " + jocUri.resolve(apiUrl).toString());
   if (client != null) {
              response = client.postRestService(jocUri.resolve(apiUrl), consumedMessagecloseHttpClient();
            }
        LOGGER.info("HTTP status code: " + client.statusCode());}
    }

    private static SOSRestApiClient setupHttpClient(String username, String password) {
        SOSRestApiClient responseclient = new client.postRestService(jocUri.resolve(API_LOGOUT), nullSOSRestApiClient();
        String basicAuth           LOGGER.info("HTTP status code: = Base64.getMimeEncoder().encodeToString((username + ":" + clientpassword).statusCodegetBytes());
        client.setBasicAuthorization(basicAuth);
        return }client;
    }

    private static String  } catch (Exception ecleanupValue(String value) {
        value = value.trim();
             LOGGER.error(e.getMessage(), e);
            } finallyif (value.startsWith("\"")) {
            value =   clientvalue.closeHttpClientsubstring(1);
            }
        }
    }
    
    private static SOSRestApiClient setupHttpClient(String username, String passwordif (value.endsWith("\"")) {
        SOSRestApiClient client = new SOSRestApiClient();
        String basicAuth = Base64.getMimeEncoder().encodeToString((username + ":" + password).getBytes() value = value.substring(0, value.length() - 1);
        client.setBasicAuthorization(basicAuth);}
        return clientvalue;
    }

    private static void readPropertiesFile(Path path) {
        Properties privateprops static= Stringnew cleanupValue(String value)Properties();
        try {
         if(value.startsWith("\"")) {   props.load(Files.newInputStream(path));
            valuejmsServerUri = valuecleanupValue(props.substring(1getProperty("jms_url"));
        }
        if(valueLOGGER.endsWithinfo("\"")) {cfg jms_url: " + jmsServerUri);
            valuequeueName = value.substring(0, value.length() -1cleanupValue(props.getProperty("jms_queue_name"));
        }
     LOGGER.info("cfg jms_queue_name: " return+ valuequeueName);
    }
     
   queueTtl private static void readPropertiesFile (Path path) {
= Long.parseLong(cleanupValue(props.getProperty("jms_queue_name"))); 
            Properties props = new Properties();
LOGGER.info("cfg jms_queue_ttl: " + queueTtl.toString());
            jocApiUri try {= cleanupValue(props.getProperty("joc_api_url"));
            propsLOGGER.load(Files.newInputStream(path))info("cfg joc_api_url: " + jocApiUri);
            jmsServerUricontrollerId = cleanupValue(props.getProperty("JMScontroller_URIid"));
            jocApiUri = cleanupValue(props.getProperty("JOC_API_URL"))LOGGER.info("cfg controller_id: " + controllerId);
            controllerIdworkflowPath = cleanupValue(props.getProperty("controllerIdworkflow_path"));
            workflowPath = cleanupValue(props.getProperty("workflowPath")LOGGER.info("cfg workflow_path: " + workflowPath);
            username = cleanupValue(props.getProperty("username"));
            pwd = cleanupValue(props.getProperty("password"));
            requestBody = "{\"controllerId\":\"" + controllerId + "\",\"orders\":[{\"workflowPath\":\"" + workflowPath
                    workflowPath + "\",\"scheduledFor\":\"now\"}],\"auditLog\":{}}";
        } catch (IOException e) {
            LOGGER.warn("could not read properties file, use defaults instead.");
            jmsServerUri = DEFAULT_JMS_URI;
            queueName = DEFAULT_QUEUE_NAME;
            jocApiUri = DEFAULT_JOC_API_URL;
            requestBody = DEFAULT_JOC_API_REQUEST_BODY;
            username = DEFAULT_USERNAME;
            pwd = DEFAULT_PWD;
         }
   queueTtl = 5000L; 
        }
    }

  }


Maven Configuration Example

This example shows the dependencies required to build the example above example as a Maven project.

Code Block
languagexml
titleMaven Configuration
collapsetrue
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>


	<groupId>com.sos-berlin</groupId>
	<artifactId>activeMQ-example</artifactId>
	<version>0.0.1-SNAPSHOT</version>


	<dependencies>
		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-all</artifactId>
			<version>5.15.0</version>
		</dependency>
	</dependencies>
</project>

...