Versions Compared

Key

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

Table of Contents

Introduction

This document article describes the implementation required for sending messages to a Java Message Queue Service queuewhich:

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

...

  • .

The Apache Active MQ server following Message Queue Service is used in this example: https://activemq.apache.org/.

Mode of Operation

The implementation enables includes the following steps:

  • Creation creation of a message producer to send messages to a Message Queue server (MQ server).Service,
  • creation Creation of a message consumer to receive messages from an MQ server.a Message Queue Service,
  • using the message as part of a JS7 REST Web Service API callSending the message to a JS7 JOC API.

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

Most of the implementation work is done with the standard JMS implementation of Java. The only class from the Active MQ implementation is the ActiveMQConnectionFactory class. It shouldn´t be too complex to change the implementation to the ConnectionFactory of your desired message queue servicepreferred Message Queue Service.

Download

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

Prerequisites

  • A running Message Queue server Service (The example uses Apache the example makes use of Active MQ)
  • A running JS7 Controller, Agent and JOC Cockpit.
  • Maven (required only needed if you users want to build the example as a maven Maven project)

The MessageProducer

This example describes how to build establish a connection to an MQ server a Message Queue Service and send a message to a queue on this server.

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

...

Methods

...

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

The steps are separated into different methods to make the implementation more readable as well as reusable. 

createConnection(String url)

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

The ActiveMQConnectionFactory object has to be instantiated with the URL of the MQ server.

Code Block
languagejava
titlecreateConnectionwrite(String urltext)
linenumberstrue
collapsetrue
    public Connectionvoid createConnectionwrite(String uri){
text, String queueName, long ttl) throws Exception {
       ConnectionFactory Connection factoryconnection = new ActiveMQConnectionFactory(uri)null;
       Connection Session connectionsession = null;
        try {
        connection = factory.createConnection();
  ConnectionFactory factory }= catchnew ActiveMQConnectionFactory(JMSException e) {uri);
        LOGGER.error("JMSException occurred while trying toconnection connect: " , e= factory.createConnection();
    }
      return connection;
}

createSession(Connection connection)

The method is called with an already instantiated Connection object and initiates a Session object through the Connection objects createSession(boolean transacted,  int acknowledgeMode) method.

