Calling REST Services using Spring’s REST Template

Hi guys, here is my 80th blog post which talks about calling Restful service using Spring’s “RestTemplate”. This codebase is executed under Spring 3.1 and 4.0 dependencies. The project structure looks as shown below.
RestTemplate_proj_struct

let me explain one scenario here, the calling REST service can return JSON Object or an XML Document back to consumer. it si up to the implementation how to convert JSON back to Java Object or convert Xml Back to Java.
We have many Marshallers and UnMarshallers available some of them are Jaxb2Marshaller,Jibx Marshaller, XStreamMarshaller,XmlBeanMarshaller..etc, i personally used Jaxb2Marshaller in this project. let us now dive into the code, there is no much explanation needed in the code, please follow the comments over the code blocks.

ConfigUtil.java

/**
 * 
 */
package com.spark.spring.rest.config;

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

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.web.client.RestTemplate;

import com.spark.spring.rest.models.Customer;

/**
 * @author PavanKumar Mantha
 * 
 */
@Configuration
public class ConfigUtil {

	/**
	 * @return the RetTemplate Object. This method sets the marshaller object as
	 *         params to RestTemplate leveraging the marshalling capability to
	 *         the template.
	 */
	@Bean(name = "restTemplate")
	public RestTemplate getRestTemplate() {
		RestTemplate restTemplate = new RestTemplate();

		List<HttpMessageConverter<?>> converters = new ArrayList<>();
		converters.add(getMarshallingHttpMessageConverter());
		converters.add(new FormHttpMessageConverter());
		converters.add(new StringHttpMessageConverter());
		restTemplate.setMessageConverters(converters);
		return restTemplate;
	}

	/**
	 * @return MarshallingHttpMessageConverter object which is responsible for
	 *         marshalling and unMarshalling process
	 */
	@Bean(name = "marshallingHttpMessageConverter")
	public MarshallingHttpMessageConverter getMarshallingHttpMessageConverter() {

		MarshallingHttpMessageConverter marshallingHttpMessageConverter = new MarshallingHttpMessageConverter();
		marshallingHttpMessageConverter.setMarshaller(getJaxb2Marshaller());
		marshallingHttpMessageConverter.setUnmarshaller(getJaxb2Marshaller());
		return marshallingHttpMessageConverter;
	}

	/**
	 * @return Jaxb2Marshaller, this is the Jaxb2Marshaller object
	 */
	@Bean(name = "jaxb2Marshaller")
	public Jaxb2Marshaller getJaxb2Marshaller() {
		Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
		jaxb2Marshaller.setClassesToBeBound(Customer.class);
		return jaxb2Marshaller;
	}
}

RestServiceConsumer .java, RestService call

/**
 * 
 */
package com.spark.spring.rest.consume;

import org.springframework.web.client.RestTemplate;

import com.spark.spring.rest.models.Customer;

/**
 * @author PavanKumar Mantha
 *
 */
public class RestServiceConsumer {

	/**
	 * @param restTemplate, this is the exact call to the service
	 */
	public static void consumeService(RestTemplate restTemplate){
		// getting xml directly from the response as string
		String xml = restTemplate.getForObject("http://www.thomas-bayer.com/sqlrest/CUSTOMER/18/", String.class);
		System.out.println(xml);
		
		// unmarshalling xml string to java object using Jaxb
		Customer customer = restTemplate.getForObject("http://www.thomas-bayer.com/sqlrest/CUSTOMER/18/", Customer.class);
		System.out.println(customer.getFirstName());
	}

}

Customer.java, Jaxb mapping POJO

/**
 * 
 */
package com.spark.spring.rest.models;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author PavanKumar Mantha
 * 
 */
@XmlRootElement(name="CUSTOMER")
public class Customer {

	private String id;
	private String firstName;
	private String lastName;
	private String street;
	private String city;

	/**
	 * @return the id
	 */
	@XmlElement(name="ID")
	public String getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * @return the firstName
	 */
	@XmlElement(name="FIRSTNAME")
	public String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName
	 *            the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * @return the lastName
	 */
	@XmlElement(name="LASTNAME")
	public String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName
	 *            the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * @return the street
	 */
	@XmlElement(name="STREET")
	public String getStreet() {
		return street;
	}

	/**
	 * @param street
	 *            the street to set
	 */
	public void setStreet(String street) {
		this.street = street;
	}

	/**
	 * @return the city
	 */
	@XmlElement(name="CITY")
	public String getCity() {
		return city;
	}

	/**
	 * @param city
	 *            the city to set
	 */
	public void setCity(String city) {
		this.city = city;
	}

}

Main Method

/**
 * 
 */
package com.spark.spring.rest.test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.client.RestTemplate;

import com.spark.spring.rest.config.ConfigUtil;
import com.spark.spring.rest.consume.RestServiceConsumer;

/**
 * @author PavanKumar Mantha
 *
 */
public class TestRestApp {

	/**
	 * @param args
	 */
	
	public static void main(String[] args) {
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ConfigUtil.class);
		RestServiceConsumer.consumeService((RestTemplate)applicationContext.getBean("restTemplate"));
	}

}

finally when we run the main method you should see the below output on the screen.
console

Happy RESTing…(RestTemplate) 🙂

IF and Else in BPEL

Hi All, its long time i wrote on SOA technologies so this week end decided to write on BPEL again. In this post i will start explaining on how to create BPEL process programmatically rather using GUI tool (Drag and Drop).

First lets create BPEl project and process as explained below.

1. Create a new BPEL project named “BpelTest” by selecting File→New→Others→BPEL 2.0→BPEL Project. Select Next. Type the project name as “BpelTest”. Click Finish.

2. Create a new BPEL process file named “BpelTestProcess” by right clicking on the BpelTest/bpelContent folder, select New→Others→BPEL 2.0→New BPEL Process File. Click Next. Fill in BPEL Process Name the string “BpelTestProcess”, and in the Namespace the string “http://spark.bpel.test.process&#8221;. Select the Template as Synchronous BPEL Process. Click Finish.

Note : Please rename the WSDL that is create as shown in the screen shot below.
image

