Wednesday, May 30, 2012

Some handy JSF utility methods

Some handy JSF utility methods:

import java.io.*;
import java.text.*;
import java.util.*;
import javax.faces.application.*;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;

import javax.servlet.http.HttpSession;
import oracle.adf.view.faces.model.UploadedFile;


public class JSFUtils {

    private static final String NO_RESOURCE_FOUND = "Missing resource: ";

    /**
       * Method for taking a reference to a JSF binding expression and returning
       * the matching object (or creating it)     
       */
    public static Object resolveExpression(FacesContext ctx,
                                           String expression) {
        Application app = ctx.getApplication();
        ValueBinding bind = app.createValueBinding(expression);
        return bind.getValue(ctx);
    }

    /**
       * Convenience method for resolving a reference to a managed bean by name
       * rather than by expression
       */
    public static Object getManagedBeanValue(FacesContext ctx,
                                             String beanName) {
        StringBuffer buff = new StringBuffer("#{");
        buff.append(beanName);
        buff.append("}");
        return resolveExpression(ctx, buff.toString());
    }

    /**
       * Method for setting a new object into a JSF managed bean
       * Note: will fail silently if the supplied object does
       * not match the type of the managed bean
      */
    public static void setExpressionValue(FacesContext ctx, String expression,
                                          Object newValue) {
        Application app = ctx.getApplication();
        ValueBinding bind = app.createValueBinding(expression);
       
        Class bindClass = bind.getType(ctx);
        if (bindClass.isPrimitive()||bindClass.isInstance(newValue)) {
            bind.setValue(ctx, newValue);
        }
    }

    /**
       * Convenience method for setting the value of a managed bean by name
       * rather than by expression
       */
    public static void setManagedBeanValue(FacesContext ctx, String beanName,
                                           Object newValue) {
        StringBuffer buff = new StringBuffer("#{");
        buff.append(beanName);
        buff.append("}");
        setExpressionValue(ctx, buff.toString(), newValue);
    }


    /**
       * Convenience method for setting Session variables
      */
    public static

    void storeOnSession(FacesContext ctx, String key, Object object) {
        Map sessionState = ctx.getExternalContext().getSessionMap();
        sessionState.put(key, object);
    }

    /**
       * Convenience method for getting Session variables
      */
    public static Object getFromSession(FacesContext ctx, String key) {
        Map sessionState = ctx.getExternalContext().getSessionMap();
        return sessionState.get(key);
    }


    /**
       * Pulls a String resource from the property bundle that
       * is defined under the application <message-bundle> element in
       * the faces config. Respects Locale
       */
    public static String getStringFromBundle(String key) {
        ResourceBundle bundle = getBundle();
        return getStringSafely(bundle, key, null);
    }


    /**
       * Convenience method to construct a <code>FacesMesssage</code>
       * from a defined error key and severity
      */
    public static FacesMessage getMessageFromBundle(String key,
                                                    FacesMessage.Severity severity) {
        ResourceBundle bundle = getBundle();
        String summary = getStringSafely(bundle, key, null);
        String detail = getStringSafely(bundle, key + "_detail", summary);
        FacesMessage message = new FacesMessage(summary, detail);
        message.setSeverity(severity);
        return message;
    }

    /*
       * Internal method to pull out the correct local
       * message bundle
       */

    private static ResourceBundle getBundle() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        UIViewRoot uiRoot = ctx.getViewRoot();
        Locale locale = uiRoot.getLocale();
        ClassLoader ldr = Thread.currentThread().getContextClassLoader();
        return ResourceBundle
        .getBundle(ctx.getApplication().getMessageBundle(), locale, ldr);
    }

    /*
       * Internal method to proxy for resource keys that don't exist
       */

    private static String getStringSafely(ResourceBundle bundle, String key,
                                          String defaultValue) {
        String resource = null;                                         
        try {                                         
            resource = bundle.getString(key);
        }
        catch (MissingResourceException mrex) {
            if (defaultValue != null) {
                resource = defaultValue;
            } else {
                resource = NO_RESOURCE_FOUND + key;
            }
        }
        return resource;
    }
    /**
     *
     * @param msg
     */
    public static void addFacesErrorMessage(String msg) {
        FacesContext ctx = getFacesContext();
        FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR,msg,null);
        ctx.addMessage(getRootViewComponentId(),fm);
      }
      /**
     *
     * @return
     */
    public static FacesContext getFacesContext() {
         return FacesContext.getCurrentInstance();
       }
       /**
     *
     * @return
     */
    public static String getRootViewComponentId() {
         return getFacesContext().getViewRoot().getId();
       } 
       /**
     *
     * @param beanname
     * @return
     */
       public static Object getBeanByName(String beanname) {
           FacesContext ctx = getFacesContext();
           Application app = ctx.getApplication();    
           return app.getVariableResolver().resolveVariable(ctx,beanname);
       }
      
      
      
     
    public static void  addValuesToSession(String key,String value) {
   
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        session.setAttribute(key, value);
       
    }
   
 
}



