Sterling OMS How to test Java Code using HTTP Client

By | 08/27/2017

Sterling OMS How to test Java Code using HTTP Client

Requirement : For given Organization ID (Matrix) print payment processing is enabled or not ? Write Java Class with Method return type as boolean.

Java HTTP Tester Sterling OMS

private boolean isPaymentProcessRequired(String orgCode) throws Exception {
  if(payment process enabled) {
   return true;
  }
  else {
   return false;
  }
}

What all the required parameters to solve the requirement ?

  1. Need the valid Organization ID
  2. Which Environment we are going to validate ? Mostly in our local Environment that’s the place we start for any given requirement
  3. Which API can get this details ? Open API Java Doc and find the API. We already know out-of-box API getOrganizationHierarchy can give Organization related details.
  4. Now try to create input XML by passing and Organization Code
  5. Look the output XML and find which XPath attribute has payment processing flag (Organization/@PaymentProcessingReqd)

What Developers to do ?

  1. Create Java Class with method name isPaymentProcessRequired()
  2. Complete the required coding
  3. Create custom-jar and export to OMS install folder. Assume this jar already added part of external jars
  4. Build and Deployment
    1. If SMCFS deployed using weblogic exploded war format : Just restart Server;
    2. If weblogic exploded war format not used create smcfs.ear file using build command and perform deploy
  5. Create new service and configure API with Java class and method details.
  6. Invoke the newly created service using HTTP API tester.
  7. If method did not work as expected; Make Java code change and follow from step 3

Sterling OMS How to test Java Code using HTTP Client

How nice will be directly write code and test from Java IDE (Eclipse) with out build/deployment/restart of servers ?

There are multiple way to do this. In this post we are going to see one way of doing. Called as Java HTTP API Client.

Steps

  1. Download following Jar files from Internet. These jar files has dependency with each other. So try to download correct versions.
    • commons-codec-1.2.jar
    • commons-httpclient-3.1.jar
    • commons-logging-1.0.4.jar
    • junit-4.12.jar
  2. Add these jar file into Eclipse (From Project Explorer — Right Click on Project Name — Build Path — Add External Archives)
  3. Create HttpSocketClient.java (Image shown below)
package com.oms94.util.http;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

public class HttpSocketClient {
	
	public String postAndGetContents(String url,
			String requestXML, String template,String apiName, String isFlow, 
			String userId, String password) throws Exception {
		int retryCount = 2;
		PostMethod method = new PostMethod(url);

		method.setRequestBody(getParams(apiName,isFlow,requestXML,template, userId, password));
		try {
			int statusCode = execute(method, retryCount);
			if (statusCode != HttpStatus.SC_OK) {
				throw new HttpException("Method failed: " + method.getStatusLine());
			}
			return method.getResponseBodyAsString();
		} finally {
			//Release
			method.releaseConnection();
		}
	}

	private NameValuePair[] getParams(String apiName, String IsFlow,String requestXml, String template, 
			String userName, String password) {
		return new NameValuePair[] {new NameValuePair("YFSEnvironment.userId", userName),
				new NameValuePair("YFSEnvironment.password", password),
				new NameValuePair("InteropApiName", apiName),
				new NameValuePair("IsFlow", IsFlow),
				new NameValuePair("InteropApiData", requestXml),new NameValuePair("TemplateData", template)};		
	}
	
	private int execute(PostMethod method, int retryCount) throws Exception {
		HttpClient client = new HttpClient();
		int count = 0;
		while (true) {
			try {
				return client.executeMethod(method);
			} catch (HttpException e) {
				throw e;
			} catch (IOException ie) {
				if (count++ >= retryCount) {
					throw ie;
				}
				//close cached connection
				client.getHttpConnectionManager().closeIdleConnections(0);		
			}
		}
	}
}
  • Create HttpSocketClientTest.java (Image shown below)
package com.oms94.test;

import java.io.StringWriter;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.xpath.XPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import com.oms94.util.http.HttpSocketClient;
import com.yantra.yfc.dom.YFCDocument;
import com.yantra.yfc.dom.YFCElement;

public class HttpSocketClientTest {

