Thursday, October 6, 2011

org.jasypt.exceptions.EncryptionOperationNotPossibleException

Many of us have come across this exception while using encryption in our functionality.

org.jasypt.exceptions.EncryptionOperationNotPossibleException: Encryption raised an excep tion. A possible cause is you are using strong encryption algorithms and you have not installed the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files in this Java Virtual Machine


Resolution:


As the exception indicates one need to install the latest JCE Policy Jar Files into your JAVA setup.

1. Download the JCE Policy jar files from the below location:

2. The zip file would contain two jar files (local_policy.jar and US_export_policy.jar). 

3. These jar files need to be placed under the following location:

%JAVA_HOME%\jre\lib\security\

Reference Link:

Monday, October 3, 2011

Mule - Expression Splitter Router

The following example is used to simulate the functionality of the expression-splitter-router in mule.

Java Classes:

Fruit:

package com.expressionsplitterrouter;

public abstract class Fruit {

    private String shape;

    public String getShape() {
        return shape;
    }

    public void setShape(String shape) {
        this.shape = shape;
    }

} 


Apple:

package com.expressionsplitterrouter;

public class Apple extends Fruit {

    private String type;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}


Banana:

package com.expressionsplitterrouter;

public class Banana extends Fruit {

    private String form;

    public String getForm() {
        return form;
    }

    public void setForm(String form) {
        this.form = form;
    }

}


FruitBowl:

package com.expressionsplitterrouter;

import java.util.ArrayList;
import java.util.List;

public class FruitBowl {

    private List<Fruit> fruit;

    public List<Fruit> getFruit() {
        return fruit;
    }

    public void setFruit(List<Fruit> fruit) {
        this.fruit = fruit;
    }
    
    public void addFruit(Fruit fruit){
        if (this.fruit == null) {
            this.fruit = new ArrayList<Fruit>();
        }
        this.fruit.add(fruit);
    }

} 


CreateFruitComponent:

package com.expressionsplitterrouter;

public class CreateFruitComponent {

    public FruitBowl createFruit(String start) {
        
        FruitBowl bowl = new FruitBowl();
        
        Apple apple = new Apple();
        apple.setShape("Round");
        apple.setType("Green");
        
        Banana banana = new Banana();
        banana.setShape("Lengthy");
        banana.setForm("Yellow");
        
        bowl.addFruit(apple);
        bowl.addFruit(banana);
        
        apple = new Apple();
        apple.setShape("Rectangular Square");
        apple.setType("Red");
        
        bowl.addFruit(apple);
        return bowl;
    }
} 


AppleComponent:

package com.expressionsplitterrouter;

public class AppleComponent {

    public void displayApple(Apple apple) {

        System.out.println("Apple Component");
        System.out.println(apple.getShape() + "," + apple.getType());
    }
} 


BananaComponent:

package com.expressionsplitterrouter;

public class BananaComponent {

    public void displayBanana(Banana banana) {

        System.out.println("BananaComponent");
        System.out.println(banana.getShape() + "," + banana.getForm());
    }
} 


Mule-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:stdio="http://www.mulesource.org/schema/mule/stdio/2.2"
    xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2"
    xsi:schemaLocation="
          http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd
          http://www.mulesource.org/schema/mule/stdio/2.2 http://www.mulesource.org/schema/mule/stdio/2.2/mule-stdio.xsd
          http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd">

    <stdio:connector name="stdioIN" promptMessage="Press any key to continue" />

    <model name="ExpressionSplitterRouterModel">
        <service name="CreateMsgService">
            <inbound>
                <stdio:inbound-endpoint
                    connector-ref="stdioIN" system="IN" />
            </inbound>
            <component
                class="com.expressionsplitterrouter.CreateFruitComponent" />
            <outbound>
                <expression-splitter-router
                    expression="fruit" evaluator="bean">
                    <vm:outbound-endpoint path="banana-channel">
                        <payload-type-filter
                            expectedType="com.expressionsplitterrouter.Banana" />
                    </vm:outbound-endpoint>
                    <vm:outbound-endpoint path="apple-channel">
                        <payload-type-filter
                            expectedType="com.expressionsplitterrouter.Apple" />
                    </vm:outbound-endpoint>
                </expression-splitter-router>
            </outbound>
        </service>
        
        <service name="BananaService">
            <inbound>
                <vm:inbound-endpoint path="banana-channel"/>
            </inbound>
            <component class="com.expressionsplitterrouter.BananaComponent"/>
        </service>
        
        <service name="AppleService">
            <inbound>
                <vm:inbound-endpoint path="apple-channel"/>
            </inbound>
            <component class="com.expressionsplitterrouter.AppleComponent"/>
        </service>
    </model>
