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 Blockcode
languagejava
titlecreateConnectionwrite(String urltext)
linenumberstrue
collapsetrue
    public Connectionvoid createConnectionwrite(String text, String queueName, long urittl) throws Exception {
       ConnectionFactory Connection factoryconnection = new ActiveMQConnectionFactory(uri)null;
       Connection Session connectionsession = null;
        try {
        connection    ConnectionFactory factory = new factory.createConnectionActiveMQConnectionFactory(uri);
    } catch (JMSException e) {
    connection = factory.createConnection();
       LOGGER.error("JMSException occurred while trying to connect:session "= connection.createSession(false, eSession.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_ACKNOWLEDGE);
setTimeToLive(ttl);
            Message message = null;
         }  catch if(JMSException e) 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){
.createTextMessage(TEXT);
         Destination destination = null;}
    try {
        destination = sessionproducer.createQueuesend(queueNamemessage);
        } catch (JMSExceptionThrowable e) {
            LOGGER.error("JMSException occurred while trying to write Message createto 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){
    MessageProducer producer = null;
    try {
 if(session != null) {
                try {
                  producer = session.createProducerclose(destination);
    } catch (JMSException e) {
        LOGGER.error} catch (JMSException e) {
                    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){
    Message message = null;
if (connection != null) {
                try {
        if(text != null){
            message = session.createTextMessage(textconnection.close();
        }  else{
      } catch (JMSException e) {
  message = session.createTextMessage(DEFAULT_TEXT);
        }
        producerLOGGER.send(message);
    } catch (JMSException e) {
warn("JMSException occurred while trying to close the connection: ", 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 = Logger.getLogger(SOSProducer.class);
    private static final String TEXT =   connection.close()"{\"controllerId\":\"testsuite\",\"orders\":[{\"workflowPath\":\"/JS7Demo/01_HelloWorld/jdHelloWorld\",\"scheduledFor\":\"now\"}],\"auditLog\":{}}";
    private String uri;
    
    }public catch SOSProducer(JMSExceptionString euri) {
            LOGGER.error("JMSException occurred while trying to close the connection: " , ethis.uri = uri;
    }
    
    public void write(String text, String queueName) throws Exception {
        write(text, queueName, 5000L);
    }
    }
    public  }
}

The SOSProducer class

...

void write(String text

...

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) {
, String queueName, long ttl) throws Exception {
        Connection connection = null;
        Session session = null;
        try {
            ConnectionFactory factory = new ActiveMQConnectionFactory(uri);
            connection = factory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue(queueName);
            MessageProducer this.uriproducer = urisession.createProducer(destination);
    }
    
    private// Connection createConnection(){5 sec time to live for the producer for this showcase
        ConnectionFactory factory = new ActiveMQConnectionFactoryproducer.setTimeToLive(urittl);
            ConnectionMessage connectionmessage = null;
            try if(text != null){
                connectionmessage = factorysession.createConnectioncreateTextMessage(text);
         } catch (JMSException e)} else{
            LOGGER.error("JMSException occurred while trying tomessage connect: " , e= session.createTextMessage(TEXT);
            }
        return connection;
    }producer.send(message);
    
    private} Sessioncatch createSession(ConnectionThrowable connectione) {
        Session session = null;
        try { LOGGER.error("JMSException occurred while trying to write Message to Destination: ");
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)throw e;
        } catch (JMSException e) finally {
            LOGGER.error("JMSException occurred while trying to create Session: " , e);
if(session != null) {
             }
   try {
    return session;
    }
    
    private Destination createDestination(Session session.close(){;
        Destination destination = null;
     } catch (JMSException trye) {
                  destination = sessionLOGGER.createQueue(QUEUE_NAME);
        } catch (JMSException e) {
warn("JMSException occurred while trying to close the session: ", e);
               LOGGER.error("JMSException occurred while trying to create Destination: " , e);
  }
            }
       }
     if (connection != returnnull) destination;{
    }
    
    private MessageProducer createMessageProducer(Session session, Destinationtry destination){
        MessageProducer producer = null;
        try { connection.close();
            producer = session.createProducer(destination);
        } catch (JMSException e) {
                    LOGGER.errorwarn("JMSException occurred while trying to createclose MessageProducerthe connection: " , 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);
            } else
}

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 = session.createTextMessage(TEXT)null;
        String textMessage =  }null;
        Connection connection   producer.send(message)= null;
        Session }session catch (JMSException e) {
= null;
        try {
     LOGGER.error("JMSException occurred while trying to write Message toConnectionFactory Destination:factory "= ,new eActiveMQConnectionFactory(uri);
            }connection finally {
= factory.createConnection();
            session if= connection.createSession(connection != null) {false, Session.AUTO_ACKNOWLEDGE);
            Destination destination   try {
= session.createQueue(queueName);
            connection.start();
            MessageConsumer consumer = connectionsession.closecreateConsumer(destination);
                } catchwhile (JMSException etrue) {
                Message receivedMessage =  LOGGERconsumer.error("JMSException occurred while trying to close the connection: " , e);
receive(1);
                if (receivedMessage != null) {
      }
            }
  if (receivedMessage instanceof TextMessage) {
  }
    }
    
}

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)

...

                  message = (TextMessage) receivedMessage;
                        textMessage = message.getText();
                        LOGGER.info("Reading message: " + textMessage);
                        break;
                    } else {
                        break;
                    }
                }
            }
        } catch (Throwable e) {
            LOGGER.error("JMSException occurred while trying to read from Destination: ");
            throw e;
        } finally {
            if(session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    LOGGER.warn("JMSException occurred while trying to close the session: ", e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    LOGGER.warn("JMSException occurred while trying to close the connection: ", e);
                }
            }
         }
        return textMessage;
    }