Some handy utility methods for XPath

Some handy utility methods for XPath:

import com.collaxa.cube.xml.xpath.SimpleNamespaceContext;
import java.util.*;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.*;
import oracle.bpel.services.common.util.XMLUtil;
import oracle.tip.pc.infra.exception.PCException;

import oracle.xml.xpath.JXPathFactory;
import org.w3c.dom.*;

    public class XPathUtils
{

    public XPathUtils()
    {
    }

    public static NodeList selectNodes(Element pElement, String xpathExpression)
        throws Exception
    {
        XPath xPath = createXPath();
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        NodeList value = (NodeList)xPath.evaluate(xpathExpression, doc, XPathConstants.NODESET);
        return value;
    }

    public static NodeList selectNodes(Element pElement, String xpathExpression, Map prefixNamespaceMapping)
        throws Exception
    {
        XPath xPath = createXPath(prefixNamespaceMapping);
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        NodeList value = (NodeList)xPath.evaluate(xpathExpression, doc, XPathConstants.NODESET);
        return value;
    }

    public static NodeList selectNodes(Element pElement, String xpathExpression, NamespaceContext namespaceContext)
        throws Exception
    {
        XPath xPath = createXPath(namespaceContext);
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        NodeList value = (NodeList)xPath.evaluate(xpathExpression, doc, XPathConstants.NODESET);
        return value;
    }

    public static Object evaluate(Element pElement, String xpathExpression)
        throws Exception
    {
        XPath xPath = createXPath();
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Object value = xPath.evaluate(xpathExpression, doc, XPathConstants.NODESET);
        return value;
    }

    public static Object evaluate(Element pElement, String xpathExpression, Map prefixNamespaceMapping)
        throws Exception
    {
        XPath xPath = createXPath(prefixNamespaceMapping);
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Object value = xPath.evaluate(xpathExpression, doc, XPathConstants.NODESET);
        return value;
    }

    public static Object selectSingleNode(Element pElement, String xpathExpression)
        throws Exception
    {
        XPath xPath = createXPath();
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Node value = (Node)xPath.evaluate(xpathExpression, doc, XPathConstants.NODE);
        return value;
    }

    public static Object selectSingleNode(Element pElement, String xpathExpression, Map prefixNamespaceMapping)
        throws Exception
    {
        XPath xPath = createXPath(prefixNamespaceMapping);
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Node value = (Node)xPath.evaluate(xpathExpression, doc, XPathConstants.NODE);
        return value;
    }

    public static String valueOf(Element pElement, String xpathExpression)
        throws Exception
    {
        XPath xPath = createXPath();
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
           
        String value = (String)xPath.evaluate(xpathExpression, doc, XPathConstants.STRING);
        return value;
    }

    public static String valueOf(Element pElement, String xpathExpression, Map prefixNamespaceMapping)
        throws Exception
    {
        XPath xPath = createXPath(prefixNamespaceMapping);
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        String value = (String)xPath.evaluate(xpathExpression, doc, XPathConstants.STRING);
        return value;
    }

    public static Number numberValueOf(Element pElement, String xpathExpression)
        throws Exception
    {
        XPath xPath = createXPath();
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Number nValue = (Number)xPath.evaluate(xpathExpression, doc, XPathConstants.NUMBER);
        return nValue;
    }

    public static Number numberValueOf(Element pElement, String xpathExpression, Map prefixNamespaceMapping)
        throws Exception
    {
        XPath xPath = createXPath(prefixNamespaceMapping);
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Number nValue = (Number)xPath.evaluate(xpathExpression, doc, XPathConstants.NUMBER);
        return nValue;
    }