</mule> 

Mule - Expression recipient list router

The following example is on the usage of the expression-recipient-list-router. This router can be used to extract the endpoints from the message and route it to the corresponding component.

Java Classes:

CreateXmlMessageComponent:


package com.expressrecipienttransformers;

public class CreateXmlMessageComponent {

    public String createMessage(String msg) {

        StringBuilder sb = new StringBuilder();
        sb.append("<message>");
        sb.append("<recipientList>");
        sb.append("<recipient>vm://display-message-channel</recipient>");
        sb.append("<recipient>vm://compute-message-channel</recipient>");
        sb.append("</recipientList>");
        sb.append("<info>");
        sb.append("Hi there");
        sb.append("</info>");
        sb.append("</message>");
        
        
        return sb.toString();
    }
} 

DisplayMessageComponent:

package com.expressrecipienttransformers;

public class DisplayMessageComponent {

    public void displayMessage(String msg) {
        
        System.out.println("Into displaymessage");
        System.out.println(msg);
    }
} 

ComputeMsgComponent:


package com.expressrecipienttransformers;

public class ComputeMsgComponent {

    public void compute(String msg) {
        
        System.out.println("Into compute component");
        System.out.println(msg.length());
    }
} 

mule-config.xml:



<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:stdio="http://www.mulesource.org/schema/mule/stdio/2.2"
    xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2"
    xsi:schemaLocation="
          http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd
          http://www.mulesource.org/schema/mule/stdio/2.2 http://www.mulesource.org/schema/mule/stdio/2.2/mule-stdio.xsd
          http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd">

    <stdio:connector name="stdioIN" promptMessage="Press any key to continue" />

    <model name="expression-recipient-list-model">
        <service name="expression-recipient-list-serviec">
            <inbound>
                <stdio:inbound-endpoint
                    connector-ref="stdioIN" system="IN" />
            </inbound>
            <component
                class="com.expressrecipienttransformers.CreateXmlMessageComponent"></component>
            <outbound>
                <expression-recipient-list-router
                    expression="/message/recipientList/recipient"
                    evaluator="xpath" />
            </outbound>
        </service>

        <service name="DisplayService">
            <inbound>
                <vm:inbound-endpoint path="display-message-channel" />
            </inbound>
            <component
                class="com.expressrecipienttransformers.DisplayMessageComponent" />
        </service>

        <service name="ComputeService">
            <inbound>
                <vm:inbound-endpoint path="compute-message-channel" />
            </inbound>
            <component
                class="com.expressrecipienttransformers.ComputeMsgComponent" />
        </service>
    </model>
</mule

Friday, September 30, 2011

Mule Expression Transformers

Java Classes:

GameData: 

A simple POJO object.

package com.expressiontransformers;

public class GameData {

    private String gameName;
    private int year;

    public String getGameName() {
        return gameName;
    }

    public void setGameName(String gameName) {
        this.gameName = gameName;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

}

GameInfo:

Another simple POJO that contains the GameData Object.

package com.expressiontransformers;

public class GamingInfo {

    private int gameId;

    private GameData gameData;

    public int getGameId() {
        return gameId;
    }

    public void setGameId(int gameId) {
        this.gameId = gameId;
    }

    public GameData getGameData() {
        return gameData;
    }

    public void setGameData(GameData gameData) {
        this.gameData = gameData;
    }

}


Here we will be using two component classes. One is used to generate the GameInfo Object and the other is used to print the values.

CreateGamingInfoComponent:

package com.expressiontransformers;

public class CreateGamingInfoComponent {

    public GamingInfo create(String msg) {
        GamingInfo info = new GamingInfo();
        info.setGameId(1);
        
        GameData data = new GameData();
        data.setGameName("Cricket");
        data.setYear(2010);
        
        info.setGameData(data);
        return info;
    }
}


GamingComponent:

package com.expressiontransformers;

public class GamingComponent {