Once the BPEL process is created let us change it as show as below. BPEL process file contain 5 major sections.
1. BPEL Process namespace.
2. Client WSDL import.
3. Specifying Partner Links.
4. Declaring Variables.
5. Orchestrating the Process Logic.

The Bpel Process name space and Client WSDL import are shown as below.

<bpel:process name="BpelTestProcess" targetNamespace="http://spark.bpel.test.process"
	suppressJoinFailure="yes" xmlns:tns="http://spark.bpel.test.process"
	xmlns:bpel="http://docs.oasis-open.org/wsbpel/2.0/process/executable"
	xmlns:xsd="http://www.w3.org/2001/XMLSchema">

	<!-- Import the client WSDL -->
	<bpel:import location="BpelTestProcess.wsdl" namespace="http://spark.bpel.test.process"
		importType="http://schemas.xmlsoap.org/wsdl/" />

Now its time to specify the partner links and declare variables as shown below.

<bpel:partnerLinks>
		<bpel:partnerLink name="client" partnerLinkType="tns:BpelTestProcess"
			myRole="BpelTestProcessProvider" />
	</bpel:partnerLinks>


	<bpel:variables>
		<bpel:variable name="input" messageType="tns:BpelTestProcessRequestMessage" />
		<bpel:variable name="output" messageType="tns:BpelTestProcessResponseMessage" />
		<bpel:variable name="tmpInput" type="xsd:string"></bpel:variable>
	</bpel:variables>

Here we come with the exact orchestration logic.

<bpel:sequence name="main">
		<bpel:receive name="receiveInput" partnerLink="client"
			portType="tns:BpelTestProcess" operation="process" variable="input"
			createInstance="yes" />

		<bpel:assign validate="no" name="Assign">
			<bpel:copy>
				<bpel:from variable="input" part="payload"></bpel:from>
				<bpel:to variable="tmpInput"></bpel:to>
			</bpel:copy>
		</bpel:assign>
		<bpel:if>
			<bpel:condition>string($tmpInput)=string("sample passowrd")</bpel:condition>
			<bpel:assign name="working">
				<bpel:copy>
					<bpel:from>
						<bpel:literal>password matched</bpel:literal>
					</bpel:from>
					<bpel:to variable="output" part="payload"></bpel:to>
				</bpel:copy>
			</bpel:assign>
			<bpel:else>
				<bpel:assign name="failed">
					<bpel:copy>
						<bpel:from>
							<bpel:literal>Security Breach !</bpel:literal>
						</bpel:from>
						<bpel:to variable="output" part="payload"></bpel:to>
					</bpel:copy>
				</bpel:assign>
			</bpel:else>

		</bpel:if>
		<bpel:reply name="replyOutput" partnerLink="client"
			portType="tns:BpelTestProcess" operation="process" variable="output" />
	</bpel:sequence>

combining the sequence of xmls, final resultant BPEL Process code is as below.

<!-- BpelTestProcess BPEL Process [Generated by the Eclipse BPEL Designer] -->
<!-- Date: Sat May 24 19:07:43 IST 2014 -->
<bpel:process name="BpelTestProcess" targetNamespace="http://spark.bpel.test.process"
	suppressJoinFailure="yes" xmlns:tns="http://spark.bpel.test.process"
	xmlns:bpel="http://docs.oasis-open.org/wsbpel/2.0/process/executable"
	xmlns:xsd="http://www.w3.org/2001/XMLSchema">

	<!-- Import the client WSDL -->
	<bpel:import location="BpelTestProcess.wsdl" namespace="http://spark.bpel.test.process"
		importType="http://schemas.xmlsoap.org/wsdl/" />


	<bpel:partnerLinks>
		<bpel:partnerLink name="client" partnerLinkType="tns:BpelTestProcess"
			myRole="BpelTestProcessProvider" />
	</bpel:partnerLinks>


	<bpel:variables>
		<bpel:variable name="input" messageType="tns:BpelTestProcessRequestMessage" />
		<bpel:variable name="output" messageType="tns:BpelTestProcessResponseMessage" />
		<bpel:variable name="tmpInput" type="xsd:string"></bpel:variable>
	</bpel:variables>


	<bpel:sequence name="main">
		<bpel:receive name="receiveInput" partnerLink="client"
			portType="tns:BpelTestProcess" operation="process" variable="input"
			createInstance="yes" />

		<bpel:assign validate="no" name="Assign">
			<bpel:copy>
				<bpel:from variable="input" part="payload"></bpel:from>
				<bpel:to variable="tmpInput"></bpel:to>
			</bpel:copy>
		</bpel:assign>
		<bpel:if>
			<bpel:condition>string($tmpInput)=string("06b81a04a1")</bpel:condition>
			<bpel:assign name="working">
				<bpel:copy>
					<bpel:from>
						<bpel:literal>password matched</bpel:literal>
					</bpel:from>
					<bpel:to variable="output" part="payload"></bpel:to>
				</bpel:copy>
			</bpel:assign>
			<bpel:else>
				<bpel:assign name="failed">
					<bpel:copy>
						<bpel:from>
							<bpel:literal>Security Breach !</bpel:literal>
						</bpel:from>
						<bpel:to variable="output" part="payload"></bpel:to>
					</bpel:copy>
				</bpel:assign>
			</bpel:else>

		</bpel:if>
		<bpel:reply name="replyOutput" partnerLink="client"
			portType="tns:BpelTestProcess" operation="process" variable="output" />
	</bpel:sequence>
</bpel:process>

the result of this process code in GUI looks as below
image2

Now lets code our client WSDl as follows

<?xml version="1.0"?>
<definitions name="BpelTestProcess"
        targetNamespace="http://spark.bpel.test.process"
        xmlns:tns="http://spark.bpel.test.process"
        xmlns:plnk="http://docs.oasis-open.org/wsbpel/2.0/plnktype"
        xmlns="http://schemas.xmlsoap.org/wsdl/"
        xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
        >