    public static boolean booleanValueOf(Element pElement, String xpathExpression)
        throws Exception
    {
        XPath xPath = createXPath();
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Boolean bValue = (Boolean)xPath.evaluate(xpathExpression, doc, XPathConstants.BOOLEAN);
        return bValue.booleanValue();
    }

    public static boolean booleanValueOf(Element pElement, String xpathExpression, Map prefixNamespaceMapping)
        throws Exception
    {
        XPath xPath = createXPath(prefixNamespaceMapping);
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Boolean bValue = (Boolean)xPath.evaluate(xpathExpression, doc, XPathConstants.BOOLEAN);
        return bValue.booleanValue();
    }

    private static XPath createXPath()
        throws Exception
    {
        return getXPath(null);
    }

    private static XPath createXPath(NamespaceContext namespaceContext)
    {
        return getXPath(namespaceContext);
    }

    private static XPath createXPath(Map namespaceMapping)
    {
        XPath xpath = null;
        NamespaceContext nc = null;
        if(namespaceMapping != null)
        {
            if(namespaceMapping.containsKey(""))
                namespaceMapping.remove("");
            nc = new SimpleNamespaceContext(namespaceMapping);
        }
        xpath = getXPath(nc);
        return xpath;
    }

    public static XPath getXPath(NamespaceContext nsContext)
    {
        JXPathFactory xpfac = new JXPathFactory();
        XPath xpath = xpfac.newXPath();
        if(nsContext != null)
            xpath.setNamespaceContext(nsContext);
        return xpath;
    }
   
   
   public static  String getNodeValue(NodeList nodes) {
        Node node = nodes.item(0);
        String value = null;
        if(nodes.getLength()>0){
        NodeList children = node.getChildNodes();
        int length = children.getLength();
        if (length == 1) {
            Node textNode = children.item(0);
            value = textNode.getNodeValue();
        }
        }
        return value;
       
    }
   
   
   public static  int getNodeType(String xpath) {
        String lastPart = xpath.substring(xpath.lastIndexOf("/") + 1);
        return !lastPart.startsWith("@") ? 1 : 2;
    }
   
   public static  Node getNode(Element payload, String xpath,
                 Map nameSpaceMap) throws PCException {
        Node node = null;

        NodeList nodes;
        try {
            nodes = XPathUtils.selectNodes(XMLUtil.getDocumentElement(payload), xpath, nameSpaceMap);
        } catch (Exception e) {
            return null;
        }
        if (nodes == null || nodes.getLength() == 0)
            return null;
        if (nodes.getLength() == 1) {
            node = nodes.item(0);
        } else {
            Object obj[] = { xpath };
            throw new PCException(10175, obj);
        }

        return node;
    }
   
    public static Node appendChildNode(Element payload, Map nameSpaceMap, String xpath,
                        Node parentNode) throws PCException {
       if (parentNode == null) {
           Object obj[] = { xpath + "(cannot append to empty parent)" };
           throw new PCException(10175, obj);
       }
       short nodeType = (short)getNodeType(xpath);
       String lastPart = xpath.substring(xpath.lastIndexOf("/") + 1);
       if (lastPart.startsWith("@"))
           lastPart = lastPart.substring(1);
       int colon = lastPart.indexOf(58);
       String localNS = null;
       if (colon > 0)
           localNS = lastPart.substring(0, colon);
       String localName = lastPart.substring(colon + 1);
       Node node;
       if (nodeType == 2) {
           if (localNS == null)
               node = parentNode.getOwnerDocument().createAttribute(localName);
           else
               node = parentNode.getOwnerDocument().createAttributeNS((String)nameSpaceMap.get(localNS), localName);
       } else if (nodeType == 1) {
           if (localNS == null)
               node = parentNode.getOwnerDocument().createElement(localName);
           else
               node = parentNode.getOwnerDocument().createElementNS((String)nameSpaceMap.get(localNS),
                                             localName);
       } else {
           Object obj[] = { xpath + "(cannot determine node type)" };
           throw new PCException(10175, obj);
       }
       parentNode.appendChild(node);
       return node;
    }
   