    public void addGame(Integer gameId, GameData data) {
        
        System.out.println(gameId);
        System.out.println(data.getGameName());
        System.out.println(data.getYear());
    }
}

Mule-config.xml:

The mule-config.xml uses the expression-transformer in the inbound-endpoint to convert the input GameInfo object to the required values of the GamingComponent.

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:stdio="http://www.mulesource.org/schema/mule/stdio/2.2"
    xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2"
    xsi:schemaLocation="
          http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd
          http://www.mulesource.org/schema/mule/stdio/2.2 http://www.mulesource.org/schema/mule/stdio/2.2/mule-stdio.xsd
          http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd">

    <stdio:connector name="stdioIN" promptMessage="Press any key to Continue" />

    <model name="RestaurantServiceE">
        <service name="ExpressionFilterService">
            <inbound>
                <stdio:inbound-endpoint system="IN"
                    connector-ref="stdioIN" />
            </inbound>
            <component
                class="com.expressiontransformers.CreateGamingInfoComponent" />
            <outbound>
                <pass-through-router>
                    <vm:outbound-endpoint path="displayGamingInfo-channel" />
                </pass-through-router>
            </outbound>
        </service>

        <service name="DisplayInfoService">
            <inbound>
                <vm:inbound-endpoint path="displayGamingInfo-channel">
                    <expression-transformer>
                        <return-argument expression="gameId"
                            evaluator="bean" />
                        <return-argument expression="gameData"
                            evaluator="bean" />
                    </expression-transformer>
                </vm:inbound-endpoint>
            </inbound>
            <component class="com.expressiontransformers.GamingComponent" />
        </service>
    </model>
</mule>

Monday, September 26, 2011

Log4j, Mx4j and JMX JConsole Configuration in Mule

Sample Configuration File:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:http="http://www.mulesource.org/schema/mule/http/2.2"
    xmlns:https="http://www.mulesource.org/schema/mule/https/2.2"
    xmlns:saaj="http://www.mulesource.org/schema/mule/saaj/2.2"
    xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2"
    xmlns:mule-xml="http://www.mulesource.org/schema/mule/xml/2.2"
    xmlns:management="http://www.mulesource.org/schema/mule/management/2.2"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="
          http://www.mulesource.org/schema/mule/http/2.2 http://www.mulesource.org/schema/mule/http/2.2/mule-http.xsd
          http://www.mulesource.org/schema/mule/https/2.2 http://www.mulesource.org/schema/mule/https/2.2/mule-https.xsd
          http://www.mulesource.org/schema/mule/saaj/2.2 http://www.mulesource.org/schema/mule/saaj/2.2/mule-saaj.xsd
          http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd
          http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd
          http://www.mulesource.org/schema/mule/xml/2.2 http://www.mulesource.org/schema/mule/xml/2.2/mule-xml.xsd
          http://www.mulesource.org/schema/mule/management/2.2 http://www.mulesource.org/schema/mule/management/2.2/mule-management.xsd
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!--

        Mule Management Console Configurations START............
        Register the Mx4j Console...............................
        Register the JMX Console................................
        Register Log4j Console..................................
    -->
    <management:jmx-default-config port="1098"
        registerMx4jAdapter="true">
        <management:credentials>
            <spring:entry key="vijay" value="vijay123" />
        </management:credentials>
    </management:jmx-default-config>

    <management:jmx-log4j />

    <!-- 
        Mule Management Console Configurations END.
     -->
</mule> 

Handling SOAP Fault with Http Web Service

The sample XML configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:http="http://www.mulesource.org/schema/mule/http/2.2"
    xmlns:https="http://www.mulesource.org/schema/mule/https/2.2"
    xmlns:saaj="http://www.mulesource.org/schema/mule/saaj/2.2"
    xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2"
    xmlns:mule-xml="http://www.mulesource.org/schema/mule/xml/2.2"
    xmlns:management="http://www.mulesource.org/schema/mule/management/2.2"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="
          http://www.mulesource.org/schema/mule/http/2.2 http://www.mulesource.org/schema/mule/http/2.2/mule-http.xsd
          http://www.mulesource.org/schema/mule/https/2.2 http://www.mulesource.org/schema/mule/https/2.2/mule-https.xsd
          http://www.mulesource.org/schema/mule/saaj/2.2 http://www.mulesource.org/schema/mule/saaj/2.2/mule-saaj.xsd
          http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd
          http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd
          http://www.mulesource.org/schema/mule/xml/2.2 http://www.mulesource.org/schema/mule/xml/2.2/mule-xml.xsd
          http://www.mulesource.org/schema/mule/management/2.2 http://www.mulesource.org/schema/mule/management/2.2/mule-management.xsd
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!--

