Page History
...
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
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; } private Connection createConnection() { ConnectionFactory factory = new ActiveMQConnectionFactory(uri); Connection connection = null; try { connection = factory.createConnection(); } catch (JMSException e) { LOGGER.error("JMSException occurred while trying to connect: ", e); } return connection; } private Session createSession(Connection connection) { Session session = null; try { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } catch (JMSException e) { LOGGER.error("JMSException occurred while trying to create Session: ", e); } return session; } private Destination createDestination(Session session) { return this.createDestination(session, DEFAULT_QUEUE_NAME); } private Destination createDestination(Session session, String queueName) { Destination destination = null; try { destination = session.createQueue(queueName); } catch (JMSException e) { LOGGER.error("JMSException occurred while trying to create Destination: ", e); } return destination; } 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; } private String read() { TextMessage message = null; String textMessage = null; Connection connection = createConnection(); try { Session session = createSession(connection); Destination destination = createDestination(session); connection.start(); MessageConsumer consumer = createMessageConsumer(session, 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; } else { break; } } } } catch (JMSException e) { LOGGER.error("JMSException occurred while trying to read from Destination: ", e); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { LOGGER.error("JMSException occurred while trying to close the connection: " , e); } } } return textMessage; } public String receiveFromQueue() { return read(); } } |
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 | ||
---|---|---|
| ||
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])) {
SOSProducer producer = new SOSProducer(JMS_URI);
producer.write(JOC_API_REQUEST_BODY);
} else if ("consume".equals(args[0])) {
SOSConsumer consumer = new SOSConsumer(JMS_URI);
String consumedMessage = consumer.receiveFromQueue();
SOSRestApiClient client = setupHttpClient();
try {
URI jocUri = URI.create(JOC_API_URL);
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) {
LOGGER.warn("Could not determine accessToken.");
} 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(JOC_API_URL)) {
apiUrl = JOC_API_URL + API_ADD_ORDER;
}
LOGGER.info("resolvedUri: " + jocUri.resolve(apiUrl).toString());
response = client.postRestService(jocUri.resolve(apiUrl), consumedMessage);
LOGGER.info("HTTP status code: " + client.statusCode());
response = client.postRestService(jocUri.resolve(API_LOGOUT), null);
LOGGER.info("HTTP status code: " + client.statusCode());
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
} finally {
client.closeHttpClient();
}
}
}
private static SOSRestApiClient setupHttpClient() {
SOSRestApiClient client = new SOSRestApiClient();
String basicAuth = Base64.getMimeEncoder().encodeToString(("[USERNAME]:[PASSWORD]").getBytes());
client.setBasicAuthorization(basicAuth);
return client;
}
}
|
Maven Configuration Example
...
Overview
Content Tools