    public static Map getNamespaces(Element rootElement) {
        NamedNodeMap attrs = rootElement.getFirstChild().getAttributes();
        int len = attrs.getLength();
        Hashtable namespaces = new Hashtable();
        namespaces.put("ns0", "http://xmlns.oracle.com/bpel/workflow/task");
        for (int i = 0; i < len; i++) {
            Node node = attrs.item(i);
            String name = node.getNodeName();
            if (name.startsWith("xmlns:ns")) {
                String key = name.substring(name.indexOf(":") + 1);
                namespaces.put(key, node.getNodeValue());
            }
        }

        return namespaces;
    }
   
    public static void setNodeValue(Element payload, Map namespacemap, String xpath,
                      String value) throws Exception {
        Node node = null;
        NodeList nodes = null;
        NodeList children =null;
        int length = 0;
        try {
            nodes = XPathUtils.selectNodes(XMLUtil.getDocumentElement(payload), xpath, namespacemap);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
       
        node = nodes.item(0);
       
        if(nodes.getLength()>0){
        children = node.getChildNodes();
        length = children.getLength();
       
       
        if (length == 1) {
            Node textNode = children.item(0);
            String oldValue = textNode.getNodeValue();               
            value=value==null?"":value;
            oldValue=oldValue==null?"":oldValue;
           
            if (!oldValue.equals(value)) {
                textNode.setNodeValue(value);
            }
        } else if (length == 0 && value != null && !value.equals("")) {
            Node valueNode = node.getOwnerDocument().createTextNode(value);
            node.appendChild(valueNode);
            }
        }
    }
    public static Node createNode(Element payload, Map nameSpaceMap,
                    String xpath) throws PCException {
        if (xpath == "/ns0:task/ns0:payload") {
            Object obj[] = { xpath };
            throw new PCException(10175, obj);
        }
        String parentXPath = xpath.substring(0, xpath.lastIndexOf("/"));
       
        Node parentNode = getNode(payload, parentXPath, nameSpaceMap);
        if (parentNode == null)
            parentNode = createNode(payload, nameSpaceMap, parentXPath);
        return appendChildNode(payload, nameSpaceMap, xpath, parentNode);
    }
   
    public static void removeNode(Element payload, String xpath,Map nameSpaceMap) throws Exception
    {
      NodeList nodes=null;
   
      try
      {
        nodes = XPathUtils.selectNodes(XMLUtil.getDocumentElement(payload), xpath, nameSpaceMap);      
        for(int i=0;i<nodes.getLength();i++)
        {
          nodes.item(i).getParentNode().removeChild(nodes.item(i)) ;
        }
      }
      catch (Exception e)
      {
        e.printStackTrace();
        throw e;
      }
    }
   
    public static boolean isNodePresent(Element payload, Map namespacemap, String xpath)
    {
        NodeList nodes = null;
        try {
            nodes = XPathUtils.selectNodes(XMLUtil.getDocumentElement(payload), xpath, namespacemap);
        } catch (Exception e) {
           e.printStackTrace();
        }
       
        if(nodes.getLength()==0)
          return false;  
        else
         return true;
    }
}



Tuesday, May 29, 2012

Update the Human task payload via JAVA API - Oracle SOA Suite 11g

Update the Human task payload via JAVA API - Oracle SOA Suite 11g:

Oracle SOA Suite 11g provides java API’s to manipulate the Human task data.The below java code will help us to update the Human task payload.

This is the Remote Java client  to get the Workflow service and perform the required operations on the task.

The XPath of the input element will be used to update the payload data.

UpdateWorkflowPayload.java

import java.util.*;
import oracle.bpel.services.workflow.IWorkflowConstants;
import oracle.bpel.services.workflow.client.*;
import oracle.bpel.services.workflow.query.ITaskQueryService;
import oracle.bpel.services.workflow.repos.*;
import oracle.bpel.services.workflow.task.ITaskService;
import oracle.bpel.services.workflow.task.model.Task;
import oracle.bpel.services.workflow.verification.IWorkflowContext;
import org.w3c.dom.Element;
public class UpdateWorkflowPayload {     
   public static void updatePayload()
    {
        List displayColumns = new ArrayList();
        displayColumns.add("TASKNUMBER");
        displayColumns.add("TITLE");
        displayColumns.add("STATE");
        displayColumns.add("CREATOR");
        List optionalInfo = new ArrayList();      
        optionalInfo.add("Comments");
        optionalInfo.add("Payload");      
    try {
              String userid="weblogic";
              String password = "password";       
              String serverUrl ="t3://localhost:8000"; // host:port of the soa server
              Map<IWorkflowServiceClientConstants.CONNECTION_PROPERTY, String> connProperties = new HashMap<IWorkflowServiceClientConstants.CONNECTION_PROPERTY, String>();              connProperties.put(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.CLIENT_TYPE,WorkflowServiceClientFactory.REMOTE_CLIENT);              connProperties.put(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.EJB_PROVIDER_URL,serverUrl);
              connProperties.put(IWorkflowServiceClientConstants.CONNECTION_PROPERTY.EJB_INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");       
              IWorkflowServiceClient wfSvcClient = WorkflowServiceClientFactory.getWorkflowServiceClient(connProperties, null, null);   
              IWorkflowContext ctx = wfSvcClient.getTaskQueryService().authenticate(userid, password.toCharArray(), "jazn.com" );
              ITaskQueryService querySvc = wfSvcClient.getTaskQueryService();
              ITaskService taskSvc = wfSvcClient.getTaskService();       
              Predicate statePredicate =new Predicate(TableConstants.WFTASK_STATE_COLUMN,Predicate.OP_EQ,IWorkflowConstants.TASK_STATE_ASSIGNED);
              Predicate compositenamePredicate = new Predicate(TableConstants.COMPONENT_COMPOSITE_NAME_COLUMN,Predicate.OP_EQ,"HumanWorkflow");
              Predicate predicate = new Predicate(statePredicate, Predicate.AND, compositenamePredicate);
            
       
              List tasks =querySvc.queryTasks(ctx, displayColumns, optionalInfo, ITaskQueryService.AssignmentFilter.MY,null, statePredicate, null, 0, 0);
              
              for (int i = 0; i < tasks.size(); i++) {
                       Task task = (Task)tasks.get(i);
                       String taskId = task.getSystemAttributes().getTaskId();                
                       String title = task.getTitle();
                       String state = task.getSystemAttributes().getState();
                       Task currentTask=querySvc.getTaskDetailsById(ctx,taskId);                   
                 
                       Element payload = currentTask.getPayloadAsElement();
                 
                       Map namespacemap = new HashMap();
                       namespacemap.put("ns0", "http://xmlns.oracle.com/bpel/workflow/task");
                                     
                       setPayloadValue(payload,"/ns0:task/ns0:payload/ns0:Name",namespacemap,"Albin Issac");
                       setPayloadValue(payload,"/ns0:task/ns0:payload/ns0:Number",namespacemap,"024");
                       setPayloadValue(payload,"/ns0:task/ns0:payload/ns0:Dep",namespacemap,"I.T");
                       setPayloadValue(payload,"/ns0:task/ns0:payload/ns0:Place",namespacemap,"KAMPLAR");
                 
                       currentTask.setPayloadAsElement(payload);    
                       taskSvc.updateTaskOutcome(ctx, currentTask,"APPROVE"); 
                 
                   }
                         
          } catch (Exception e) {
              e.printStackTrace();
          
          }
    }
  
   public static void setPayloadValue(Element payload,String xpath,Map namespacemap,String value) {
        try {
            XPathUtils.setNodeValue(payload, namespacemap, xpath,value);
        } catch (Exception e) {
        }
    }
   public static void main(String[] args) {
        updatePayload();
    }
}

XPathUtils.java
(To perform the XPath related operations)
import java.util.Map;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.*;
import oracle.bpel.services.common.util.XMLUtil;
import oracle.fabric.common.xml.xpath.SimpleNamespaceContext;
import org.w3c.dom.*;
public class XPathUtils {
    public static void setNodeValue(Element payload, Map namespacemap, String xpath,
                         String value) throws Exception {
           Node node = null;
           NodeList nodes = null;
           NodeList children =null;
           int length = 0;
           try {
               nodes = XPathUtils.selectNodes(XMLUtil.getDocumentElement(payload), xpath, namespacemap);
           } catch (Exception e) {
               e.printStackTrace();
               throw e;
           }
           node = nodes.item(0);          
           if(nodes.getLength()>0){
           children = node.getChildNodes();
           length = children.getLength();          
           if (length == 1) {
               Node textNode = children.item(0);
               String oldValue = textNode.getNodeValue();               
               value=value==null?"":value;
               oldValue=oldValue==null?"":oldValue;              
               if (!oldValue.equals(value)) {
                   textNode.setNodeValue(value);
               }
           } else if (length == 0 && value != null && !value.equals("")) {
               Node valueNode = node.getOwnerDocument().createTextNode(value);
               node.appendChild(valueNode);
               }
           }
       }
   