        Mule Management Console Configurations START............
        Register the Mx4j Console...............................
        Register the JMX Console................................
        Register Log4j Console..................................
    -->
    <management:jmx-default-config port="1098"
        registerMx4jAdapter="true">
        <management:credentials>
            <spring:entry key="vijay" value="vijay123" />
        </management:credentials>
    </management:jmx-default-config>

    <management:jmx-log4j />

    <!-- 
        Mule Management Console Configurations END.
     -->

    <spring:beans>
        <spring:import resource="transformers.xml" />
    </spring:beans>

    <custom-transformer
        class="com.restaurantsrevice.transformers.DocumentToSOAPFaultTransformer"
        name="faultTransformer">
        <spring:property name="propagateHeaders" value="false" />
    </custom-transformer>

    <model name="RestaurantServiceModel">

        <!-- Default Service Exception Strategy -->
        <default-service-exception-strategy>
            <vm:outbound-endpoint path="exception-channel" />
        </default-service-exception-strategy>

        <service name="RestaurantService">
            <inbound>
                <http:inbound-endpoint
                    address="http://localhost:8080/RestaurantService"
                    synchronous="true">
                    <transformers>

                        <!-- Transform Incoming Soap Message to XML String -->
                        <saaj:soap-message-to-document-transformer />
                        <mule-xml:dom-to-xml-transformer
                            returnClass="java.lang.String" />
                    </transformers>
                </http:inbound-endpoint>
            </inbound>
            <outbound>
                <pass-through-router>
                    <vm:outbound-endpoint path="router-channel"
                        synchronous="true" />
                </pass-through-router>
            </outbound>

            <async-reply>
                <vm:inbound-endpoint path="success-response-channel"
                    synchronous="true" />
                <vm:inbound-endpoint path="exception-response-channel"
                    synchronous="true" />
                <single-async-reply-router />
            </async-reply>
        </service>

        <service name="RouterService">
            <inbound>
                <vm:inbound-endpoint path="router-channel"
                    synchronous="true" />
            </inbound>
            <log-component />
            <outbound>
                <filtering-router>
                    <vm:outbound-endpoint path="request-processing-channel"
                        synchronous="true">
                        <transformer ref="addFoodRequestTransformer" />
                    </vm:outbound-endpoint>
                    <wildcard-filter pattern="*AddFoodRequest*" />
                </filtering-router>
            </outbound>
        </service>

        <service name="RequestProcessingService">
            <inbound>
                <vm:inbound-endpoint path="request-processing-channel"
                    synchronous="true" />
            </inbound>
            <component
                class="org.restaurantservice.RestaurantService"></component>
            <outbound>
                <filtering-router>
                    <vm:outbound-endpoint path="success-response-channel">
                        <transformers>
                            <transformer ref="addFoodResponseTransformer" />

                            <!-- Transform XML to SOAP response -->
                            <mule-xml:xml-to-dom-transformer
                                returnClass="org.w3c.dom.Document" />
                            <saaj:document-to-soap-message-transformer
                                propagateHeaders="false" />
                        </transformers>
                    </vm:outbound-endpoint>
                    <payload-type-filter
                        expectedType="com.services.restaurantservice.AddFoodResponse" />
                </filtering-router>
            </outbound>
        </service>

        <service name="ExceptionService">
            <inbound>
                <vm:inbound-endpoint path="exception-channel"
                    synchronous="true" />
            </inbound>
            <component
                class="com.services.restaurantservice.components.ExceptionHandler" />
            <outbound>
                <filtering-router>
                    <vm:outbound-endpoint path="exception-response-channel"
                        synchronous="true">

