Versions Compared

Key

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

...

Code Block
languagejava
collapsetrue
package com.sos.jms;

import java.io.FileInputStreamIOException;
import java.io.IOException.StringReader;
import java.net.URI;
import java.ionet.StringReaderURISyntaxException;
import java.net.URIURL;
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) throws URISyntaxException {
        if(args[1] != nullfor (int i = 0; i < args.length; i++) {
            readPropertiesFile(PathsLOGGER.get(args[1])info("args["+ i +"] = " + args[i]);
        } else {
        URL    jmsServerUriclassUrl = DEFAULT_JMS_URIJmsExecute.class.getProtectionDomain().getCodeSource().getLocation();
        Path classPath = Paths.get(classUrl.toURI());
    jocApiUri = DEFAULT_JOC_API_URL;
  String filename = classPath.getFileName().toString().replace(".jar", ".config");
      requestBody = DEFAULT_JOC_API_REQUEST_BODY LOGGER.info(classPath.getParent().resolve(filename).toString());
        readPropertiesFile(classPath.getParent().resolve(filename));
    username = DEFAULT_USERNAME;
    if("produce".equals(args[0])) {
            SOSProducer pwdproducer = DEFAULT_PWDnew SOSProducer(jmsServerUri);
        }
    LOGGER.info("message send   if("produce".equals(args[0])) {to queue:");
            SOSProducer producer = new SOSProducer(jmsServerUriLOGGER.info(requestBody);
            producer.write(requestBody);
        } else if ("consume".equals(args[0])) {
            SOSConsumer consumer = new SOSConsumer(jmsServerUri);
            String consumedMessage = consumer.receiveFromQueue(read();
            LOGGER.info("message received from queue:");
            LOGGER.info(consumedMessage);
            SOSRestApiClient client = setupHttpClient(username, pwd);
            try {
                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) {
                        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(DEFAULT_JOC_API_URLjocApiUri)) {
                        apiUrl = DEFAULT_JOC_API_URLjocApiUri + 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(String username, String password) {
        SOSRestApiClient client = new SOSRestApiClient();
        String basicAuth = Base64.getMimeEncoder().encodeToString((username + ":" + password).getBytes());
        client.setBasicAuthorization(basicAuth);
        return client;
    }
    
    private static String cleanupValue(String value) {
        if(value.startsWith("\"")) {
            value = value.substring(1);
        }
        if(value.endsWith("\"")) {
            value = value.substring(0, value.length() -11);
        }
        return value;
    }
    
    private static void readPropertiesFile (Path path) {
        Properties props = new Properties();
        try }{
          return value  props.load(Files.newInputStream(path));
    }
    
    privatejmsServerUri static void readPropertiesFile (Path path) {
= cleanupValue(props.getProperty("jms_url"));
            Properties props = new Properties(LOGGER.info("cfg jms_url: " + jmsServerUri);
            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 + "\",\"scheduledFor\":\"now\"}],\"auditLog\":{}}";
        } catch (IOException e) {
            LOGGER.warn("could not read properties file, use defaults instead.");
            jmsServerUri = DEFAULT_JMS_URI;
            jocApiUri = DEFAULT_JOC_API_URL;
            requestBody = DEFAULT_JOC_API_REQUEST_BODY;
            username = DEFAULT_USERNAME;
            pwd = DEFAULT_PWD;
        }
    }
}

  


Maven Configuration Example

...

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>

...