    public static NodeList selectNodes(Element pElement, String xpathExpression, Map prefixNamespaceMapping)  throws Exception {
           XPath xPath = createXPath(prefixNamespaceMapping);
           Document doc = null;
           if(pElement instanceof Document)
               doc = (Document)pElement;
           else
               doc = pElement != null ? pElement.getOwnerDocument() : null;
           NodeList value = (NodeList)xPath.evaluate(xpathExpression, doc, XPathConstants.NODESET);
           return value;
       }
    public static  String getNodeValue(NodeList nodes) {
         Node node = nodes.item(0);
         String value = null;
         if(nodes.getLength()>0){
         NodeList children = node.getChildNodes();
         int length = children.getLength();
         if (length == 1) {
             Node textNode = children.item(0);
             value = textNode.getNodeValue();
         }
         }
         return value;
        
     }     
    private static XPath createXPath(Map namespaceMapping)
      {
          XPath xpath = null;
          NamespaceContext nc = null;
          if(namespaceMapping != null)
          {
              if(namespaceMapping.containsKey(""))
                  namespaceMapping.remove("");
              nc = new SimpleNamespaceContext(namespaceMapping);
          }
          xpath = getXPath(nc);
          return xpath;
      }
   
    public static XPath getXPath(NamespaceContext nsContext)
        {
            XPath xpath = XPathFactory.newInstance().newXPath();
            if(nsContext != null)
                xpath.setNamespaceContext(nsContext);
            return xpath;
        }   
}

Jar Files Required:



O/P

Input Payload:




Updated payload:






Saturday, May 26, 2012

Exposing the BPEL process as a Http Service using HTTP Binding Adapter – Oracle SOA Suite 11g

Exposing the BPEL process as a Http Service using HTTP Binding Adapter – Oracle SOA Suite 11g:

By default the BPEL processes can be invoked via SOAP service, sometimes we may need to invoke the service from the HTTP client by using the HTTP methods – GET/POST

The HTTP Binding Adapter will help us to expose the BPEL process as an HTTP Service.

If we are exposing the service as a HTTP service, the marshaling/unmarshaling overhead related to soap can be avoided when the client invoke the service.

Steps to Expose the BPEL process as a HTTP Service:
  • Create a new SOA project with the Composite Template as Empty
  • Open the Composite.xml and Insert HTTP Binding Adapter to Exposed Services section.
  • Configure the Adapter
1.       Select the Interface Option as “Define from operation and schema specified later”
2.       Select the operation type, verb(HTTP Method) and payload type accordingly
3.       Provide the Request/Response Message Schema


 