<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     TYPE DEFINITION - List of types participating in this BPEL process 
     The BPEL Designer will generate default request and response types
     but you can define or import any XML Schema type and use them as part 
     of the message types.
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->    
    <types>
        <schema attributeFormDefault="unqualified" elementFormDefault="qualified" 
                targetNamespace="http://spark.bpel.test.process" 
                xmlns="http://www.w3.org/2001/XMLSchema">

            <element name="BpelTestProcessRequest">
                <complexType>
                    <sequence>
                        <element name="input" type="string"/>
                    </sequence>
                </complexType>
            </element>

            <element name="BpelTestProcessResponse">
                <complexType>
                    <sequence>
                        <element name="result" type="string"/>
                    </sequence>
                </complexType>
            </element>
        </schema>
    </types>


<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     MESSAGE TYPE DEFINITION - Definition of the message types used as 
     part of the port type defintions
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->    
    <message name="BpelTestProcessRequestMessage">
        <part name="payload" element="tns:BpelTestProcessRequest"/>
    </message>
    <message name="BpelTestProcessResponseMessage">
        <part name="payload" element="tns:BpelTestProcessResponse"/>
    </message>

<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     PORT TYPE DEFINITION - A port type groups a set of operations into
     a logical service unit.
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->    

    <!-- portType implemented by the BpelTestProcess BPEL process -->
    <portType name="BpelTestProcess">
        <operation name="process">
            <input  message="tns:BpelTestProcessRequestMessage" />
            <output message="tns:BpelTestProcessResponseMessage"/>
        </operation>
    </portType>   
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     PARTNER LINK TYPE DEFINITION
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->    
    <plnk:partnerLinkType name="BpelTestProcess">
        <plnk:role name="BpelTestProcessProvider" portType="tns:BpelTestProcess"/>
    </plnk:partnerLinkType>
    

<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     BINDING DEFINITION - Defines the message format and protocol details
     for a web service.
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    <binding name="BpelTestProcessBinding" type="tns:BpelTestProcess">
    	<soap:binding style="document"
    		transport="http://schemas.xmlsoap.org/soap/http" />
    	<operation name="process">
    		<soap:operation
    			soapAction="http://spark.bpel.test.process/process" />
    		<input>
    			<soap:body use="literal" />
    		</input>
    		<output>
    			<soap:body use="literal" />
    		</output>
    	</operation>
    </binding>

<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     SERVICE DEFINITION - A service groups a set of ports into
     a service unit.
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    <service name="BpelTestProcessService">
    	<port name="BpelTestProcessPort" binding="tns:BpelTestProcessBinding">
    		<soap:address location="http://localhost:8080/BpelTestProcess" />
    	</port>
    </service>
</definitions>

also the deploy.xml looks as below.

<?xml version="1.0" encoding="UTF-8"?>
<deploy xmlns="http://www.apache.org/ode/schemas/dd/2007/03" xmlns:pns="http://ode/bpel/unit-test" xmlns:spark.bpel.test.process="http://spark.bpel.test.process" xmlns:wns="http://ode/bpel/unit-test.wsdl">
  <process name="spark.bpel.test.process:BpelTestProcess">
    <process-events generate="all"/>
    <provide partnerLink="client">
      <service name="spark.bpel.test.process:BpelTestProcessService" port="BpelTestProcessPort"/>
    </provide>
  </process>
</deploy>

Download WSO2 BPS server(BPEL Process Server) from this link : http://wso2.com/products/business-process-server/. once the server is downloaded we start it by running the wso2server.bat file located in “YourDownloadLocation\$BPS_Home\bin”. Once the server is up and running we can open the management console by typing the below URL “https://localhost:9443/carbon/admin/login.jsp&#8221; and login with the admin/admin user and password.

BpsLogin

now Zip only the source files, wsdl and deploy.xml and then upload the zip archieve to BPS server. in “Main->Process->add”, when the process gets successfully uploaded it will be shown under “Main -> Process -> list”
once the deployment is complete its time for us to test our BPEL process. BPS provice a tool internally to test the process or we can use SOAP UI to test it(I prefer to use BPS Tool ‘TryIt’)

click on the process name this will take us to the process specific page and there we can find TryIt tool. please follow the screens as below.

process after deploy

try it

once we click on the try it. this will open a testing tool where we can send request and response will be shown.
Testing

In my next write up we will see how to call Java Code from BPEL Process.
Happy BPEL coding 🙂

MTOM With JAX-WS

Hi All, what if you want to send large binary data using web services we have SOAP with attachments i.e. MTOM(Message Transmission Optimization Mechanism).SOAP Message Transmission Optimization Mechanism (MTOM) specifies an optimized method for sending binary data as part of a SOAP message. Unlike SOAP with Attachments, MTOM requires the use of XML-binary Optimized Packaging (XOP) packages for transmitting binary data. Using MTOM to send binary data does not require you to fully define the MIME Multipart/Related message as part of the SOAP binding. It does, however, require that you do the following:

1. Annotate the data that you are going to send as an attachment.
2. You can annotate either your WSDL or the Java class that implements your data.
3. Enable the runtime’s MTOM support.
4. This can be done either programatically or through configuration.
5. Develop a DataHandler for the data being passed as an attachment.

below is the code snippet for MTOM implementation, follow the comments closely in the code.

/**
 * 
 */
package com.webservice.endpoint.interfaces;

import java.awt.Image;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

/**
 * @author Sony
 *
 */
@WebService
@SOAPBinding(style = Style.RPC)
public interface BinaryDataDistribution {

	@WebMethod
	public Image downloadBinaryData(String name);
	
	@WebMethod
	public String uploadBinaryData(Image data);
}
/**
 * 
 */
package com.webservice.endpoint.interfaces.impl;

import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.soap.MTOM;

import com.webservice.endpoint.interfaces.BinaryDataDistribution;

/**
 * @author Sony
 * 
 */
@MTOM
@WebService(endpointInterface = "com.webservice.endpoint.interfaces.BinaryDataDistribution")
public class BinaryDataDistributionImpl implements BinaryDataDistribution {

	
	 // (non-Javadoc)
	  
	 // @see
	 // com.webservice.endpoint.interfaces.BinaryDataDistribution#downloadBinaryData
	 // (java.lang.String)
	 