                        <transformers>
                            <transformer
                                ref="FoodAdditionFailedExceptionMap" />
                            <!-- Transform to Document Object -->
                            <mule-xml:xml-to-dom-transformer
                                returnClass="org.w3c.dom.Document" />

                            <!-- Transform to SOAP Fault -->
                            <transformer ref="faultTransformer" />
                        </transformers>

                    </vm:outbound-endpoint>
                    <payload-type-filter
                        expectedType="com.services.restaurantservice.webservice.FoodAdditionFailed" />
                </filtering-router>
                <filtering-router>
                    <vm:outbound-endpoint path="exception-response-channel"
                        synchronous="true">

                        <transformers>
                            <transformer ref="IncompleteRequestExceptionMap" />
                            <!-- Transform to Document Object -->
                            <mule-xml:xml-to-dom-transformer
                                returnClass="org.w3c.dom.Document" />

                            <!-- Transform to SOAP Fault -->
                            <transformer ref="faultTransformer" />
                        </transformers>

                    </vm:outbound-endpoint>
                    <payload-type-filter
                        expectedType="com.services.restaurantservice.webservice.IncompleteRequest" />
                </filtering-router>
            </outbound>
        </service>
    </model>
</mule> 
Java Code to transform to Soap Fault:
package com.restaurantsrevice.transformers;

import javax.xml.namespace.QName;
import javax.xml.soap.Detail;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;

import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.module.saaj.SaajUtils;
import org.mule.module.saaj.i18n.SaajMessages;
import org.mule.transformer.AbstractMessageAwareTransformer;
import org.w3c.dom.Document;

public class DocumentToSOAPFaultTransformer extends
        AbstractMessageAwareTransformer {

    private boolean propagateHeaders = true;
    private String headerURI = "http://www.mulesource.org/schema/mule/saaj/2.2";
    private String headerPrefix = "mule-saaj";

    private SOAPFactory soapFactory;
    private MessageFactory messageFactory;

    public DocumentToSOAPFaultTransformer() throws Exception {
        soapFactory = SOAPFactory.newInstance();
        messageFactory = MessageFactory.newInstance();
    }

    public void setPropagateHeaders(boolean propagateHeaders) {
        this.propagateHeaders = propagateHeaders;
    }

    public void setHeaderURI(String headerURI) {
        this.headerURI = headerURI;
    }

    public void setHeaderPrefix(String headerPrefix) {
        this.headerPrefix = headerPrefix;
    }

    public Object transform(MuleMessage muleMessage, String s)
            throws TransformerException {

        Document document = (Document) muleMessage.getPayload();
        SOAPMessage soapMessage;

        try {
            soapMessage = messageFactory.createMessage();
            SOAPBody body = soapMessage.getSOAPBody();

            addFault(body, document);

            if (propagateHeaders) {
                propagateHeaders(muleMessage, soapMessage);
            }
            soapMessage.saveChanges();
        } catch (SOAPException ex) {
            throw new TransformerException(SaajMessages
                    .failedToBuildSOAPMessage());
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Transformation result: "
                    + SaajUtils.getSOAPMessageAsString(soapMessage));
        }

        return SaajUtils.getSOAPMessageAsBytes(soapMessage);
    }

    void propagateHeaders(MuleMessage muleMessage, SOAPMessage soapMessage)
            throws SOAPException {
        for (Object n : muleMessage.getPropertyNames()) {
            String propertyName = (String) n;
            SOAPHeader header = soapMessage.getSOAPHeader();

            Name name = soapFactory.createName(propertyName, headerPrefix,
                    headerURI);
            SOAPHeaderElement headerElement = header.addHeaderElement(name);
            headerElement.addTextNode(muleMessage.getProperty(propertyName)
                    .toString());
        }
    }

    private void addFault(SOAPBody soapBody, Document document)
            throws SOAPException {

        org.w3c.dom.Element docElement = document.getDocumentElement();
        QName qName = new QName(docElement.getLocalName());

        SOAPFault soapFault = soapBody.addFault(qName, docElement
                .getTextContent());

        Detail detail = soapFault.addDetail();
        detail.addChildElement(soapFactory.createElement(docElement));
    }

}

Sunday, September 25, 2011