  •  Insert a BPEL Component in the Components section and use the Define Service Later template.
  •  Make a wire between the Service and the BPEL component.



  • Open the BPEL component and add a Receive, Reply Activity and the required activities (create input/output variables before starting mappings) to finish the flow- Make sure the Create Instance Check box is selected in the Receive activity.
  • Connect the Receive/Reply activities to the client partner link.

 

  • To expose the service with both GET/POST http methods, remove the http.verb and http.payload properties configured in the Composite.xml


  •  Deploy the composite to the server and open the end point URL in browser to test the service.                                                                                                                                                  http://localhost:8000/soa-infra/services/default/HttpService/HttpBinding
 









Updating the BPEL Component preference value from JAVA – Oracle SOA Suite 11g

Updating the BPEL Component preference value from JAVA – Oracle SOA Suite 11g:

Sometimes we may need to update the preference value for the BPEL component, the below java code will help us to update the preference value.

This update is not a cluster-aware,remember that you must repeat the same process for each managed server of your environment.
Before executing the code change the mbeanName accordingly.

   String mBeanName ="*:*,j2eeType=SCAComposite.SCAComponent,revision=*,SCAComposite=\"Preference\",name=Preference";




import java.util.*;
import javax.management.*;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.remote.*;
import javax.naming.Context;

public class UpdatePreferenceValue {  