	@Override
	@WebMethod
	public Image downloadBinaryData(String name) {
		try {

			File image = new File("c:\\images\\" + name);
			return ImageIO.read(image);

		} catch (IOException e) {

			e.printStackTrace();
			return null;

		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.webservice.endpoint.interfaces.BinaryDataDistribution#uploadBinaryData
	 * (java.awt.Image)
	 */
	@Override
	@WebMethod
	public String uploadBinaryData(Image data) {
		if (data != null) {
			// saving logic goes here !
			return "Upload Successful";
		}

		throw new WebServiceException("Upload Failed!");
	}

}
/**
 * 
 */
package com.webservice.publish;

import javax.xml.ws.Endpoint;

import com.webservice.endpoint.interfaces.impl.BinaryDataDistributionImpl;

/**
 * @author Sony
 * 
 */
public class PublishService {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Endpoint.publish("http://localhost:9999/ws/image",
				new BinaryDataDistributionImpl());

		System.out.println("Server is published!");
	}

}

Now the Wsdl should look as below.

  <?xml version="1.0" encoding="UTF-8" ?> 
- <!--  Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.2.4-b01. 
  --> 
- <!--  Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.2.4-b01. 
  --> 
- <definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://impl.interfaces.endpoint.webservice.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://impl.interfaces.endpoint.webservice.com/" name="BinaryDataDistributionImplService">
  <import namespace="http://interfaces.endpoint.webservice.com/" location="http://localhost:9999/ws/image?wsdl=1" /> 
- <wsp:Policy wsu:Id="BinaryDataDistributionImplPortBinding_MTOM_Policy">
  <ns1:OptimizedMimeSerialization xmlns:ns1="http://schemas.xmlsoap.org/ws/2004/09/policy/optimizedmimeserialization" wsp:Optional="true" /> 
  </wsp:Policy>
- <binding xmlns:ns2="http://interfaces.endpoint.webservice.com/" name="BinaryDataDistributionImplPortBinding" type="ns2:BinaryDataDistribution">
  <wsp:PolicyReference URI="#BinaryDataDistributionImplPortBinding_MTOM_Policy" /> 
  <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc" /> 
- <operation name="downloadBinaryData">
  <soap:operation soapAction="" /> 
- <input>
  <soap:body use="literal" namespace="http://interfaces.endpoint.webservice.com/" /> 
  </input>
- <output>
  <soap:body use="literal" namespace="http://interfaces.endpoint.webservice.com/" /> 
  </output>
  </operation>
- <operation name="uploadBinaryData">
  <soap:operation soapAction="" /> 
- <input>
  <soap:body use="literal" namespace="http://interfaces.endpoint.webservice.com/" /> 
  </input>
- <output>
  <soap:body use="literal" namespace="http://interfaces.endpoint.webservice.com/" /> 
  </output>
  </operation>
  </binding>
- <service name="BinaryDataDistributionImplService">
- <port name="BinaryDataDistributionImplPort" binding="tns:BinaryDataDistributionImplPortBinding">
  <soap:address location="http://localhost:9999/ws/image" /> 
  </port>
  </service>
  </definitions>

Happy coding 🙂 “MTOM

Spring Web Services using JAXB part-2

After the part-1 this is the contd part of it, now we are going to write the endpoint implementations and mapping these end points to the request from the web. so lets not waste time just jumping into the implementation part here we go.

Lets write AbstractPersonEndPoint class which will extend AbstractMarshallingPayloadEndpoint of Spring framework. Here we are going to just create PersonService object and define an abstract method invokeInternal of AbstractMarshallingPayloadEndpoint class.

/**
 * 
 */
package com.spark.springws.abstrct.endpoint;

import org.springframework.ws.server.endpoint.AbstractMarshallingPayloadEndpoint;

import com.spark.springws.service.PersonService;

/**
 * @author Sony
 *
 */
public abstract class AbstractPersonEndPoint extends AbstractMarshallingPayloadEndpoint {

	protected PersonService personService;
	
	/**
	 * @param personService the personService to set
	 */
	public void setPersonService(PersonService personService) {
		this.personService = personService;
	}


	/* (non-Javadoc)
	 * @see org.springframework.ws.server.endpoint.AbstractMarshallingPayloadEndpoint#invokeInternal(java.lang.Object)
	 */
	@Override
	protected abstract Object invokeInternal(Object request) throws Exception;

}

Now its time to create concrete endpoint classes which will have exact business logic implementation and will extend AbstractPersonEndPoint. I will show for one of the service and other implementations are left for you.

/**
 * 
 */
package com.spark.springws.endpoints;

import org.springws.beans.schema.AddPersonRequest;

import com.spark.springws.abstrct.endpoint.AbstractPersonEndPoint;

/**
 * @author Sony
 *
 */
public class AddPersonEndPoint extends AbstractPersonEndPoint {

	/* (non-Javadoc)
	 * @see com.spark.springws.abstrct.endpoint.AbstractPersonEndPoint#invokeInternal(java.lang.Object)
	 */
	@Override
	protected Object invokeInternal(Object request) throws Exception {

		AddPersonRequest addPersonRequest = (AddPersonRequest) request;
		personService.addPerson(addPersonRequest.getPerson());
		return null;
	}

}

now lets take a look at the spring-ws-servlet.xml which we already defined in this part-1 section and modify it a little bit as shown below.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oxm="http://www.springframework.org/schema/oxm"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.2.xsd">

	<bean id="personService" class="com.spark.springws.service.impl.PersonServiceImpl"
		init-method="initialize" />
	<bean id="Person"
		class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition">
		<property name="schema" ref="schema" />
		<property name="portTypeName" value="Person" />
		<property name="locationUri" value="/services" />
		<property name="targetNamespace" value="http://www.example.org/person/schema" />
	</bean>
	<bean id="schema" class="org.springframework.xml.xsd.SimpleXsdSchema">
		<property name="xsd" value="/WEB-INF/xsd/schemas/Person.xsd" />
	</bean>

	<bean id="validationInterceptor"
		class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor">
		<property name="xsdSchema" ref="schema"></property>
		<property name="validateRequest" value="true" />
		<property name="validateResponse" value="true" />
	</bean>

