Tuesday, May 12, 2009

Mule2.x - expression-recipient-list-router – Dynamic Endpoint in mule

Mule2.x - expression-recipient-list-router – Dynamic Endpoint in mule

The expression recipient list router can be used to send the same message to multiple endpoints over the same endpoint or to implement routing-slip behavior where the next destination for the message is determined from message properties or the payload. It uses a list of recipient’s endpoints which are extracted from the message using an expression.

Here I will give you an example how to use the expression-recipient-list-router.

In this example I am using mule 2.2. (http://www.mulesource.org)


Mule-config.xml

Spring declaration
<spring:bean id="ExpressionHandlerBean"
class="com.javatch.expression.ExpressionHandlerBean">

actual mule configuration
<model name="test Expression">
<service name="Expression">
<inbound>
<vm:inbound-endpoint address="vm://Expression" synchronous="true" >
</vm:inbound-endpoint>
</inbound>
<component>
<spring-object bean="ExpressionHandlerBean"></spring-object>
</component>
<outbound>
<expression-recipient-list-router evaluator="header"
expression="ADDR_LIST" >
</expression-recipient-list-router>
</outbound>
</service>

<service name="TEST">
<inbound>
<vm:inbound-endpoint address="vm://TEST" synchronous="true" />
</inbound>
<outbound>
<pass-through-router>
<file:outbound-endpoint path="${some temp dir}"
transformer-refs="ValidateTheFlow" />
</pass-through-router>
</outbound>
</service>
</model>





In the component class I am adding the endpoint, here if you can any number endpoint ExpressionRecipientList.java (from Mule) will take care of functional flow. 

ExpressionHandlerBean.java

public class ExpressionHandlerBean implements Callable {

public Object onCall(MuleEventContext eventContext) throws Exception {
try {
List<String> addressList = new ArrayList<String>();
addressList.add("vm://TEST");
eventContext.getMessage().setProperty("ADDR_LIST",addressList);
}
catch( Exception ex ) {
ex.printStackTrace();
}
return null;
}

}

Friday, May 1, 2009

Setting up EhCache using Spring

Setting up EhCache using Spring

Ehcache is a pure Java cache with the following features: fast, simple, small foot print, minimal dependencies, provides memory and disk stores for scalability into gigabytes, scalable to hundreds of caches are a pluggable cache for Hibernate.

Here I am going to explain how to integrate ehcache with spring.

Following jar files are required in the class path in order to run this application J
ehcache-1.6.0-beta3.jar
spring-2.5.5.jar

We use ehcache.xml to configure all cache related information.


<ehcache>
<diskStore path="java.io.tmpdir"/>
<cache name="javatchEhcache"
maxElementsInMemory="1000"
eternal="true"
overflowToDisk="false"/>
<defaultCache
maxElementsInMemory="200"
maxElementsOnDisk="500"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"/>
</ehcache>

Back to spring configuration, we have to configure ehcache dependencies in to spring.

beans.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="ecManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml" />
</bean>

<bean id="mycache" class=" com.javatch.ehcache.example.EhCacheManager" init-method="setupCache">
<property name="cacheManager" ref="ecManager"/>
</bean>

</beans>

Create ehcache reference from java
EhCacheManager.java
package com.javatch.ehcache.example;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class EhCacheManager {

private CacheManager cacheManager;
private static Cache myCache = null;

public void setCacheManager(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}

private void setupCache() {
String cacheName = "javatchEhcache";
System.out.println("cache Name [" + cacheName + "]");
myCache = cacheManager.getCache(cacheName);
}

private static Element getValues(String key){
Element value = myCache.get(key);
if(value!=null) {
System.out.println("from cache");
return value;
} else {
// DAO call goes here...
myCache.put(new Element(key, "Object"));
System.out.println("not from cache");
}
return value;
}
private static void setValuesIntoCache(){
myCache.put(new Element("OS", "OSCache"));
myCache.put(new Element("OD", "OracleDBCache"));
}
public static void main(String[] args) {

BeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
System.out.println(factory.getBean("mycache"));
setValuesIntoCache();
getValues("NB");

}

}

Thank you 

Tuesday, April 14, 2009

MTOM (Message Transmission Optimization Mechanism)

MTOM (Message Transmission Optimization Mechanism)

MTOM allows send and receives attachments (such as document, pdf and images) efficiently and in an interoperable manner. It uses XOP (XML-binary Optimized Packaging) to transmit binary data (attachments like PDF, Doc and images etc)


Advantage of MTOM:

Base64Binary encoded data bloats the attachment by ~33%. MTOM converts the Base64Binary data to raw bytes over MIME, thus reducing the wire foot-print for transmission. The reciever can optinally convert the raw bytes back to Base64Binary encoding.


MTOM Process

The Consumer application begins by sending a SOAP Message that contains complex data in Base64Binary encoded format. Base64Binary data type represents arbitrary data (e.g., Images, PDF files, Word Docs) in 65 textual characters that can be displayed as part of a SOAP Message element. For the Send SOAP Message Step 1 in the Figure above, a sample SOAP Body with Base64Binary encoded element


Next it tried convert the Base64Binary data to MIME data with an XML-binary Optimization Package (xop) content type.

A Simple MTOM using Apache CXF:

Server implementation:

package com.javatch.service;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import javax.activation.DataHandler;

import javax.jws.WebService;

import com.javatch.bean.Upload;

@WebService(endpointInterface = "com.javatch.service.MTOMServiceImpl",

serviceName = "MTOMService")

public class MTOMServiceImpl implements MTOMService {

public void uploadFile(Upload upload) {

DataHandler handler = upload.getFile();

try {

InputStream is = handler.getInputStream();

OutputStream os = new FileOutputStream(new File("c:\\"

+ upload.getFile()+"."+

upload.getExtn()));

byte[] buf = new byte[100000];

int len;

while ((len = is.read(buf)) > 0){

os.write(buf, 0, len);

}

is.close();

os.close();

System.out.println("File copied.");

} catch (IOException e) {

e.printStackTrace();

}

}

}

Service Interface:

@WebService

public interface MTOMService {

void uploadFile(@WebParam(name="upload") Upload upload);

}

Pojo:

package com.javatch.bean;

import javax.activation.DataHandler;

public class Upload

{

private String fileName;

private String extn;

private DataHandler file;

public String getFileName()

{

return this.fileName;

}

public void setFileName(String fileName)

{

this.fileName = fileName;

}

public DataHandler getFile()

{

return this.file;

}

public void setFile(DataHandler file)

{

this.file = file;

}

public String getExtn() {

return extn;

}

public void setExtn(String extn) {

this.extn = extn;

}

}

Cxf file:

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:jaxws="http://cxf.apache.org/jaxws"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://cxf.apache.org/jaxws

http://cxf.apache.org/schemas/jaxws.xsd">

<import resource="classpath:META-INF/cxf/cxf.xml" />

<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>

<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

<jaxws:endpoint id="uploadresume"

implementor="com.javatch.service.MTOMServiceImpl"

address="MTOMService">

<jaxws:properties>

<entry key="mtom-enabled" value="true"/>

jaxws:properties>

jaxws:endpoint>

beans>

The structure of application looks like this,

Webapps

--FileUpload

--WEB-INF

--classes

--com.javatch.bean

--Upload

--com.javatch.service

--MTOMService

--MTOMServiceImpl

--cxf.xml

--lib

--web.xml

We have to modify web.xml to include cxf with this application

Web.xml

xml version="1.0"?>

DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<display-name>ResumeUploaddisplay-name>

<context-param>

<param-name>contextConfigLocationparam-name>

<param-value>classpath:com/thea/service/cxf.xmlparam-value>

context-param>

<listener>

<listener-class>

org.springframework.web.context.ContextLoaderListener

listener-class>

listener>

<servlet>

<servlet-name>CXFServletservlet-name>

<servlet-class>

org.apache.cxf.transport.servlet.CXFServlet

servlet-class>

servlet>

<servlet-mapping>

<servlet-name>CXFServletservlet-name>

<url-pattern>/services/*url-pattern>

servlet-mapping>

web-app>

We are done with server files J

Client :

package com.javatch.client;

import java.io.File;

import java.util.HashMap;

import java.util.Map;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import org.apache.cxf.interceptor.LoggingInInterceptor;

import org.apache.cxf.interceptor.LoggingOutInterceptor;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import com.javatch.bean.Upload;

import com.javatch.service.MTOMService;

public final class Client {

private Client() {

}

public static void main(String args[]) throws Exception {

Map props = new HashMap();

props.put("mtom-enabled", Boolean.TRUE);

JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

factory.setProperties(props);

factory.getInInterceptors().add(new LoggingInInterceptor());

factory.getOutInterceptors().add(new LoggingOutInterceptor());

factory.setServiceClass(MTOMService.class);

factory.setAddress

("http://localhost:8081/resumeupload/services/UploadResumeWS");

MTOMService client = (MTOMService) factory.create();

Upload upload=new Upload();

upload.setFileName("EnterpriseAOP_Free-seminar_July_2006");

upload.setExtn("pdf");

DataSource source = new FileDataSource(new File("C: \\EnterpriseAOP_Free-seminar_July_2006.pdf"));

upload.setFile(new DataHandler(source));

client.uploadFile(upload);

System.exit(0);

}

}

Copy FileUpload folder in to the webapps directory and restart the server.

Now use the client code to test the application.

Saturday, December 6, 2008

Parse and replace the XML elements using java

This example helps to find the xml tag values and replace with new values at runtime

Prerequisites

Following jar files are required in the class path in order to run this application J

1)      xalan-2.6.0.jar

2)      xercesImpl.jar

3)      example.xml

In this example I am using java 1.6

 

Example.xml

<Request xmlns="http://javatch.blogspot.com">

      <Details>

      <name>James</name>

      <pin>9901260200041906233</pin>

      <contact>1234567890</contact>

      </Details>

      <Details>

      <name>Bill</name>

      <pin>7701260200041906244</pin>

      <contact>0987654321</contact>

      </Details>

</Request>

 

This java application tries to find out the <pin> element from xml and replace with new value to this element

package com.javatch.xml;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.io.StringWriter;

import java.util.Iterator;

import java.util.Random;

import javax.xml.namespace.NamespaceContext;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.xml.serialize.XMLSerializer;

import org.apache.xpath.XPathAPI;

import org.w3c.dom.Document;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

import com.sun.org.apache.xml.internal.utils.PrefixResolver;

import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault;

 

public class XMLUpdate {

     

      InputStream stream = null;

      DocumentBuilderFactory xmlFact = null;

      DocumentBuilder builder = null;

      Document doc = null;

      NamespaceContext ctx = null;

     

      public XMLUpdate() {

                  initialization();

 

      }

      private void initialization(){

            try {

      stream = new FileInputStream(new File("example.xml"));

            if(stream == null) {

                  System.out.println("Cannot find xml file" + "example.xml");

                  return;

            }

        xmlFact = DocumentBuilderFactory.newInstance();

        xmlFact.setNamespaceAware(false);

        builder = xmlFact.newDocumentBuilder();

        doc = builder.parse(stream);

        // following declaring is required if there is any namespace in your xml

        final PrefixResolver resolver = new PrefixResolverDefault(doc.getDocumentElement());

              ctx = new NamespaceContext() {

                  public String getNamespaceURI(String prefix) {

                      return resolver.getNamespaceForPrefix(prefix);

                  }

                  public Iterator getPrefixes(String val) {

                      return null;

                  }

                  // Dummy implemenation - not used!

                  public String getPrefix(String uri) {

                      return null;

                  }

              };

            }catch(ParserConfigurationException pce) {

                 

            } catch (FileNotFoundException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

            } catch (SAXException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

            } catch (IOException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

            }

      }

      private void xmlTagValueReplace(){

        try {

            String xpathStr = "/Request/Details/pin";

            NodeList nodes =  XPathAPI.selectNodeList(doc, xpathStr);

            for(int i=0; i<nodes.getLength(); i++) {

                  nodes.item(i).setTextContent((new Random().nextInt())+"");

            }

                StringWriter stringOut = new StringWriter ();

                XMLSerializer serial = new XMLSerializer();

                serial.setOutputCharStream(stringOut);

                serial.serialize(doc);

                System.out.println(stringOut.toString());

        }catch (Exception ex) {

                ex.printStackTrace();

        }

      }

      public static void main(String args[]) {

                  XMLUpdate update = new XMLUpdate();

                  update.xmlTagValueReplace();

      }

 

}