    public static MBeanServerConnection getMbeanServerConnection(String host,
                                                                 int port,
                                                                 String userName,
                                                                 String password) throws Exception {
        String jndiroot = "/jndi/";
        MBeanServerConnection m_connection = null;
        try {
            Hashtable jndiProps = new Hashtable();
            jndiProps.put(Context.SECURITY_PRINCIPAL, userName);
            jndiProps.put(Context.SECURITY_CREDENTIALS, password);
            jndiProps.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,"weblogic.management.remote");

            JMXServiceURL serviceURL =new JMXServiceURL("t3", host, port, jndiroot +"weblogic.management.mbeanservers.runtime");
            JMXConnector m_connector =JMXConnectorFactory.newJMXConnector(serviceURL, jndiProps);
            m_connector.connect();
            m_connection = m_connector.getMBeanServerConnection();

        } catch (Exception e) {

            e.printStackTrace();
        }
        return m_connection;
    }


    private static CompositeDataSupport UpdatePreferenceData(CompositeDataSupport cds,String[] keys,String[] newValues) throws Exception {
        Map<String, Object> items =new HashMap<String, Object>(cds.getCompositeType().keySet().size());

        for (String key : cds.getCompositeType().keySet()) {
            boolean matched = false;
            int i = 0;

            for (; i < keys.length; i++) {
                String searchKey = keys[i];

                if (searchKey.equalsIgnoreCase(key)) {
                    items.put(key, newValues[i]);
                    matched = true;
                    break;
                }
            }       

            if (!matched) {             
                    items.put(key, cds.get(key));
            }
         
        }
    

        return new CompositeDataSupport(cds.getCompositeType(), items);
    }
  
    public static void updatePreference(String host,String port,String userName,String password, String  preferenceName,String value) {
 
        String mBeanName ="*:*,j2eeType=SCAComposite.SCAComponent,revision=*,SCAComposite=\"Preference\",name=Preference";

        MBeanServerConnection mbsc;
        try {
            mbsc =getMbeanServerConnection(host, Integer.parseInt(port),userName,password);
            Set<ObjectName> mbeans=mbsc.queryNames(new ObjectName(mBeanName), null);
            ObjectName mbean=(ObjectName)mbeans.iterator().next();
           javax.management.openmbean.CompositeData[] properties =
               (javax.management.openmbean.CompositeData[])mbsc.getAttribute(mbean,"Properties");
         
            for (int i = 0; i < properties.length; i++) {
                CompositeDataSupport cds = (CompositeDataSupport)properties[i];

                if (preferenceName.equalsIgnoreCase((String)cds.get("name"))) {

                    properties[i] =UpdatePreferenceData((CompositeDataSupport)properties[i],new String[] { "value" },new String[] { value });
                    mbsc.setAttribute(mbean,new Attribute("Properties", properties));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   
    public static void main(String[] args) {
        updatePreference("localhost", "8000","weblogic", "password","preference.password","password");
        }
    }


Add the weblogic.jar file to the class.






Monday, May 21, 2012

Using Regular Expressions with Oracle BPEL


Using Regular Expressions with Oracle BPEL:

Sometimes we may have to validate the data based on the Regular Expressions.

xp20:matches() is a function which can be used to compare data with regular expressions. This function returns true when the input matches the given expression.

xp20:matches(intputString, regexPattern)
  • inputString - The input string
  • regexPattern - The regular expression pattern
Validation of numeric fields :-
xp20:matches(bpws:getVariableData('inputString'),'^[0-9]*$')=true()

Validation of alpha fields :-
xp20:matches(bpws:getVariableData('inputString'),'^[A-Za-z]*$')=true()

Validation for list of values:-
xp20:matches(bpws:getVariableData('inputString'),'^(A|B|C|D)$') =true()

The matches function returns true if inputString variable contains any one of these values (A, B, C, and D).

The expression can be replaced with other regular expressions for similar comparisons.



Contact Form

Name

Email *

Message *