	<bean id="loggingInterceptor"
		class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor" />

	<oxm:jaxb2-marshaller id="marshaller"
		contextPath="org.springws.beans.schema" />
	<oxm:jaxb2-marshaller id="unmarshaller"
		contextPath="org.springws.beans.schema" />

	<bean id="addPersonEndpoint" class="com.spark.springws.endpoints.AddPersonEndPoint"
		autowire="byName" />
	<bean id="getAllPersonsEndpoint" class="com.spark.springws.endpoints.GetAllPersonsEndPoint"
		autowire="byName" />
	<bean id="getPersonEndpoint" class="com.spark.springws.endpoints.GetPersonEndPoint"
		autowire="byName" />

	<bean name="endpointMapping"
		class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
		<property name="interceptors">
			<list>
				<ref local="loggingInterceptor" />
				<ref local="validationInterceptor" />
			</list>
		</property>
		<property name="mappings">
			<props>
				<prop key="{http://www.example.org/person/schema}AddPersonRequest">addPersonEndpoint</prop>
				<prop key="{http://www.example.org/person/schema}GetAllPersonsRequest">getAllPersonsEndpoint</prop>
				<prop key="{http://www.example.org/person/schema}GetPersonRequest">getPersonEndpoint</prop>
				<prop key="{http://www.example.org/person/schema}UpdatePersonRequest">updatePersonEndpoint</prop> 
					<prop key="{http://www.example.org/person/schema}DeletePersonRequest">deletePersonEndpoint</prop>
			</props>
		</property>
	</bean>

	<bean id="exceptionResolver"
		class="org.springframework.ws.soap.server.endpoint.SoapFaultMappingExceptionResolver">
		<property name="defaultFault" value="SERVER" />
		<property name="exceptionMappings">
			<props>
				<prop key="org.springframework.oxm.ValidationFailureException">CLIENT,Invalid request</prop>
				<prop key="com.spark.springws.custom.exception.PersonException">SERVER</prop>
			</props>
		</property>
	</bean>
</beans>

once this is done just deploy the project and test the request and response from SOAP UI as shown below.
add-request

get-req-res

Happy Spring-Web services 🙂

Spring Web Services using JAXB part-1

Hi all its long time i put pen on my blog, its now time to write some thing about Spring web services implementation. Web services implementation of Spring is the best product and now a days service driven projects are in more demand, spring web services are of two types 1.RESTful Services and SOAP services. Some of the key features of spring web services are as follows

a) XML API support: Incoming XML messages can be handled in standard JAXP APIs such as DOM, SAX, and StAX, but also JDOM, dom4j, XOM, or even marshalling technologies.

b) Flexible XML Marshalling: The Object/XML Mapping module in the Spring Web Services distribution supports JAXB 1 and 2, Castor, XMLBeans, JiBX, and XStream. And because it is a separate module, you can use it in non-Web services code as well.

c) Also, the architecture of Spring-WS resembles that of Spring-MVC.

d) Apache license. You can confidently use Spring-WS in your project.

Before moving into the coding part, the essential jars required by the project as as below.
jars

Now its time for us to define the service contract.
Service Contract

Here’s where we start our contract first approach, the Service contract. The wsdl contract can be happily generated by Spring’s DefaultWsdl11Definition later. so lets start with simple schema as below.

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
	targetNamespace="http://www.example.org/person/schema" xmlns:per="http://www.example.org/person/schema"
	elementFormDefault="qualified">

	<xs:element name="Person">
		<xs:complexType>
			<xs:sequence>
				<xs:element name="FirstName" type="xs:string" />
				<xs:element name="LastName" type="xs:string" />
			</xs:sequence>
			<xs:attribute ref="per:Id" use="required" />
		</xs:complexType>
	</xs:element>

	<xs:attribute name="Id" type="xs:int" />

	<xs:element name="AddPersonRequest">
		<xs:complexType>
			<xs:sequence>
				<xs:element ref="per:Person" />
			</xs:sequence>
		</xs:complexType>
	</xs:element>

	<xs:element name="GetPersonRequest">
		<xs:complexType>
			<xs:attribute ref="per:Id" use="required" />
		</xs:complexType>
	</xs:element>

	<xs:element name="GetPersonResponse">
		<xs:complexType>
			<xs:sequence>
				<xs:element ref="per:Person" />
			</xs:sequence>
		</xs:complexType>
	</xs:element>

	<xs:element name="GetAllPersonsRequest">
		<xs:complexType>
			<xs:sequence />
		</xs:complexType>
	</xs:element>

	<xs:element name="GetAllPersonsResponse">
		<xs:complexType>
			<xs:sequence>
				<xs:element ref="per:Person" maxOccurs="unbounded" />
			</xs:sequence>
		</xs:complexType>
	</xs:element>

	<xs:element name="UpdatePersonRequest">
		<xs:complexType>
			<xs:sequence>
				<xs:element ref="per:Person" />
			</xs:sequence>
		</xs:complexType>
	</xs:element>

	<xs:element name="DeletePersonRequest">
		<xs:complexType>
			<xs:attribute ref="per:Id" use="required" />
		</xs:complexType>
	</xs:element>
</xs:schema>

once our schema is ready now lets write simple ant script to generate the jaxb classes and compile them using jaxb’s xjc command using as follows.

<?xml version="1.0" encoding="UTF-8"?>
<project name="Spring-Ws Project With JaxB,XMLBeans and Jibx Capability"
	default="all" basedir=".">
	
	<property file="./build.properties" />
	
	<property name="javac.source" value="1.6" />
	<property name="javac.target" value="1.6" />
	
	<path id="classpath" description="Classpath to web application">
		<fileset dir="${dir.webapp.lib}" includes="**/*.jar" />
		<pathelement location="bin" />
	</path>
	
	<target name="clean">
        <delete dir="${base.dir}/classes"/>
        <mkdir dir="${base.dir}/classes"></mkdir>
    </target>
    
	<target name="compile">
        <javac srcdir="${dir.src}/org/springws/beans/schema" destdir="${base.dir}/classes"/>
    </target>
	
	<target name="clean-compile" description="java xml binding tool" depends="clean,compile">
		<echo message="compiling JAXB classes from xsd" />
		<exec executable="${jdk.home}/bin/xjc.exe">
			<arg value="-d" />
			<arg value="${dir.src}" />
			<arg value="-p" />
			<arg value="org.springws.beans.schema" />
			<arg value="${xsd.dir}/Person.xsd" />
		</exec>
	</target>