The SOSConsumer class

The code example below shows the complete 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 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();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue(queueName);
            connection.start();
            MessageConsumer consumer = session.createConsumer(destination);
            while (true) {
                Message receivedMessage = consumer.receive(1);
                if (receivedMessage != null) {
                    if (receivedMessage instanceof TextMessage) {
                        message = (TextMessage) receivedMessage;
                        textMessage = message.getText();
                        LOGGER.info("Reading message: " + textMessage);
                        break;
     
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) {
        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) {
    TextMessage message = null;
    String textMessage = null;
    try {
        while (true) {
            Message   receivedMessage} = consumer.receive(1);else {
            if (receivedMessage != null) {
        break;
        if  (receivedMessage instanceof TextMessage) {
       }
             message = (TextMessage) receivedMessage;}
            }
        } textMessagecatch = message.getText();(Throwable e) {
            LOGGER.error("JMSException occurred while trying to read   LOGGER.info("Reading messagefrom Destination: " + textMessage);
            throw e;
       break;
 } finally {
            if(session }!= elsenull) {
                try {
    break;
                }
session.close();
                }
 catch (JMSException e) {
    }
    } catch (JMSException e) {
        LOGGER.errorwarn("JMSException occurred while trying to readclose fromthe Destinationsession: ", e);
                }
           return textMessage;
}
Note

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

receiveFromQueue()

...

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

The SOSConsumer class

textMessage;
    }

}

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. The below code example slightly differs from the examples above. In the below class the read() method uses another method for instantiation, therefore it requires fewer parameters and it closes the connection to JOC Cockpit.

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

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSExceptionpackage com.sos.jms;

import java.io.IOException;
import javaxjava.jmsio.MessageStringReader;
import javaxjava.jmsnet.MessageConsumerURI;
import javaxjava.jmsnet.SessionURISyntaxException;
import javaxjava.jmsnet.TextMessageURL;

import orgjava.apachenio.activemqfile.ActiveMQConnectionFactoryFiles;
import orgjava.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) {
        this.uri = uri;
    }
    
    private Connection createConnection() {
        ConnectionFactory factory = new ActiveMQConnectionFactory(uri);
        Connection connection = null;
        try {
            connection = factory.createConnection();
        } catch (JMSException e) {
    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\""
        LOGGER.error("JMSException occurred while trying to connect: ", e);
        }
        return connection+ ":[{\"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 private Session createSession(Connection connection) {DEFAULT_QUEUE_NAME = "test_queue";
    private static final String Session session = nullAPI_ADD_ORDER = "orders/add";
    private static final String try {API_LOGIN = "authentication/login";
    private static final      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)String API_LOGOUT = "authentication/logout";
    private static final String } catch (JMSException e) {ACCESS_TOKEN_HEADER = "X-Access-Token";
    private static final String APPLICATION_JSON  =  LOGGER.error("JMSException occurred while trying to create Session: ", e);
 "application/json";
    private static final }
String CONTENT_TYPE = "Content-Type";
    private returnstatic session;
final Logger LOGGER  }

