Tuesday, November 29, 2011

Java client to post/consume message from Weblogic JMS Queue

Java client to post/consume message from Weblogic JMS Queue

Sample Java client to post the message and consume the message from the Weblogic JMS queue.

package com.jms.test.wl;

import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnectionFactory;
import javax.jms.TextMessage;
import javax.naming.NamingException;

public class TestJMSQueue {

public static void main(String[] args) {
TestJMSQueue testApp = new TestJMSQueue();
testApp.post2Queue();
testApp.receiveFromQueue();
}

public void post2Queue() {
long l1 = System.currentTimeMillis();
javax.naming.Context jndiContext = null;
javax.jms.QueueConnectionFactory queueConnectionFactory = null;
javax.jms.QueueConnection queueConnection = null;
javax.jms.QueueSession queueSession = null;
javax.jms.Queue queue = null;
javax.jms.QueueSender queueSender = null;

javax.jms.TextMessage message = null;

java.util.Hashtable<String, String> env = new java.util.Hashtable<String, String>();
env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
env.put(javax.naming.Context.PROVIDER_URL, "t3://localhost:7001");
env.put("weblogic.jndi.createIntermediateContexts", "true");

try {
jndiContext = new javax.naming.InitialContext(env);
} catch (NamingException e) {
System.out.println("Unable to create JNDI context "+e.toString());
e.printStackTrace();
}

try {
//queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("javax.jms.QueueConnectionFactory");
queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("jms/CustomerApplicationJMSConnectionFactory");
queue = (Queue) jndiContext.lookup("jms/CustomerApplicationRequestQueue");
} catch (NamingException e) {
System.out.println("JNDI lookup failed: " + e.toString());
e.printStackTrace();
}

try {
queueConnection = queueConnectionFactory.createQueueConnection();
queueSession = queueConnection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
queueSender = queueSession.createSender(queue);
long l2 = System.currentTimeMillis();
//for(int i=0; i<1000; i++) {
message = queueSession.createTextMessage("Hello There 1");
queueSender.send(message);
//}
long l3 = System.currentTimeMillis();

System.out.println("Time Taken for setup and due diligence: "+(l2 - l1));
System.out.println("Time taken to send 1 million messages: "+(l3 -l2));
System.out.println("Overall Time taken: "+(l3 - l1));

} catch (JMSException e) {
System.out.println("Exception occurred: " + e.toString());
e.printStackTrace();
} finally {
if(queueConnection != null) {
try {
queueConnection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}

}

Common JAVA framework to invoke the Oracle SOA Suite Composite services

Common JAVA framework to invoke the Oracle SOA Suite Composite services:

There are different approaches to invoke the SOA Composites through java like DirectConnection, ADFBinding etc. But in both the approaches we have to add the additional configurations in the Composite.xml file.
Instead of using this approach, we can use the Apache Axis framework to invoke all the composites as a webservice.
We have implemented a Service Invocation Framework to invoke the composites through JAVA.
We have to set the endpoint and the operation name correspondingly to invoke the service.
I thought of sharing the framework as this may help somebody looking for same kind of framework.
Sample Client to Invoke the service(download the framework attached):
String endpoint="http://soahost:soaport/soa-infra/services/default/HelloWorld/helloworld_client_ep";

String xmlInput="<ns1:process xmlns:ns1=\"http://xmlns.oracle.com/EAIRules/HelloWorld/HelloWorld\">\n" +
" <ns1:input>Albin Issac</ns1:input>\n" +
" </ns1:process>";

InputObject inputParamObj = new InputObject();
System.out.println("End pint URL " +endpoint );
inputParamObj.setSServiceEndPoint(endpoint);
inputParamObj.setSOprName("sayHello");
inputParamObj.setInputPayload(xmlInput);
// Getting service invoker class to invoke service.
ServiceInvoker serviceInvoker =ServiceInvoker.getInstance();
try {
serviceInvoker.invokeService(inputParamObj, null);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Process Successfully Invoked!<br>");

DOWNLOAD WebServiceInvocationFramework.zip

Monday, November 28, 2011

Oracle SOA Suite – Local optimization for webservice calls

Oracle SOA Suite – Local optimization for webservice calls:

The property “oracle.webservices.local.optimization” instructs Composite to make the webservice calls via SOAP stack or not. This property will work both in Oracle SOA Suite 11g and Oracle SOA Suite 12c.
By default the value for the property “oracle.webservices.local.optimization” is true. If the value is true and composite invokes any other webservice on the same server/domain, it avoids soap overhead and calls natively.

There may be a situation that you want to invoke the services via Soap Stack and changing the value of “oracle.webservices.local.optimization” property to false will help us to do that.
We can set this property in Composite.xml for a specific partner link only that partner link invocation always happens via soap stack.
Open the Composite.xml in JDev and add the property - oracle.webservices.local.optimization to the corresponding partnerlink binding.



When the local optimization is true, the policies attached to the partnerlinks are also bypassed

Friday, November 25, 2011

Some of the utilities used for the Oracle SOA Suite 10g to 11g Migration.

Some of the utilities used for the Oracle SOA Suite 10g to 11g Migration.

I thought of sharing the pre and post migration utilities, we had used in our project.
Hope this may help somebody looking for the migration utilities.

Pre-Migration:

The below java program helps us to remove the space in the preference name(bpel file and bpel.xml) used in 10g code base before starting the migration, the migration will fails if there is any empty spaces in the preference name.

MigrationTask.java
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
public class MigrationTask {
public MigrationTask() { }
static FilenameFilter filterPreferences = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.equals("bpel.xml");
}
};
static FilenameFilter bpelProcess = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.matches(".*.bpel");
}
};

//Remove the empty spaces in the preference name in bpel.xml and
//chanage corresponding preference name in bpel file
public static void updatePreferences(String baseDir) throws Exception {
File[] fileList =
listFilesAsArray(new File(baseDir), filterPreferences, true);
for (int i = 0; i < fileList.length; i++) {
DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
File f = fileList[i];
String fileName = f.getAbsolutePath();
// System.out.println(fileName);
Document document =
docBuilderFactory.newDocumentBuilder().parse(fileName);
String bpelFolder =
fileName.substring(0, fileName.lastIndexOf("\\"));
NodeList nodeList =
executeXPath(document, "//preferences/property");
File[] fileListBpel =
listFilesAsArray(new File(bpelFolder), bpelProcess, false);
for (int j = 0; j < nodeList.getLength(); j++) {
Node node =
nodeList.item(j).getAttributes().getNamedItem("name");
String preferenceValue = node.getNodeValue();
if (isSpaceAvilable(preferenceValue) &&
fileListBpel.length > 0) {
System.out.println(fileListBpel[0].getName());
String newpreferenceValue =
preferenceValue.replaceAll(" ", "");
node.setNodeValue(newpreferenceValue);
replaceStringInFile(fileListBpel[0], preferenceValue,
newpreferenceValue, "Pre");
}
}
Source source = new DOMSource(document);
File file = new File(fileList[i].getAbsolutePath());
Result result = new StreamResult(file);
Transformer xformer =
TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
xformer.transform(source, result);
}
}
public static NodeList executeXPath(Document doc, String xpathStr) {
XPath xpath = null;
NodeList value = null;
try {
XPathFactory xpathFactory = XPathFactory.newInstance();
xpath = xpathFactory.newXPath();
XPathExpression expr = xpath.compile(xpathStr);
value = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
return value;
} catch (XPathExpressionException e) {
System.err.println("Exception while processing xpath ::" +
e.getMessage());
} catch (Exception e) {
System.err.println("Exception while processing xpath ::" +
e.getMessage());
}
return null;
}
public static boolean isSpaceAvilable(String preference) {
return preference.contains(" ");
}
public static void main(String[] args) throws Exception {
if (args[1].equals("updatePreferences")) {
updatePreferences(args[0]);
}
}
public static File[] listFilesAsArray(File directory,
FilenameFilter filter,
boolean recurse) throws Exception {
Collection<File> files = listFiles(directory, filter, recurse);
File[] arr = new File[files.size()];
return files.toArray(arr);
}
public static Collection<File> listFiles(File directory,
FilenameFilter filter,
boolean recurse) throws Exception {
Vector<File> files = new Vector<File>();
File[] entries = directory.listFiles();
for (File entry : entries) {
if (filter == null || filter.accept(directory, entry.getName())) {
files.add(entry);
}
if (recurse && entry.isDirectory()) {
files.addAll(listFiles(entry, filter, recurse));
}
}
return files;
}
public static void replaceStringInFile(File file, String searchText,
String replaceText,
String replacementtype) {
try {
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String fileName = file.getAbsolutePath();
String strLine;
StringBuffer sb = new StringBuffer();
while ((strLine = br.readLine()) != null) {
// if(strLine.contains(searchText)){
Pattern p = Pattern.compile(searchText);
Matcher m = p.matcher(strLine);
if (m.find()) {
strLine = strLine.replace(searchText, replaceText);
}
sb.append(strLine);
sb.append("\n");
}
in.close();
FileOutputStream fos = new FileOutputStream(fileName);
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
String outText = sb.toString();
out.write(outText);
out.close();
} catch (Exception e) { //Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

java MigrationTask <10g codebase location > updatePreferences

Thursday, November 24, 2011

Oracle SOA Suite – Purging the Xref Data through JAVA API.

Oracle SOA Suite  – Purging the Xref Data through JAVA API.

The Oracle SOA Suite 11g and Oracle SOA Suite 12cprovides the Java API’s that can be used to purge the Xref Data.

The client API provides the Locator class to purge the Xref Data based on the filter.

locator.purgeXRefData(XRefPurgeFilter purgeFilter);

The XRefPurgeFilter class is used to set the filter condition to purge the Xref Data.

XRefPurgeFilter purgeFilter =new XRefPurgeFilter();

purgeFilter.setPurgeXRefTableURI ("oramds:/apps/EAIMetaData/Xref/Test.xref");

Specify the Xref Table for which data needs to be purged. If no column names are provided, all data for that XRef Table would be purged.

purgeFilter.setPurgeXRefTableURI – Can be used only combination with purgeFilter.addColumnToPurge, 

if we are using purgeFilter.setPurgeXRefTableURI with other filter conditions like purgeFilter.setPurgeDataBefore, we would receive the following error.

EJB Exception: ; nested exception is: java.lang.RuntimeException: oracle.tip.xref.exception.RepositoryException: Unable to access Cross Reference Values from Database.The SQL Exception is: "ORA-00933: SQL command not properly ended " Please ensure that the database is accessible. If accessible, please look at the stack trace and fix the issue. If unable to fix contact Oracle Support Fetching Data...

purgeFilter.addColumnToPurge("ColumnA");
Add column names for specified XRef Table whose column data would be purged. 

If we are using purgeFilter.addColumnToPurge with any other filter condition other than purgeFilter.setPurgeXRefTableURI would be ignored.

purgeFilter.setPurgeDataBefore(purgeDataAfter);
Last modified date before which all data in the database would be purged.

purgeFilter.setPurgeAllData(true);
All data in the database would be purged

purgeFilter.setPurgeDataAfter(purgeDataAfter);
Last modified date after which all data in the database would be purged.

The following code snippet will enable you to purge the Xref Data based on the filter condition.

Jar File required - <JDEV_HOME>\soa\modules\oracle.soa.mgmt_11.1.1\soa-infra-mgmt.jar

try
{
Hashtable jndiProps = new Hashtable();
jndiProps.put(Context.PROVIDER_URL,"t3://soahost:soaport");
jndiProps.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
jndiProps.put(Context.SECURITY_PRINCIPAL,"weblogic");
jndiProps.put(Context.SECURITY_CREDENTIALS,"xxxxxx");
jndiProps.put("dedicated.connection","true");
Locator locator = LocatorFactory.createLocator(jndiProps);
java.util.Date purgeData=new Date(2011,11,24);

XRefPurgeFilter purgeFilter =new XRefPurgeFilter();
purgeFilter.setPurgeXRefTableURI("oramds:/apps/EAIMetaData/Xref/Test.xref");
// purgeFilter.addColumnToPurge("ColumnA");
//purgeFilter.setPurgeDataBefore(purgeData);
//purgeFilter.setPurgeDataAfter(purgeData);
// purgeFilter.setPurgeAllData(true);
locator.purgeXRefData(purgeFilter);
}catch(Exception e)
{
e.printStackTrace();
}

Wednesday, November 23, 2011

Business Rule issue while migrating from Oracle SOA Suite 10g to Oracle SOA Suite 11g - Compilation errors with rule facts classes having long qualified package name.

Business Rule issue while migrating from Oracle SOA Suite 10g to Oracle SOA Suite 11g - Compilation errors with rule facts classes having long qualified package name.

If we had used the long qualified package name with rule facts classes (mainly with XML facts)e.g. “com.xxxxxxx.ns._2007._01._25.gcap.eai.ordermanagement” in 10g Business rule ,we will be receiving the below error during the compilation of the composite with the migrated rule in 11g.



[scac] error: location {/ns:composite/ns:import[@location='file:/D:/Albin/EAI/DevCodeBase/11g_Migration/CRM_EAI_code_deploy/code/OrderRequestRule/OrderRequestRule/OrderLineRequestDictionary141008_DecisionService_1.wsdl']}: Load of wsdl "OrderLineRequestDictionary141008_DecisionService_1.wsdl with Message part element undefined in wsdl [file:/D:/Albin/EAI/DevCodeBase/11g_Migration/CRM_EAI_code_deploy/code/OrderRequestRule/OrderRequestRule/OrderLineRequestDictionary141008_DecisionService_1.wsdl] part name = payload type = {http://xmlns.oracle.com/OrderLineRequestDictionary141008/OrderLineRequestDictionary141008_DecisionService_1}callFunctionStatelessDecision" failed
[scac] error: location {OrderLineRequestDictionary141008}: Rule Dictionary OrderLineRequestDictionary141008 is invalid.
[scac] error: location {OrderLineRequestDictionary141008}: Function OrderLineRequestDictionary141008.Version1_1.OrderLineRequestDictionary141008.OrderLineRequestDictionary141008_DecisionService_1 does not exist in rule dictionary

The rule facts need to be recreated with the shorter package name to overcome this compilation error.

The below are the steps to recreate the rule facts from XSD:

1. Remove all the XML facts - Open the rule dictionary and remove all the facts available.


Sunday, November 20, 2011

Migrating the WEBDAV Business Rule Repository from Oracle SOA Suite 10g to Oracle SOA Suite 11g format and exposing the rules as a webservice.


Migrating the WEBDAV Business Rule Repository from Oracle SOA Suite 10g to Oracle SOA Suite 11g format and exposing the rules as a webservice.

If we had used the Business Rule in 10g the same should be migrated to 11g.The below are the steps to migrate the sample webdav rule repository from 10g to 11g and to expose the rule dictionary as a service.
  1. Create a folder Rules with child folders “jaxboutput” and “xsd”.
  1. Copy the xsd files used in 10g to build the Input/output of rule to xsd folder.
  1. Crete a java file “RuleMigrator.java” with the below contents.
import java.io.PrintWriter;
import java.util.ArrayList;
import oracle.rules.tools.migrator.MigrateRuleRepository;
public class RuleMigrator {
public RuleMigrator() {
super();
}
public static void migrateRule() throws Exception{
String parent_output_dir=System.getenv("rule.output.path");
MigrateRuleRepository conv = new MigrateRuleRepository();
// Set the output buffer
conv.setOutLog(new PrintWriter(System.out));
// Set input properties (SDK format)
conv.setOriginLocation(System.getenv("rule.repository.location"));
conv.setXSDOutputDir(parent_output_dir+"\\jaxboutput");
conv.setOriginType(MigrateRuleRepository.WEBDAV_REPO);
conv.setOriginUserid(System.getenv("rule.repository.username"));
conv.setOriginPassword(System.getenv("rule.repository.password"));
conv.setOriginDictionaryName(MigrateRuleRepository.MIGRATE_ALL);
conv.setOriginVersionName(MigrateRuleRepository.MIGRATE_ALL);
conv.setLogWithStackTrace(true);
conv.setXSDLocation(parent_output_dir+"\\xsd");
// Set output properties
conv.setDestinationLocation(current_dir+"\\Rules");
System.out.println("Before calling migrate");
conv.migrate();
String results = conv.getTotalStats();
System.out.print(results);
}
public static void main(String[] args) {
try
{
migrateRule();
}catch(Exception e) {
e.printStackTrace();
}
}
}