</project>

build.properties

base.dir=.

jdk.home=C\:\\Oracle\\Middleware\\jdk160_24
dir.src=../../src
xsd.dir=${base.dir}/xsd/schemas

dir.webapp.lib=${base.dir}/lib

Now lets design our own custom exception class as follows.
PersonException.java

/**
 * 
 */
package com.spark.springws.custom.exception;

/**
 * @author Sony
 *
 */
public class PersonException extends Exception {

	private static final long serialVersionUID = 1L;

	public PersonException(String message) {
		super(message);
	}
}

now lets start with the service class and its implementation class as follows.
PersonService.java, PersonServiceImpl.java

/**
 * 
 */
package com.spark.springws.service;

import java.util.List;

import org.springws.beans.schema.Person;

import com.spark.springws.custom.exception.PersonException;

/**
 * @author Sony
 * 
 */
public interface PersonService {
	public void addPerson(Person person) throws PersonException;
	public Person getPerson(Integer id) throws PersonException;
	public List<Person> getAllPersons();
	public void updatePerson(Person person) throws PersonException;
	public void deletePerson(Integer id) throws PersonException;
}

/**
 * 
 */
package com.spark.springws.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springws.beans.schema.Person;

import com.spark.springws.custom.exception.PersonException;
import com.spark.springws.service.PersonService;

/**
 * @author Sony
 * 
 */
public class PersonServiceImpl implements PersonService {

	private Map dataSource;

	@Override
	public void addPerson(Person person) throws PersonException {
		if (idExists(person.getId())) {
			throw new PersonException("Cannot add person. Id already exists.");
		}
		dataSource.put(person.getId(), person);
	}

	
	@Override
	public Person getPerson(Integer id) throws PersonException {
		if (!idExists(id)) {
			throw new PersonException("Cannot get person. ID does not exist.");
		}
		return (Person) dataSource.get(id);
	}

	@Override
	public List<Person> getAllPersons() {
		return new ArrayList(dataSource.values());
	}

	@Override
	public void updatePerson(Person person) throws PersonException {
		if (!idExists(person.getId())) {
			throw new PersonException(
					"Cannot update person. ID does not exist.");
		}
		dataSource.put(person.getId(), person);
	}

	@Override
	public void deletePerson(Integer id) throws PersonException {
		if (!idExists(id)) {
			throw new PersonException(
					"Cannot delete person. Id does not exists.");
		}
		dataSource.remove(id);
	}

	public void initialize() {
		dataSource = new HashMap();
		putPerson(1, "Clark", "Kent");
		putPerson(2, "Bruce", "Wayne");
		putPerson(3, "Harold", "Jordan");
	}

	private void putPerson(Integer id, String firstName, String lastName) {
		Person person = new Person();
		person.setId(id);
		person.setFirstName(firstName);
		person.setLastName(lastName);
		dataSource.put(id, person);
	}

	private boolean idExists(Integer id) {
		return dataSource.containsKey(id);
	}

}

Now lets write web.xml file as follows.

<?xml version="1.0" encoding="ISO-8859-1"?> 

<!DOCTYPE web-app PUBLIC 
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
    "http://java.sun.com/dtd/web-app_2_4.dtd">

<web-app>
	<display-name>Person Service</display-name>
	<description>Simple CRUD like Application</description>

	<!-- Defines the Spring-WS MessageDispatcherServlet -->
	<servlet>
		<servlet-name>spring-ws</servlet-name>
		<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
		<init-param>
			<!-- Transform the location attributes in WSDLs -->
			<param-name>transformWsdlLocations</param-name>
			<param-value>true</param-value>
		</init-param>
	</servlet>

	<!-- Map all requests to this servlet -->
	<servlet-mapping>
		<servlet-name>spring-ws</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>
</web-app>

spring-ws-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oxm="http://www.springframework.org/schema/oxm"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-1.5.xsd">

	<bean id="personService" class="com.spark.springws.service.impl.PersonServiceImpl"
		init-method="initialize" />
	<bean id="Person"
		class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition">
		<property name="schema" ref="schema" />
		<property name="portTypeName" value="Person" />
		<property name="locationUri" value="/services" />
		<property name="targetNamespace" value="http://www.example.org/person/schema" />
	</bean>
	<bean id="schema" class="org.springframework.xml.xsd.SimpleXsdSchema">
		<property name="xsd" value="/WEB-INF/xsd/schemas/Person.xsd" />
	</bean>
</beans>

my project structure looks as below.
project-struct

once comleted please deploy the project onto server and run this url we should see the contract wsdl in the browser.
http://localhost:8080/Spring-WS-Ant/Person.wsdl

lets see how to define the service-endpoint-implementation,endpoint-mapping,mapping request to beans in the next post
until then keep coding
Happy Java and web services 🙂

JSON in JavaEE 7

Hello guys..During week end i was doing lot of research on new technologies and newly released JavaEE 7 API. I found a very good enhancement in the API, i.e “JSON”. In modern day Programming when compared to lagecy apps the communication is completely depending on JSON data rather XML format, because of JSON’s readability and Object oriented nature. JSR-353 has bought a new feature in JavaEE 7, they included JSON API in JavaEE 7. Previous to JavaEE 7 most of us are relying on third party libs to form JSON structure now its all JavaEE 7 responsibility. I researched few things in the JSON(JavaEE 7) and here are my findings.

Note:Please add the following Maven dependency in you pom.xml file to get the JSON support from JavaEE 7

<dependencies>
	<dependency>
		<groupId>org.glassfish</groupId>
		<artifactId>javax.json</artifactId>
		<version>1.0.1</version>
	</dependency>
</dependencies>