= LoggerFactory.getLogger(JmsExecute.class);
    private static DestinationString createDestination(Session session) {jmsServerUri = null;
    private static String jocApiUri return this.createDestination(session, DEFAULT_QUEUE_NAME)= null;
    }

    private Destinationstatic createDestination(Session session, String queueName) {String controllerId = null;
    private static String  Destination destinationworkflowPath = null;
    private static String requestBody try= {null;
    private static       destinationString username = session.createQueue(queueName)null;
    private static String pwd }= catchnull;
 (JMSException e) {
 private static String queueName = null;
    private  LOGGER.error("JMSException occurred while trying to create Destination: ", e);
        }
static Long queueTtl = null;

    public static void main(String[] args) throws URISyntaxException {
        SOSRestApiClient client return= destinationnull;
    }

    private MessageConsumer createMessageConsumer(Session session, Destination destination) {
try {
            MessageConsumerURL consumerclassUrl = nullJmsExecute.class.getProtectionDomain().getCodeSource().getLocation();
        try {
   Path classPath = Paths.get(classUrl.toURI());
      consumer = session.createConsumer(destination);
    String filename   } catch (JMSException e) {= classPath.getFileName().toString().replace(".jar", ".config");
            LOGGER.error("JMSException occurred while trying to create MessageConsumer: ", e.info(classPath.getParent().resolve(filename).toString());
        }
    readPropertiesFile(classPath.getParent().resolve(filename));
    return consumer;
    }

    private String read(if ("produce".equals(args[0])) {
        TextMessage message = null;
     SOSProducer producer = String textMessage = null;
new SOSProducer(jmsServerUri);
        Connection connection = createConnection();
     LOGGER.info("message send  try {
to queue:");
             Session session = createSessionLOGGER.info(connectionrequestBody);
            Destination  destination = createDestination(sessionproducer.write(requestBody, queueName, queueTtl);
            } else if connection.start();
("consume".equals(args[0])) {
                MessageConsumerSOSConsumer consumer = new createMessageConsumer(session, destinationSOSConsumer(jmsServerUri);
                String whileconsumedMessage (true) {= null;
                Message receivedMessageconsumedMessage = consumer.receiveread(1queueName);
                if (receivedMessage != null) {
LOGGER.info("message received from queue:");
                LOGGER.info(consumedMessage);
                if (receivedMessageconsumedMessage instanceof!= TextMessagenull) {
                      client  message = setupHttpClient(TextMessage) receivedMessageusername, pwd);
                    URI    textMessagejocUri = messageURI.getTextcreate(jocApiUri);
                        LOGGER.info("Readingsend login messageto: " + textMessagejocUri.resolve(API_LOGIN).toString());
                    String response =  break;
client.postRestService(jocUri.resolve(API_LOGIN), null);
                    LOGGER.info("HTTP status code: }" else {
+ client.statusCode());
                    if (client.statusCode() == 200) {
         break;
               JsonReader jsonReader =   }null;
                }
        String accessToken =  }null;
        } catch (JMSException e) {
            LOGGER.error("JMSException occurred while trying to read from Destination: ", e);
try {
                } finally {
          jsonReader = ifJson.createReader(new (connection != null) {StringReader(response));
                try {
           JsonObject         connection.closejson = jsonReader.readObject();
                } catch (JMSException e) {
        accessToken = json.getString("accessToken", "");
         LOGGER.error("JMSException occurred while trying to close the connection: " , e);
     } catch (Exception e) {
       }
            }
         }
throw new Exception("Could not determine    return textMessageaccessToken.", e);
    }

    public String receiveFromQueue() {
        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.StringReader;
import java.net.URI;
import java.util.Base64;

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 JMS_URI = "tcp://[MESSAGE_SERVER_HOST]:61616";
    private static final String JOC_API_URL = "http://[JOC_COCKPIT_HOST]:[JOC_COCKPIT_PORT]/joc/api/";
    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 JOC_API_REQUEST_BODY = "{\"controllerId\":\"testsuite\",\"orders\":[{\"workflowPath\":\"/JS7Demo/01_HelloWorld/jdHelloWorld\",\"scheduledFor\":\"now\"}],\"auditLog\":{}}";
    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);

    public static void main(String[] args) {
        if("produce".equals(args[0])) {
     } finally {
                            jsonReader.close();
                        }
                        client.addHeader(ACCESS_TOKEN_HEADER, accessToken);
                        client.addHeader(CONTENT_TYPE, APPLICATION_JSON);
                        LOGGER.info("REQUEST: " + API_ADD_ORDER);
                        LOGGER.info("PARAMS: " + consumedMessage);
                        String apiUrl = null;
                        if (!API_ADD_ORDER.toLowerCase().startsWith(jocApiUri)) {
                SOSProducer producer = new SOSProducer(JMS_URI);
        apiUrl = jocApiUri + producer.write(JOC_API_REQUESTADD_BODY)ORDER;
                 } else if ("consume".equals(args[0])) {
   }
         SOSConsumer consumer = new SOSConsumer(JMS_URI);
            String consumedMessage = consumer.receiveFromQueue(LOGGER.info("resolvedUri: " + jocUri.resolve(apiUrl).toString());
            SOSRestApiClient client = setupHttpClient();
         response =  try {client.postRestService(jocUri.resolve(apiUrl), consumedMessage);
                URI jocUri = URI.create(JOC_API_URL);
                LOGGER.info("sendHTTP loginstatus tocode: " + jocUriclient.resolvestatusCode(API_LOGIN).toString());
                      String  response = client.postRestService(jocUri.resolve(API_LOGINLOGOUT), null);
;
                        LOGGER.info("HTTP status code: " + client.statusCode());
                    }
            if (client.statusCode() == 200) {}
            }
        } JsonReadercatch jsonReader(Throwable =e) null;{
            e.printStackTrace();
         String accessToken = null System.exit(1);
        } finally {
           try {
 if (client != null) {
                client.closeHttpClient();
            }
     jsonReader = Json.createReader(new StringReader(response)); }
    }

    private static SOSRestApiClient setupHttpClient(String username, String password) {
        SOSRestApiClient JsonObjectclient json= =new jsonReader.readObjectSOSRestApiClient();
        String basicAuth = Base64.getMimeEncoder().encodeToString((username + ":" + password).getBytes());
         accessToken = json.getString("accessToken", ""client.setBasicAuthorization(basicAuth);
        return client;
    }

    private static String } catchcleanupValue(ExceptionString evalue) {
        value = value.trim();
        if (value.startsWith("\"")) {
           LOGGER.warn("Could not determine accessToken." value = value.substring(1);
        }
            } finally if (value.endsWith("\"")) {
                        jsonReader.close(value = value.substring(0, value.length() - 1);
        }
        return value;
    }

    private static void readPropertiesFile(Path path) {
        Properties props = new client.addHeader(ACCESS_TOKEN_HEADER, accessTokenProperties();
        try {
            client.addHeader(CONTENT_TYPE, APPLICATION_JSONprops.load(Files.newInputStream(path));
            jmsServerUri        LOGGER.info("REQUEST: " + API_ADD_ORDER);
        = cleanupValue(props.getProperty("jms_url"));
            LOGGER.info("PARAMScfg jms_url: " + consumedMessagejmsServerUri);
            queueName = cleanupValue(props.getProperty("jms_queue_name"));
      String apiUrl = null;
   LOGGER.info("cfg jms_queue_name: " + queueName);
            queueTtl if= (!API_ADD_ORDER.toLowerCase().startsWith(JOC_API_URL)) {
Long.parseLong(cleanupValue(props.getProperty("jms_queue_name"))); 
            LOGGER.info("cfg jms_queue_ttl: " + queueTtl.toString());
          apiUrl = JOC_API_URL + API_ADD_ORDER;
jocApiUri = cleanupValue(props.getProperty("joc_api_url"));
            LOGGER.info("cfg joc_api_url: " + jocApiUri);
      }
      controllerId = cleanupValue(props.getProperty("controller_id"));
            LOGGER.info("resolvedUricfg controller_id: " + jocUri.resolve(apiUrl).toString()controllerId);
                    responseworkflowPath = client.postRestServicecleanupValue(jocUriprops.resolve(apiUrl), consumedMessagegetProperty("workflow_path"));
                    LOGGER.info("HTTP status codecfg workflow_path: " + client.statusCode(workflowPath));
            username = cleanupValue(props.getProperty("username"));
           response pwd = client.postRestServicecleanupValue(jocUriprops.resolve(API_LOGOUT), nullgetProperty("password"));
            requestBody = "{\"controllerId\":\"" + controllerId + "\",\"orders\":[{\"workflowPath\":\"" +  LOGGER.info("HTTP status code: " + client.statusCode());
workflowPath
                              }
    + "\",\"scheduledFor\":\"now\"}],\"auditLog\":{}}";
        } catch (ExceptionIOException e) {
            LOGGER.warn("could not read  LOGGER.error(e.getMessage(), eproperties file, use defaults instead.");
            }jmsServerUri finally {= DEFAULT_JMS_URI;
            queueName    client.closeHttpClient()= DEFAULT_QUEUE_NAME;
            }

jocApiUri        }= DEFAULT_JOC_API_URL;
    }
     
   requestBody private static SOSRestApiClient setupHttpClient() {
= DEFAULT_JOC_API_REQUEST_BODY;
           SOSRestApiClient clientusername = new SOSRestApiClient()DEFAULT_USERNAME;
           String basicAuthpwd = Base64.getMimeEncoder().encodeToString(("[USERNAME]:[PASSWORD]").getBytes())DEFAULT_PWD;
        client.setBasicAuthorization(basicAuth);
    queueTtl = 5000L; 
   return client;
    }
    
}

}


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>

...