Customization of WSDL using bindings.xml

<?xml version="1.0" encoding="UTF-8"?>
<jaxws:bindings wsdlLocation="RestaurantService.wsdl"
    xmlns:jaxws="http://java.sun.com/xml/ns/jaxws" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">

    <jaxws:bindings node="wsdl:definitions/wsdl:types/xsd:schema">
        <jaxb:globalBindings choiceContentProperty="true" 
            collectionType="java.util.Set"
            generateIsSetMethod="true"
            enableJavaNamingConventions="true">
            <!--
                <jaxb:javaType name="java.util.Date"
                xmlType="xs:dateTime"
                parseMethod="org.apache.cxf.tools.common.DataTypeAdapter.parseDateTime"
                printMethod="org.apache.cxf.tools.common.DataTypeAdapter.printDateTime"/>
                <jaxb:javaType name="java.util.Date" xmlType="xs:date"
                parseMethod="org.apache.cxf.tools.common.DataTypeAdapter.parseDate"
                printMethod="org.apache.cxf.tools.common.DataTypeAdapter.printDate"/>
            -->
        </jaxb:globalBindings>
    </jaxws:bindings>
</jaxws:bindings> 


Reference Link

Monday, August 29, 2011

MULE HTTP Web Service - Step2A. Creating the client jars from the WSDL with Options

This step focuses on creating the client jars from the WSDL created in the previous step. This serves two purposes.
  1. To verify that the WSDL and the XSD was created without any errors.
  2. To get the jars ready so that we will have the class files generated for the objects defined in XSD. These classes will be used in our Mule web service.
This example focuses on using the Maven cxf-codegen-plugin to generate the classes.

Since we are going to develop a Mule Web Service using maven, we can easily import the client jar in your pom.xml

1. Create a simple maven project in Eclipse.



2. Add the cxf-codegen-plugin to your pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.hello</groupId>
    <artifactId>HelloServiceClient</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-codegen-plugin</artifactId>
                <version>2.4.0</version>
                <executions>
                    <execution>
                        <id>generate-sources</id>
                        <phase>generate-sources</phase>
                        <configuration>
                            <sourceRoot>${project.build.directory}/generated/cxf</sourceRoot>
                            <wsdlOptions>
                                <wsdlOption>
                                    <extraargs>
                                        <extraarg>-p</extraarg>
                                        <extraarg>http://hello.services.com=com.services.hello.helloservice</extraarg>
                                        <extraarg>-p</extraarg>
                                        <extraarg>http://ws.hello.services.com=com.services.hello.helloservice.ws</extraarg>
                                    </extraargs>
                                    <wsdl>${basedir}/src/main/resources/Hello.wsdl</wsdl>
                                    <bindingFiles>
                                        <bindingFile>${basedir}/src/main/resources/bindings.xml</bindingFile>
                                    </bindingFiles>
                                </wsdlOption>
                            </wsdlOptions>
                        </configuration>
                        <goals>
                            <goal>wsdl2java</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

3. Move the WSDL and XSD created in the previous section under src/main/resources

4. Make sure that you have JDK in your project classpath and not JRE. This plugin needs to compile and generate the class files and it requires a JDK to do it.

5. Right click on the project, go to Run As and select Maven Package.

With the above steps the client jar would get generated successfully and the client jar should contain the following structure.


Sunday, August 14, 2011

HIBERNATE - Bidirectional Many-to-Many Association

In the following example, we will be going through the bidirectional Many-to-Many association using Hibernate. We will be using the Student and Professor table where a student will have one or more professors. The same professor will have one or more students.

Schema Creation:

Since many-to-many is not allowed on the database level (Normalization), we will change this to add a junction-entity table in the middle. I am using the name of the junction-entity table to have the combination of both the tables.

The entities will be translated as follows:

STUDENT STUDPROF PROFESSOR
ID SIDID
NAME PIDNAME
PHNO
PHNO
ADDRESS
DOB

CREATE TABLE STUDENT (
	ID INTEGER(5) PRIMARY KEY DEFAULT 1,
	NAME VARCHAR(30) NOT NULL,
	ADDRESS VARCHAR(30) NOT NULL,
	PHNO VARCHAR(10) NOT NULL
);