JSON: is a text-based data exchange format derived from JavaScript that is used in web services and other connected applications.
The following example shows JSON data for a sample object that contains name-value pairs. The value for the name “phoneNumbers” is an array whose elements are two objects.

{
   "firstName": "PavanKumar",
   "lastName": "Mantha",
   "age": 27,
   "streetAddress": "100 JavaEE RandD",
   "city": "Hyderabad",
   "state": "AP",
   "postalCode": "12345",
   "phoneNumbers": [
      { "Mobile": "111-111-1111" },
      { "Home": "222-222-2222" }
   ]
}

JSON has the following syntax:

Objects are enclosed in braces {}, their name-value pairs are separated by a comma (,) and the name and value in a pair are separated by a colon (:). Names in an object are strings, whereas values may be of any of the six data types, including another object or an array.

Arrays are enclosed in brackets [], and their values are separated by a coma (,). Each value in an array may be of a different type, including another array or an object.

When objects and arrays contain other objects or arrays, the data has a tree-like structure.

Use of JSON:

JSON is commonly used to serialize and de-serialize object data and communicate over internet between two or more applications running in different environments, these application an be programmed in different languages but JSON can be a common platform to communicate. To my understanding this is the modern approach in compatible with legacy communication over XML.

Generating and Parsing JSON Data With Example
Note: please read JSR-353 support for JSON in JavaEE 7 oracle documentation for more details and API Spec.

Create JSONObject by reading Json data:

import java.io.FileReader;
import javax.json.Json;
import javax.json.JsonReader;
import javax.json.JsonStructure;
...
JsonReader reader = Json.createReader(new FileReader("jsondata.txt"));
JsonStructure jsonst = reader.read();

Creating JSON Object from Application:

JsonObjectBuilder jsonObjectBuilder = (JsonObjectBuilder) Json
				.createObjectBuilder();
		JsonObject jsonObject = jsonObjectBuilder
				.add("firstName", "PavanKumar")
				.add("lastName", "Mantha")
				.add("age", 27)
				.add("streetAddress", "100 JavaEE RandD")
				.add("city", "Hyderabad")
				.add("state", "AP")
				.add("postalCode", "12345")
				.add("phoneNumbers",
						Json.createArrayBuilder()
								.add(Json.createObjectBuilder()
										.add("type", "mobile")
										.add("number", "111-111-1111"))
								.add(Json.createObjectBuilder()
										.add("type", "home")
										.add("number", "222-222-2222")))
				.build();

Traversing a JSON Object:

public static void navigateTree(JsonValue tree, String key) {
		if (key != null)
			System.out.print("Key " + key + ": ");
		switch (tree.getValueType()) {
		case OBJECT:
			System.out.println("OBJECT");
			JsonObject object = (JsonObject) tree;
			for (String name : object.keySet())
				navigateTree(object.get(name), name);
			break;
		case ARRAY:
			System.out.println("ARRAY");
			JsonArray array = (JsonArray) tree;
			for (JsonValue val : array)
				navigateTree(val, null);
			break;
		case STRING:
			JsonString st = (JsonString) tree;
			System.out.println("STRING " + st.getString());
			break;
		case NUMBER:
			JsonNumber num = (JsonNumber) tree;
			System.out.println("NUMBER " + num.toString());
			break;
		case TRUE:
		case FALSE:
		case NULL:
			System.out.println(tree.getValueType().toString());
			break;
		}

	}

How to write JSON Object to Stream?