Code Block
languagejava
titlecreateSession(Connection connection)
linenumberstrue
collapsetrue
private Session createSession(Connection connection){  session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Session session = null;
    try {
Destination destination       session= session.createQueue(queueName);
            MessageProducer producer = connectionsession.createSession(false, Session.AUTO_ACKNOWLEDGEcreateProducer(destination);
            // 5 }sec catchtime (JMSExceptionto e)live {
for the producer for this showcase
   LOGGER.error("JMSException occurred while trying to create Session: " , eproducer.setTimeToLive(ttl);
       }
    return session;
}

createDestination(Session session, String queueName)

This method creates a Destination object. It is called with an active Session object and the name of the queue to write to. The Destination object is initiated through the createQueue(String name) method of the Session object.

Code Block
languagejava
titlecreateDestination(Session session)
linenumberstrue
collapsetrue
public Destination createDestination(Session session, String queueName){
 Message message = null;
      Destination destination       if(text != null;){
       try {
        destinationmessage = session.createQueuecreateTextMessage(queueNametext);
         } catch (JMSException e)} else{
         LOGGER.error("JMSException occurred while trying to create Destination: "message , e= session.createTextMessage(TEXT);
            }
    return destination;
}

createMessageProducer(Session session, Destination destination)

This method is called with an already active Session object as well as an instantiated Destination object. It instantiates a MessageProducer object with the given session and destination.

Code Block
languagejava
titlecreateProducer(Session session, Destination destination)
linenumberstrue
collapsetrue
private MessageProducer createMessageProducer(Session session, Destination destination)        producer.send(message);
        } catch (Throwable e) {
    MessageProducer producer = null;
    try {
  LOGGER.error("JMSException occurred while trying to write Message to Destination: ");
           producer = session.createProducer(destination)throw e;
        } catch (JMSException e finally {
            if(session != null) {
        LOGGER.error("JMSException occurred while trying to create MessageProducer: " ,try e);{
    }           
    return producer;
}

write(String text, MessageProducer producer)

The method is called with the message to send to the server and the MessageProducer object to use for publishing. The message is a String object. The method instantiates a Message object with the text to send.

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

close()

...

connection

...

.

...

Code Block
languagejava
title
close()
linenumberstrue
collapsetrue
private void close(Connection connection){
;
       if (connection != null) {
     } catch (JMSException trye) {
            connection.close();
        } catch (JMSException e) {
            LOGGER.errorwarn("JMSException occurred while trying to close the connection: " , e);
                }
            }
        }
    }

The SOSProducer class

The code example below slightly differs from the examples above. In the class below the write(String text) method already uses the other methods for instantiation, therefore it needs less parameters and it closes the connection itself.The text in the example below consists of a JobScheduler add_order XML, which can later be used to send to a JobSchedulershows the complete class. The code creates a TEXT message consisting of the body for a JS7 /orders/add API request.

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) {
        this.uri = uri;
    }
    
    privatepublic Connectionvoid createConnection()write(String text, String queueName) throws Exception {
        ConnectionFactory factory = new ActiveMQConnectionFactory(uriwrite(text, queueName, 5000L);
    }
    
  Connection connection =public null;
        tryvoid write(String text, String queueName, long ttl) throws Exception {
           Connection connection = factory.createConnection()null;
        Session session = null;
 } catch (JMSException e) {
   try {
        LOGGER.error("JMSException occurred while trying toConnectionFactory connect:factory "= ,new eActiveMQConnectionFactory(uri);
        }
    connection     return connection= factory.createConnection();
    }
    
    privatesession Session= connection.createSession(Connection connection){false, Session.AUTO_ACKNOWLEDGE);
        Session session = null;
 Destination destination    = session.createQueue(queueName);
  try {
         MessageProducer producer = session = connection.createSession(false, Session.AUTO_ACKNOWLEDGEcreateProducer(destination);
        } catch (JMSException e) {
// 5 sec time to live for the producer for this  LOGGER.error("JMSException occurred while trying to create Session: " , eshowcase
            producer.setTimeToLive(ttl);
        }
    Message message =  return sessionnull;
    }
    
    private Destination createDestination(Session sessionif(text != null){
               Destination destinationmessage = nullsession.createTextMessage(text);
          try  } else{
                destinationmessage = session.createQueuecreateTextMessage(QUEUE_NAMETEXT);
        } catch (JMSException e) {}
            producer.send(message);
        } catch (Throwable e) {
            LOGGER.error("JMSException occurred while trying to write Message createto Destination: " , e);
        }
    throw e;
   return destination;
    } finally {
      
    private MessageProducer createMessageProducerif(Session session, Destination!= destinationnull) {
        MessageProducer producer = null;
        try {
            producer   = session.createProducer(destination     session.close();
                } catch (JMSException e) {
                    LOGGER.errorwarn("JMSException occurred while trying to close createthe MessageProducersession: " , e);
        }        }
        return producer;
    }
      
     public voidif write(String text){
connection != null) {
            Connection connection = createConnection();
 try {
      Session session = createSession(connection);
        Destination destination = createDestinationconnection.close(session);
        MessageProducer   producer = createMessageProducer(session, destination);
  } catch (JMSException    Message message = null;e) {
        try {
            if(text != null){
                message = session.createTextMessage(textLOGGER.warn("JMSException occurred while trying to close the connection: ", e);
            } else{
   }
             message = session.createTextMessage(TEXT);}
        }
    }
            producer.send(message);
        } catch (JMSException e) {
            LOGGER.error("JMSException occurred while trying to write Message to Destination: " , e);
        } finally
}

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    if (connection !message = null) {;
        String textMessage = null;
     try {
  Connection connection = null;
        Session session = null;
       connection.close();
 try {
            ConnectionFactory factory }= catchnew ActiveMQConnectionFactory(JMSException euri);
 {
           connection = factory.createConnection();
       LOGGER.error("JMSException occurred while trying to closesession the= connection: " .createSession(false, eSession.AUTO_ACKNOWLEDGE);
            Destination destination   }= session.createQueue(queueName);
            }connection.start();
        }
    }
MessageConsumer consumer   
}

The MessageConsumer

This section describes how to build a connection to a MQ server and receive a message from a queue on this server. Furthermore it describes how to build a TCP socket connection to send the received message to a JobScheduler.

  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 JobScheduler instance.
  8. Send the Message to the JobScheduler
  9. Close the (TCP) connection.

This section shows examples for the last 5 steps as the first four are similar to the examples already shown above for the instantiation of the MessageProducer.

The Methods

createMessageConsumer(Session session, Destination destination)

This method is called with an already active Session object as well as an instantiated Destination object. It instantiates a MessageConsumer object with the given session and destination.

Code Block
languagejava
titlecreateMessageConsumer(Session session, Destination destination)
linenumberstrue
collapsetrue
private MessageConsumer createMessageConsumer(Session session, Destination destination) {
    MessageConsumer consumer = null;
    try {
= session.createConsumer(destination);
            while (true) {
                Message receivedMessage = consumer.receive(1);
                if (receivedMessage != null) {
               consumer = session.createConsumer(destination);
    if (receivedMessage instanceof TextMessage) {
                       } message catch= (JMSException eTextMessage) {receivedMessage;
        LOGGER.error("JMSException occurred while trying to create MessageConsumer: ", e);
                textMessage = message.getText();
     }
     return consumer;
}

read(MessageConsumer consumer)

The method is called with an already instantiated MessageConsumer object to receive a message from the MQ server. It extracts the value from the Message object as a string representation via the Message objects getText() method. 

Code Block
languagejava
titleread()
linenumberstrue
collapsetrue
private String read(MessageConsumer consumer) {
          TextMessage message = null;
    String textMessage = null LOGGER.info("Reading message: " + textMessage);
    try  {
        while (true) {
        break;
    Message receivedMessage = consumer.receive(1);
            if (receivedMessage != null)} else {
                 if (receivedMessage instanceof TextMessage) {
   break;
                 message = (TextMessage) receivedMessage;}
                }
    textMessage = message.getText();
      }
        } catch (Throwable e) {
  LOGGER.info("Reading message: " + textMessage);
      LOGGER.error("JMSException occurred while trying to read from Destination: ");
      break;
       throw e;
        } elsefinally {
            if(session != null) {
         break;
       try {
        }
            }session.close();
        }
        } 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()

The receiveFromQueue() method uses the methods described above to connect to a host running a JobScheduler instance, read from a message queue, send the received message to the JobScheduler instance and close the session to the JobScheduler instance.

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

The SOSConsumer class

The code example below slightly differs from the examples above. In the class below the read() method already uses the other method for instantiation, therefore it needs less parameters and it closes the connection itself.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 static final String DEFAULT_QUEUE_NAME = "test_queue";
    private String uri;
    
    public SOSConsumer (String uri) {
        this.uri = uri;
    }
    
    privatepublic ConnectionString createConnectionread(String queueName) throws Exception {
        ConnectionFactoryTextMessage factorymessage = new ActiveMQConnectionFactory(uri)null;
        ConnectionString connectiontextMessage = null;
        tryConnection {
connection = null;
        Session session connection = factory.createConnection()null;
        } catch (JMSException e)try {
            LOGGER.error("JMSException occurred while trying to connect: ", eConnectionFactory factory = new ActiveMQConnectionFactory(uri);
        }
    connection = factory.createConnection();
  return  connection;
    }

    privatesession Session= connection.createSession(Connection connection) {
false, Session.AUTO_ACKNOWLEDGE);
            SessionDestination sessiondestination = nullsession.createQueue(queueName);
        try {
    connection.start();
            MessageConsumer sessionconsumer = connectionsession.createSession(false, Session.AUTO_ACKNOWLEDGEcreateConsumer(destination);
          }  catchwhile (JMSException etrue) {
            LOGGER.error("JMSException occurred while trying toMessage createreceivedMessage Session: ", e= consumer.receive(1);
           }
     if (receivedMessage != returnnull) session;{
    }

    private Destination createDestination(Session session) {
        returnif this.createDestination(session, DEFAULT_QUEUE_NAME);(receivedMessage instanceof TextMessage) {
    }

     private Destination createDestination(Session session, String queueName) {
        Destination destinationmessage = (TextMessage) nullreceivedMessage;
          try  {
            destinationtextMessage = sessionmessage.createQueuegetText(queueName);
        } catch (JMSException e) {
            LOGGER.errorinfo("JMSException occurred while trying to create DestinationReading message: ", + etextMessage);
          }
         return destination;
    }break;

    private MessageConsumer createMessageConsumer(Session  session, Destination destination) {
        MessageConsumer consumer} =else null;{
        try  {
            consumer = session.createConsumer(destination) break;
        } catch (JMSException e) {
        }
    LOGGER.error("JMSException occurred while trying to create MessageConsumer: ", e);
     }
   }
        return consumer;}
    }

    private} Stringcatch read(Throwable e) {
        TextMessage message = null;
        String textMessage = null;

 LOGGER.error("JMSException occurred while trying to read from Destination: ");
          Connection connection =throw createConnection()e;
        } tryfinally {
            Session if(session != createSession(connection);null) {
            Destination destination = createDestination(session);
 try {
          connection.start();
          session.close();
  MessageConsumer consumer = createMessageConsumer(session, destination);
          } catch while(JMSException (truee) {
                 Message receivedMessage = consumerLOGGER.receive(1warn("JMSException occurred while trying to close the session: ", e);
                if}
 (receivedMessage != null) {
        }
            if (receivedMessageconnection instanceof!= TextMessagenull) {
                try {
       message = (TextMessage) receivedMessage;
          connection.close();
              textMessage = message.getText();
     } catch (JMSException e) {
                    LOGGER.infowarn("ReadingJMSException message:occurred "while + textMessage);
                        break;
    trying to close the connection: ", e);
                } else {
                        break;
           }
         }
            return textMessage;
    }
            }
        } catch (JMSException e) {
            LOGGER.error("JMSException occurred while trying to read from Destination: ", e);
        } finally {
            if (connection != null) {
                try {
                    connection.close();}

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\""
                } catch (JMSException e) {+ ":[{\"workflowPath\":\"/JS7Demo/01_HelloWorld/jdHelloWorld\",\"scheduledFor\":\"now\"}],\"auditLog\":{}}";
    private static final String DEFAULT_USERNAME = "root";
    private static final String DEFAULT_PWD  LOGGER.error("JMSException occurred while trying to close the connection: " , e)= "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   }= "authentication/logout";
    private static final String ACCESS_TOKEN_HEADER return textMessage= "X-Access-Token";
    }

private static final String APPLICATION_JSON = "application/json";
    private static publicfinal String receiveFromQueue() { CONTENT_TYPE = "Content-Type";
    private static final Logger LOGGER return= read(LoggerFactory.getLogger(JmsExecute.class);
    private static String jmsServerUri = }

}

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

The Java class uses 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 a http connection to a JS7 JOC API 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. You can use your own HTTP client implementation instead.

Code Block
languagejava
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])) {
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;
    private static String queueName = null;
    private static Long queueTtl = null;

    public static void main(String[] args) throws URISyntaxException {
        SOSRestApiClient client = null;
        try {
            URL classUrl = JmsExecute.class.getProtectionDomain().getCodeSource().getLocation();
            Path classPath = Paths.get(classUrl.toURI());
            String filename = classPath.getFileName().toString().replace(".jar", ".config");
            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 (client.statusCode() == 200) {
                        JsonReader jsonReader = null;
                        String accessToken = null;
                        try {
                            jsonReader = Json.createReader(new StringReader(response));
                            JsonObject json = jsonReader.readObject();
                            accessToken = json.getString("accessToken", "");
                        } catch (Exception e) {
                            throw new Exception("Could not determine accessToken.", e);
                        } 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("resolvedUri"cfg 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 dependency needed dependencies required to build the example above 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>

...