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.
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 ?
- Need the valid Organization ID
- Which Environment we are going to validate ? Mostly in our local Environment that’s the place we start for any given requirement
- 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.
- Now try to create input XML by passing and Organization Code
- Look the output XML and find which XPath attribute has payment processing flag (Organization/@PaymentProcessingReqd)
What Developers to do ?
- Create Java Class with method name isPaymentProcessRequired()
- Complete the required coding
- Create custom-jar and export to OMS install folder. Assume this jar already added part of external jars
- Build and Deployment
- If SMCFS deployed using weblogic exploded war format : Just restart Server;
- If weblogic exploded war format not used create smcfs.ear file using build command and perform deploy
- Create new service and configure API with Java class and method details.
- Invoke the newly created service using HTTP API tester.
- 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
- 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
- Add these jar file into Eclipse (From Project Explorer — Right Click on Project Name — Build Path — Add External Archives)
- 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
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.
- Read User ID / Password / URL from properties files to avoid hard coding
- 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.
- 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
Really Very help full and very good topic you have cover. Thanks a Lot.
very nice topic coverage here .Please cover on some inventory management and other topic also.
Hi Ravi,
We are working some topics related to inventory management. Keep you posted. Keep sharing your feedback.
Thanks for your valuable comment
Here is one more way of testing code with out build and deployment
http://activekite.com/2017/09/11/sterling-oms-how-to-use-junit-and-code-coverage/
Simple and useful. Good read.
Thanks.
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)
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
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”);
URL which you passing is not correct. You need to use servlet url. Pls search active kite site for http
Please use the below url to call interlop:
http://localhost:7001/yantra/interop/InteropHttpServlet