try {
			StringWriter stringWriter = new StringWriter();
			JsonWriter jsonWriter = Json.createWriter(stringWriter);
			jsonWriter.writeObject(jsonObject);
			jsonWriter.close();

			FileWriter fileWriter = new FileWriter(new File("D:\\jsonDate.txt"));
			fileWriter.write(stringWriter.toString());
			fileWriter.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

Parsing Json Object Data:

JsonParser jsonParser = Json.createParser(new StringReader(
				jsonModelString.toString()));
		while (jsonParser.hasNext()) {
			JsonParser.Event event = jsonParser.next();
			if (event == event.KEY_NAME) {
				System.out.print(event.toString() + " "
						+ jsonParser.getString() + " - ");
			} else if (event == event.VALUE_NUMBER) {
				System.out.println(event.toString() + " "
						+ jsonParser.getString());
			} else if (event == event.VALUE_STRING) {
				System.out.println(event.toString() + " "
						+ jsonParser.getString());
			}
		}

Now the following is the complete picture of the above concepts

/**
 * 
 */
package com.spark.javaee;

import java.io.File;
import java.io.FileWriter;
import java.io.StringReader;
import java.io.StringWriter;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonString;
import javax.json.JsonValue;
import javax.json.JsonWriter;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonParser;

/**
 * @author Sony
 * 
 */
public class JsonJavaeeApiDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		JsonJavaeeApiDemo javaeeApiDemo = new JsonJavaeeApiDemo();
		JsonObject jsonObject = javaeeApiDemo.createJsonObject();
		javaeeApiDemo.createJsonDataFile(jsonObject);
		javaeeApiDemo.iterateObjectModel(jsonObject.toString());
		System.out.println("===============================================");
		javaeeApiDemo.generateJsonData(jsonObject);
		JsonJavaeeApiDemo.navigateTree(jsonObject, jsonObject.toString());
	}

	public void iterateObjectModel(String jsonModelString) {
		JsonParser jsonParser = Json.createParser(new StringReader(
				jsonModelString.toString()));
		while (jsonParser.hasNext()) {
			JsonParser.Event event = jsonParser.next();
			if (event == event.KEY_NAME) {
				System.out.print(event.toString() + " "
						+ jsonParser.getString() + " - ");
			} else if (event == event.VALUE_NUMBER) {
				System.out.println(event.toString() + " "
						+ jsonParser.getString());
			} else if (event == event.VALUE_STRING) {
				System.out.println(event.toString() + " "
						+ jsonParser.getString());
			}
		}
	}

	public JsonObject createJsonObject() {

		JsonObjectBuilder jsonObjectBuilder = (JsonObjectBuilder) Json
				.createObjectBuilder();
		JsonObject jsonObject = jsonObjectBuilder
				.add("firstName", "PavanKumar")
				.add("lastName", "Mantha")
				.add("age", 27)
				.add("streetAddress", "100 JavaEE RandD")
				.add("city", "Hyderabad")
				.add("state", "AP")
				.add("postalCode", "12345")
				.add("phoneNumbers",
						Json.createArrayBuilder()
								.add(Json.createObjectBuilder()
										.add("type", "mobile")
										.add("number", "111-111-1111"))
								.add(Json.createObjectBuilder()
										.add("type", "home")
										.add("number", "222-222-2222")))
				.build();
		return jsonObject;
	}

	public static void navigateTree(JsonValue tree, String key) {
		if (key != null)
			System.out.print("Key " + key + ": ");
		switch (tree.getValueType()) {
		case OBJECT:
			System.out.println("OBJECT");
			JsonObject object = (JsonObject) tree;
			for (String name : object.keySet())
				navigateTree(object.get(name), name);
			break;
		case ARRAY:
			System.out.println("ARRAY");
			JsonArray array = (JsonArray) tree;
			for (JsonValue val : array)
				navigateTree(val, null);
			break;
		case STRING:
			JsonString st = (JsonString) tree;
			System.out.println("STRING " + st.getString());
			break;
		case NUMBER:
			JsonNumber num = (JsonNumber) tree;
			System.out.println("NUMBER " + num.toString());
			break;
		case TRUE:
		case FALSE:
		case NULL:
			System.out.println(tree.getValueType().toString());
			break;
		}

	}

	public void createJsonDataFile(JsonObject jsonObject) {
		try {
			StringWriter stringWriter = new StringWriter();
			JsonWriter jsonWriter = Json.createWriter(stringWriter);
			jsonWriter.writeObject(jsonObject);
			jsonWriter.close();

			FileWriter fileWriter = new FileWriter(new File("D:\\jsonDate.txt"));
			fileWriter.write(stringWriter.toString());
			fileWriter.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void generateJsonData(JsonObject jsonObject) {
		try {
			FileWriter writer = new FileWriter("D:\\test.txt");
			JsonGenerator gen = Json.createGenerator(writer);
			gen.writeStartObject().write("firstName", "PavanKumar")
					.write("lastName", "Mantha").write("age", 27)
					.write("streetAddress", "100 javaEE RandD")
					.write("city", "JavaCity").write("state", "AP")
					.write("postalCode", "12345")
					.writeStartArray("phoneNumbers").writeStartObject()
					.write("type", "mobile").write("number", "111-111-1111")
					.writeEnd().writeStartObject().write("type", "home")
					.write("number", "222-222-2222").writeEnd().writeEnd()
					.writeEnd();
			gen.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

Happy Coding with JSON 🙂

courtesy: Oracle docs
ref:http://docs.oracle.com/javaee/7/tutorial/doc/jsonp.htm#GLRBB

BPEL HelloWorld Example with Eclipse and Apache ODE

Hi Guys as i explained in my previous post how to install Apache ODE and Eclipse BPEL Designer now im here to explain how to deploy the first BPEL process flow

Objective: deploying a BPEL process which receives an input string from a client and responses it exactly that input.
Tools: Eclipse 3.6.2, BPEL Designer 0.5.0 Plugin, Tomcat 7.0.12, ODE 1.3.5

step1.Create new BPEL project: File→New→Others→BPEL 2.0→BPEL Project.
step2.Name it BPEL_HelloWorld. Select the Target Runtime as Apache ODE 1.x Runtime and Configuration as Defaut Configuration for Apache ODE 1.x Runtime. Click Finish.

bpel_hello_world

step3.In the folder BPEL_HelloWorld\bpelContent, File → New → Other → BPEL 2.0 → New BPEL process file.
step4.Name it HelloWorld, Namespace http://helloworld.localhost and select Template Synchronous BPEL Process. Click Next.

bpel_hello_world1

step5.Edit the Service Address to : http://localhost:8080/ode/processes/HelloWorld (suppose that your Tomcat environment runs at port 8080) and keep other default declarations. Click Finish.

bpel_hello_world2

step6. Three files are created in the folder bpelContent and the HelloWorld.bpel is opened for editing the BPEL process.
step7. Click to open the Palette panel on the right of the canvas. (or right click on the canvas, select Show Pallette on Palette View)

bpel_hello_world3

step8. Drag the Assign action next to the receiveInput action and delete the FIX_ME-Add_Business_Logic_Here.

bpel_hello_world7

step9. Right click on the Assign activity. Select Show in properties.
step10.In the Properties tab, select Details. Click on the New button to define an assign operator.
step11.Assign from input→payload→input to output→payload→result. An Initializer popup dialog appear. Click Yes to initialize the output variable and save the process.

3ca9f195f7403fcc0bcb9f5a3029db16.media.900x433

step12. It’s time now to deploy the BPEL project. Click on the folder bpelContent, select File→New→Others→BPEL 2.0→Apache ODE Deployment Descriptor.
step13. Click Next. Verify the BPEL Project name as BPEL_HelloWorld. Click Finish.

bpel_hello_world5

step14 .Double click on the deploy.xml file in the bpelContent folder.
step15. In the Inbound Interfaces table, select the Partner Link as client, Associate Port as HelloWorldPort. Click on Related Service then other fields will be automatically filled. Save the deploy.xml file.

bpel_hello_world6

step16. To deploy the project on the server, right click on the Ode v1.x Server at localhost, select Add and Remove Projects.
step17.Select the BPEL_HelloWorld/HelloWorld in the Available projects box and click Add. Then, click Finish

bpel_hello_world8

step18. Start the ODE server. If the deployment was successful, you will see the following output in the console tab.

bpel_hello_world9

step19. We will test the project with Web Services Explorer provided by Eclipse. Right click on the HelloWorldArtifacts.wsdl file. Select Web Services→Test with Web Services Explorer.
step20. Select the operation process. Then, type Hello ODE in the input textbox. If your deployment was success, you will get the same string in the SOAP response.

bpel_hello_world10

We are Done
Happy Coding 🙂