CREATE TABLE PROFESSOR (
	ID INTEGER(5) PRIMARY KEY DEFAULT 1,
	NAME VARCHAR(30) NOT NULL,
	PHNO VARCHAR(30) NOT NULL,
	DOB DATE NOT NULL
);

CREATE TABLE STUDPROF (
	SID INTEGER(5) NOT NULL DEFAULT 1,
	PID INTEGER(5) NOT NULL DEFAULT 1,
	PRIMARY KEY(SID, PID),
	FOREIGN KEY (SID) REFERENCES STUDENT (ID),
	FOREIGN KEY (PID) REFERENCES PROFESSOR (ID)
);

HBM Files Creation:

Professor.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.mybusiness.pojos">
    <class name="Professor" table="PROFESSOR">
        <id name="id" column="ID" type="integer">
            <generator class="increment"></generator>
        </id>

        <property name="name" column="NAME" type="string"></property>

        <property name="phNo" column="PHNO" type="string"></property>

        <property name="dob" column="DOB" type="date"></property>

        <set name="students" table="STUDPROF" cascade="all" lazy="false">
            <key column="PID"></key>
            <many-to-many column="SID" class="Student"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

Student.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.mybusiness.pojos">
    <class name="Student" table="STUDENT">
        <id name="id" column="ID">
            <generator class="increment"></generator>
        </id>

        <property name="name" column="NAME" type="string"
            update="false"></property>

        <property name="address" column="ADDRESS" type="string"
            update="false"></property>

        <property name="phNo" column="PHNO" type="string"
            update="false"></property>

        <set name="professors" table="STUDPROF" cascade="all" lazy="false">
            <key column="SID"></key>
            <many-to-many column="PID" class="Professor"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

Java Files:

Professor.java:

package org.mybusiness.pojos;

import java.io.Serializable;
import java.util.Date;
import java.util.Set;

public class Professor implements Serializable {

    private static final long serialVersionUID = 2286787316913029844L;

    private int id;
    private String name;
    private String phNo;
    private Date dob;

    private Set<Student> students;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhNo() {
        return phNo;
    }

    public void setPhNo(String phNo) {
        this.phNo = phNo;
    }

    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    public Set<Student> getStudents() {
        return students;
    }

    public void setStudents(Set<Student> students) {
        this.students = students;
    }
}

Student.java:


package org.mybusiness.pojos;

import java.util.Set;

public class Student {

    private int id;
    private String name;
    private String address;
    private String phNo;

    private Set<Professor> professors;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPhNo() {
        return phNo;
    }

    public void setPhNo(String phNo) {
        this.phNo = phNo;
    }

    public Set<Professor> getProfessors() {
        return professors;
    }

    public void setProfessors(Set<Professor> professors) {
        this.professors = professors;
    }
}

Functionalities:

Create Student and Professor:

public void createProfessorStudent() {

    Professor professor = new Professor();

    professor.setName("Gautham");
    professor.setPhNo("3144143141");
    professor.setDob(new Date());

    Set<Student> students = new HashSet<Student>();

    Student student = new Student();
    student.setId(5);

    students.add(student);

    student = new Student();
    student.setName("Johny");
    student.setAddress("Santa Clara");
    student.setPhNo("3144443141");

    students.add(student);
    professor.setStudents(students);

    HibernateTemplate ht = new HibernateTemplate(sessionFactory);
    Session session = ht.getSessionFactory().openSession();
    Transaction tx = session.beginTransaction();

    try {

        session.saveOrUpdate(professor);
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
    }
}

Retrieve Student with Professor:

public void getProfessorStudent() {

    HibernateTemplate ht = new HibernateTemplate(sessionFactory);
    DetachedCriteria criteria = DetachedCriteria.forClass(Professor.class,
            "prof");
    criteria.add(Restrictions.eq("prof.id", 4));

    List<Professor> professors = ht.findByCriteria(criteria);
    for (Professor prof : professors) {

        System.out.println("PROFESSOR: " + prof.getName() + ":"
                + prof.getPhNo() + ":" + prof.getDob());
        for (Student stud : prof.getStudents()) {
            System.out.println("STUDENT: " + stud.getName() + ":"
                    + stud.getPhNo());
        }
    }
}