	public static void main(String[] args) {

		try {
			HttpSocketClientTest httpSocketClientTest = new HttpSocketClientTest();
			if(httpSocketClientTest.isPaymentProcessRequired("Matrix")) {
				System.out.println("Payment Processing required");
			}else {
				System.out.println("Payment Processing not required");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * @param orgCode
	 * @return boolean
	 * @throws Exception
	 */
	private boolean isPaymentProcessRequired(String orgCode) throws Exception {
		Document documentResult = getOrganizationDetails(orgCode);
		if(documentResult != null) {
			String paymentProcessRequired = getValue(documentResult, "OrganizationList/Organization/@PaymentProcessingReqd");
			if("Y".equalsIgnoreCase(paymentProcessRequired)) {
				return true;
			}else {
				return false;
			}
		}
		return false;
	}
	
	/**
	 * @param node
	 * @param xpath
	 * @return
	 * @throws TransformerException
	 */
	public static String getValue(Node node, String xpath) // should be part of util class; added here only for education purpose
			throws TransformerException	{
		if (null == node || null == xpath || 0 == xpath.trim().length()) {
			return null;
		}

		Node ret = null;
		ret = XPathAPI.selectSingleNode(node, xpath);
		return ret == null ? null : ret.getNodeValue();
	}
	
	private Document getOrganizationDetails(String orgCode) {
		YFCDocument returnDoc = null;
		try {
			HttpSocketClient httpSocketClient = new HttpSocketClient();
			YFCElement organization = YFCDocument.createDocument("Organization")
					.getDocumentElement();
			
			organization.setAttribute("OrganizationCode", orgCode);
			Document inDoc = organization.getOwnerDocument().getDocument();
			
			String result = httpSocketClient.postAndGetContents("http://localhost:7001/smcfs/interop/InteropHttpServlet", 
					getStringFromDocument(inDoc),
					"","getOrganizationList","N", "admin","password"); // should read from properties file
			
			System.out.println(result);
			returnDoc = YFCDocument.getDocumentFor(result);
			return returnDoc.getDocument();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private static String getStringFromDocument(Document doc)
	{ // should be part of util class; added here only for education purpose
	    try
	    {
	       DOMSource domSource = new DOMSource(doc);
	       StringWriter writer = new StringWriter();
	       StreamResult result = new StreamResult(writer);
	       TransformerFactory tf = TransformerFactory.newInstance();
	       Transformer transformer = tf.newTransformer();
	       transformer.transform(domSource, result);
	       return writer.toString();
	    }
	    catch(TransformerException ex) {	      
	       return null;
	    }
	}
}
  • Modify URL/User Name/Password in the above Java Code and Save
  • Run the test program directly.
  • You can make multiple API calls in one method and do all the required XML logic and test directly
Sterling OMS How to test Java Code using HTTP Client

Sterling OMS How to test Java Code using HTTP Client

Is this right way of testing in OMS ? May not. This is just for testing in local without build and deployment. Once you are confident about the code and logic should test with full build and deployment in your local environment.

Whom this process helps ?

Developer who make one line code change and do build and deployment Or restart Servers. Code change takes only few seconds but build / deploy / restart takes couple of minutes and service creation and HTTP Web tester takes time.

Improvements on the above code

Yes surly we can make lot of improvements. Sample shared here only for education purpose.

  1. Read User ID / Password / URL from properties files to avoid hard coding
  2. Instead of creating input document using Java Code; you can directly read from file and convert to Document Object; This way you can just modify the input XML and use it of any testing.
  3. Method should be moved to Util class and reused later. Example getStringFromDocument() and getValue()

Really not sure how many people read this line. This is one approach found to be useful. Many other ways could be possible. Please take your 2 minutes to comment on this post. So that we can create bigger Sterling OMS community to help people.

Any feedback/suggestion please write to us support@activekite.com

Register with us to get more OMS learning updates

Sterling OMS Interview Questions

11 thoughts on “Sterling OMS How to test Java Code using HTTP Client

  1. Aman

    Really Very help full and very good topic you have cover. Thanks a Lot.

    Reply
  2. ravi

    very nice topic coverage here .Please cover on some inventory management and other topic also.

    Reply
    1. admin Post author

      Hi Ravi,
      We are working some topics related to inventory management. Keep you posted. Keep sharing your feedback.

      Reply
  3. Shyam Santhanam

    Simple and useful. Good read.
    Thanks.

    Reply
  4. Irfan

    I am getting below error. I have imported all required jars.

    Exception in thread “main” java.lang.Error: Unresolved compilation problem:

    at com.ril.rfresh.oms.util.HttpSocketClientTest.main(HttpSocketClientTest.java:21)

    Reply
    1. admin Post author

      This seems to compile time error. Can you please tell us how are you trying to run the program ? Are you use any program like eclipse ? Look your import statements. Share us the screenshot to help you. Thanks

      Reply
  5. Sai

    Invoking getOrderDetails but output not dispalying :
    output:
    :::::::: Code Testing started ! :::::::::
    —————-Order Header Key———- = 20190705002119313152
    2222222222222222222222222222222222222222222222222222
    log4j:WARN No appenders could be found for logger (org.apache.commons.httpclient.HttpMethodBase).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
    3333333333333333333333333333333333333333333333333

    Code:
    HttpSocketClient httpSocketClient = new HttpSocketClient();

    System.out.println(“2222222222222222222222222222222222222222222222222222”);

    String result = httpSocketClient.postAndGetContents
    (“http://localhost:7001/smcfs/yfshttpapi/yantrahttpapitester.jsp”,
    getStringFromDocument(getOrderDetailsInputDoc),
    “”,
    “getOrderDetails”,”N”, “admin”,”password”); // should read from properties file
    System.out.println(“3333333333333333333333333333333333333333333333333”);

    Reply
    1. admin Post author

      URL which you passing is not correct. You need to use servlet url. Pls search active kite site for http

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *