Technical Blog Of JackCHAN

July 28, 2010

Create web service (3) — JAX-WS and JAX-WS Client

Filed under: java, myeclipse, webservice — Tags: , , — kaisechen @ 12:18 pm

In MyEclipse , it is very easy to build web service base on some web service framework.

Let’s build a JAX-WS web service.

1.Create a web service project in MyEclipse, which name is TestWS_JAXWS.

chose JAX-WS framework

It automatically produces J2EE directory.

2. import JAX-WS 2.1 library into the project

chose MyEclipse Libraries

Select JAX-WS 2.1 Libraries

3. Build a simple java which includes several methods

public class Calculator {
 public int add(int a, int b) {
 return (a + b);
 }

 public int subtract(int a, int b) {
 return (a - b);
 }

 public int multiply(int a, int b) {
 return (a * b);
 }

 public int divide(int a, int b) {
 return (a / b);
 }
}

4. Build a new web service

chose JAX-WS Framework and ‘Create web service from Java class’

In Java Class field, input ‘com.jack.ws.Calculator’ which is created at above step

It automatically fill in other fields,

Modify target namespace field to ‘http://localhost:8080/TestWS_JAXWS’

tick ‘Generate WSDL in project’

5. After click Finish button, it produces a lot of  files, directory and class

CalculatorDelegate class

wsdl directory, web.xml under WEB-INF

CalculatorDelegate.java

@javax.jws.WebService(targetNamespace = "http://localhost:8080/TestWS_JAXWS", serviceName = "CalculatorService", portName = "CalculatorPort", wsdlLocation = "WEB-INF/wsdl/CalculatorService.wsdl")
public class CalculatorDelegate {

 com.jack.ws.Calculator calculator = new com.jack.ws.Calculator();

 public int add(int a, int b) {
 return calculator.add(a, b);
 }

 public int subtract(int a, int b) {
 return calculator.subtract(a, b);
 }

 public int multiply(int a, int b) {
 return calculator.multiply(a, b);
 }

 public int divide(int a, int b) {
 return calculator.divide(a, b);
 }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <servlet>
 <description>JAX-WS endpoint - CalculatorService</description>
 <display-name>CalculatorService</display-name>
 <servlet-name>CalculatorService</servlet-name>
 <servlet-class>
 com.sun.xml.ws.transport.http.servlet.WSServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>CalculatorService</servlet-name>
 <url-pattern>/CalculatorPort</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <listener>
 <listener-class>
 com.sun.xml.ws.transport.http.servlet.WSServletContextListener
 </listener-class>
 </listener></web-app>

sun-jaxws.xml

<?xml version = "1.0"?>
<endpoints version="2.0"
 xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime">
 <endpoint name="CalculatorPort"
 implementation="com.jack.ws.CalculatorDelegate"
 url-pattern="/CalculatorPort">
 </endpoint></endpoints>

CalculatorService.wsdl

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.3-hudson-390-. -->
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://localhost:8080/TestWS_JAXWS" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="CalculatorService" targetNamespace="http://localhost:8080/TestWS_JAXWS">
 <types>
 <xsd:schema>
 <xsd:import namespace="http://localhost:8080/TestWS_JAXWS" schemaLocation="CalculatorService_schema1.xsd"/>
 </xsd:schema>
 </types>
 <message name="add">
 <part element="tns:add" name="parameters"/>
 </message>
 <message name="addResponse">
 <part element="tns:addResponse" name="parameters"/>
 </message>
 <message name="divide">
 <part element="tns:divide" name="parameters"/>
 </message>
 <message name="divideResponse">
 <part element="tns:divideResponse" name="parameters"/>
 </message>
 <message name="multiply">
 <part element="tns:multiply" name="parameters"/>
 </message>
 <message name="multiplyResponse">
 <part element="tns:multiplyResponse" name="parameters"/>
 </message>
 <message name="subtract">
 <part element="tns:subtract" name="parameters"/>
 </message>
 <message name="subtractResponse">
 <part element="tns:subtractResponse" name="parameters"/>
 </message>
 <portType name="CalculatorDelegate">
 <operation name="add">
 <input message="tns:add"/>
 <output message="tns:addResponse"/>
 </operation>
 <operation name="divide">
 <input message="tns:divide"/>
 <output message="tns:divideResponse"/>
 </operation>
 <operation name="multiply">
 <input message="tns:multiply"/>
 <output message="tns:multiplyResponse"/>
 </operation>
 <operation name="subtract">
 <input message="tns:subtract"/>
 <output message="tns:subtractResponse"/>
 </operation>
 </portType>
 <binding name="CalculatorPortBinding" type="tns:CalculatorDelegate">
 <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
 <operation name="add">
 <soap:operation soapAction=""/>
 <input>
 <soap:body use="literal"/>
 </input>
 <output>
 <soap:body use="literal"/>
 </output>
 </operation>
 <operation name="divide">
 <soap:operation soapAction=""/>
 <input>
 <soap:body use="literal"/>
 </input>
 <output>
 <soap:body use="literal"/>
 </output>
 </operation>
 <operation name="multiply">
 <soap:operation soapAction=""/>
 <input>
 <soap:body use="literal"/>
 </input>
 <output>
 <soap:body use="literal"/>
 </output>
 </operation>
 <operation name="subtract">
 <soap:operation soapAction=""/>
 <input>
 <soap:body use="literal"/>
 </input>
 <output>
 <soap:body use="literal"/>
 </output>
 </operation>
 </binding>
 <service name="CalculatorService">
 <port binding="tns:CalculatorPortBinding" name="CalculatorPort">
 <soap:address location="http://localhost:8080/TestWS_JAXWS/CalculatorPort"/>
 </port>
 </service>
</definitions>

6.Launch SOAP Web Service Explore to make a test to the web sercie

There are two Explores to be chosen. Select one.

Then click ‘WSDL Page’ in right-top , then click ‘WSDL Main’ in left-top

Input “http://localhost:8080/TestWS_JAXWS/CalculatorPort?WSDL&#8221;

Notice:

1) CalculatorPort  match the servlet-mapping in web.xml

2)?WSDL

This is a universal query string argument that can be added to the end of any web service which will tell the web service to return it’s full WSDL to the caller. In this case, the WSDL is returned to our Web Services Explorer tool which loads it up, and displays the web services exposed operations to us.

click ‘add’, ‘divide’,’subtract’,’multiply’ etc methods

e.g. add, input 100, 555, add go, then will get a return value:655

e.g. subtract, input 1000, 20 , will get 980

7. Build a new Java project as the client to use the web service, which name is TestWS_JAXWSClient

8. Build a new web service client in the project

Chose JAX-WS framework

In WSDL URL input ‘http://localhost:8080/TestWS_JAXWS/CalculatorPort?wsdl&#8217;

Create a java package

It has  a WSDL validation, click finish button

9. It automatically produces a lot of classes under new created java package

It is very easy to understand the meaning of those classes from literal

10. Build a Test Class in the java client project

public class Test {
public static void main(String[] args) {
CalculatorService  cs = new CalculatorService();
CalculatorDelegate cd = cs.getCalculatorPort();
System.out.println("3 + 10    = "+cd.add(3,10));
System.out.println("999 - 222 = "+cd.subtract(999,222));
System.out.println("250 / 5   = "+cd.divide(250, 5));
System.out.println("7 * 23    = "+cd.multiply(7,23));
}
}

11. Run Test.java, it will get

3 + 10    = 13
999 - 222 = 777
250 / 5   = 50
7 * 23    = 161

package com.jack.ws;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;

/**
* This class was generated by the JAX-WS RI. JAX-WS RI 2.1.3-hudson-390-
* Generated source version: 2.0
* <p>
* An example of how this class may be used:
*
* <pre>
* CalculatorService service = new CalculatorService();
* CalculatorDelegate portType = service.getCalculatorPort();
* portType.add(…);
* </pre>
*
* </p>
*
*/
@WebServiceClient(name = “CalculatorService”, targetNamespace = “http://localhost:8080/TestWS_JAXWS&#8221;, wsdlLocation = “http://localhost:8080/TestWS_JAXWS/CalculatorPort?wsdl&#8221;)
public class CalculatorService extends Service {

private final static URL CALCULATORSERVICE_WSDL_LOCATION;
private final static Logger logger = Logger
.getLogger(com.jack.ws.CalculatorService.class.getName());

static {
URL url = null;
try {
URL baseUrl;
baseUrl = com.jack.ws.CalculatorService.class.getResource(“.”);
url = new URL(baseUrl,
http://localhost:8080/TestWS_JAXWS/CalculatorPort?wsdl&#8221;);
} catch (MalformedURLException e) {
logger
.warning(“Failed to create URL for the wsdl Location: ‘http://localhost:8080/TestWS_JAXWS/CalculatorPort?wsdl&#8217;, retrying as a local file”);
logger.warning(e.getMessage());
}
CALCULATORSERVICE_WSDL_LOCATION = url;
}

public CalculatorService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}

public CalculatorService() {
super(CALCULATORSERVICE_WSDL_LOCATION, new QName(
http://localhost:8080/TestWS_JAXWS&#8221;, “CalculatorService”));
}

/**
*
* @return returns CalculatorDelegate
*/
@WebEndpoint(name = “CalculatorPort”)
public CalculatorDelegate getCalculatorPort() {
return super.getPort(new QName(“http://localhost:8080/TestWS_JAXWS&#8221;,
“CalculatorPort”), CalculatorDelegate.class);
}

}

July 27, 2010

Create web service (2) — XFire Client

Filed under: java, myeclipse, webservice — Tags: , , , , — kaisechen @ 1:46 pm

We build a  java client to invoke the XFire web service

1.Create a java project in MyEclipse,  which name is TestWS_XFireClient

2.Add XFire client library

chose ‘MyEclipse Libraries’

chose ‘XFire 1.2 HTTP Client Libraries’

click finish, it will import two libraries into the project

3.import the TestWS_XFire project as the dependency project of ‘TestWS_XFireClient’

4. Build a WeatherClient class

import java.net.MalformedURLException;

import org.codehaus.xfire.XFireFactory;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.binding.ObjectServiceFactory;

public class WeatherClient {

 /**
 * @param args
 */
 public static void main(String[] args) {
 Service srvcModel = new ObjectServiceFactory().create(Iweather.class);
 XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
 .newInstance().getXFire());
 String weatherURL = "http://localhost:8080/TestWS_XFire/services/weather";
 try {
 Iweather srvc = (Iweather) factory.create(srvcModel, weatherURL);
 String result = srvc.example("Jack");
 System.out.print(result);
 } catch (MalformedURLException e) {
 e.printStackTrace();
 }
 }

}

5. run WeatherClient and it will get the result listed below:

Hello JACK ,Welcome the world of Web Service

Create web service (1) — XFire ( the old version of Apache CXF)

Filed under: java, myeclipse, webservice — Tags: , , — kaisechen @ 1:20 pm

At the moment, there are a lot of web service framework.

Firstly, let’s try to build XFire web service.  XFire is now CXF(http://cxf.apache.org/).

Codehaus XFire is a next-generation java SOAP framework. Codehaus XFire makes service oriented development approachable through its easy to use API and support for standards. It is also highly performant since it is built on a low memory StAX based model.

1. Create a Web Service Project, which name is TestWS_XFire

Chose XFire Framework  and java EE 5.0.

2. MyEclipse automatically produces J2EE directory including web.xml file, importing XFile 1.2 core libraries

3. In XFire framework, it has a XFireServlet servlet

the content of web.xml is listed below

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <servlet>
 <servlet-name>XFireServlet</servlet-name>
 <servlet-class>org.codehaus.xfire.transport.http.XFireConfigurableServlet</servlet-class>
 <load-on-startup>0</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>XFireServlet</servlet-name>
 <url-pattern>/services/*</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

4.Create a new web service

select web service

chose XFire Framework

chose ‘create web service from Java class ‘ and tick ‘Create new Java bean’

5. Input web service name, create a new java package,and MyEclipse will produce interface and impl class base on the service name, chose default soap style/use

6.MyEclipse will produce a interface and implements class, at the same time it will fill in service.xml

interface Iweather

public interface Iweather {
 
 public String example(String message);
 
}

modify class weatherImpl

public class weatherImpl implements Iweather {
 
 public String example(String message) {
 String reStr = "Hello "+message.toUpperCase()+" ,Welcome the world of Web Service";
 return reStr;
 }
 
}

services.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xfire.codehaus.org/config/1.0">

 <service>
 <name>weather</name>
 <serviceClass>com.jack.ws.Iweather</serviceClass>
 <implementationClass>
 com.jack.ws.weatherImpl
 </implementationClass>
 <style>wrapped</style>
 <use>literal</use>
 <scope>application</scope>
 </service></beans>

7. run tomcat 6 server

8. deploy the app into tomcat 6 server


9.The outcome of tomcat console

27/07/2010 10:58:06 PM org.apache.catalina.startup.HostConfig checkResources
INFO: Reloading context [/TestWS_XFire]
27/07/2010 10:58:06 PM org.springframework.context.support.AbstractApplicationContext close
INFO: Closing application context [org.codehaus.xfire.spring.GenericApplicationContext;hashCode=13501060]
27/07/2010 10:58:06 PM org.springframework.beans.factory.support.AbstractBeanFactory destroySingletons
INFO: Destroying singletons in factory {org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans [xfire.customEditorConfigurer,xfire.serviceRegistry,xfire.transportManager,xfire,xfire.typeMappingRegistry,xfire.aegisBindingProvider,xfire.serviceFactory,xfire.servletController,xfire.messageServiceFactory,xfire.messageBindingProvider,org.codehaus.xfire.spring.ServiceBean]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans []; root of BeanFactory hierarchy}
27/07/2010 10:58:07 PM org.springframework.context.support.AbstractApplicationContext refresh
INFO: No beans defined in application context [org.codehaus.xfire.transport.http.XFireConfigurableServlet$GenericWebApplicationContextX;hashCode=5493403]
27/07/2010 10:58:07 PM org.springframework.context.support.AbstractApplicationContext initMessageSource
INFO: Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@d81c91]
27/07/2010 10:58:07 PM org.springframework.context.support.AbstractApplicationContext initApplicationEventMulticaster
INFO: Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@3b7f4e]
27/07/2010 10:58:07 PM org.springframework.ui.context.support.UiApplicationContextUtils initThemeSource
INFO: Unable to locate ThemeSource with name 'themeSource': using default [org.springframework.ui.context.support.ResourceBundleThemeSource@22fde7]
27/07/2010 10:58:07 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in factory [org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans []; root of BeanFactory hierarchy]
27/07/2010 10:58:07 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [org/codehaus/xfire/spring/xfire.xml]
27/07/2010 10:58:07 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [org/codehaus/xfire/spring/customEditors.xml]
27/07/2010 10:58:07 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [META-INF/xfire/services.xml]
27/07/2010 10:58:07 PM org.springframework.context.support.AbstractApplicationContext refresh
INFO: 11 beans defined in application context [org.codehaus.xfire.spring.GenericApplicationContext;hashCode=30062719]
27/07/2010 10:58:08 PM org.springframework.context.support.AbstractApplicationContext initMessageSource
INFO: Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@1abe751]
27/07/2010 10:58:08 PM org.springframework.context.support.AbstractApplicationContext initApplicationEventMulticaster
INFO: Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@df8508]
27/07/2010 10:58:08 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in factory [org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans [xfire.customEditorConfigurer,xfire.serviceRegistry,xfire.transportManager,xfire,xfire.typeMappingRegistry,xfire.aegisBindingProvider,xfire.serviceFactory,xfire.servletController,xfire.messageServiceFactory,xfire.messageBindingProvider,org.codehaus.xfire.spring.ServiceBean]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans []; root of BeanFactory hierarchy]
27/07/2010 10:58:08 PM org.codehaus.xfire.spring.ServiceBean afterPropertiesSet
INFO: Exposing service with name {http://ws.jack.com}weather

10. Launch SOAP Web Services Explorer in MyEclipse

11.Click ‘WSDL Main’, input ‘http://localhost:8080/TestWS_XFire/services/weather&#8217;

12.click go, it will present ‘Operations’ and ‘Endpoints’

13. click example, then input ‘jack’,and then click ‘go’

14. check the exampleResponse

exampleResponse
out (string):  Hello JACK ,Welcome the world of Web Service

Create Message Driven Bean (3) –JMS Topic and Topic Client

Filed under: ejb, jboss, myeclipse — Tags: , , , — kaisechen @ 2:19 am

1. Build a TopicEJB class in MessageDrivenEJB project

Add annotation ‘@ActivationConfigProperty(propertyName = “destination”, propertyValue = “topic/weatherTopic”)’

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.StreamMessage;
import javax.jms.TextMessage;

@MessageDriven(mappedName = "jms/TopicEJB", activationConfig = {
 @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
 @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
 @ActivationConfigProperty(propertyName = "clientId", propertyValue = "TopicEJB"),
 @ActivationConfigProperty(propertyName = "destination", propertyValue = "topic/weatherTopic"),
 @ActivationConfigProperty(propertyName = "subscriptionName", propertyValue = "TopicEJB") })
public class TopicEJB implements MessageListener {

 public void onMessage(Message msg) {
 try {
 System.out.println(msg.getJMSDestination());// the name of message queue

 if (msg instanceof TextMessage) { //         1.text message
 TextMessage message = (TextMessage) msg;
 System.out.println(message.getText());
 } else if (msg instanceof MapMessage) {//    2.map message
 MapMessage mapMessage = (MapMessage) msg;
 System.out.println(mapMessage.getString("hello"));
 } else if (msg instanceof ObjectMessage) {// 3. object message
 ObjectMessage objectMessage = (ObjectMessage) msg;
 System.out.println(objectMessage.getObject());
 } else if (msg instanceof BytesMessage) {//  4. byte message
 BytesMessage bytesMessage = (BytesMessage) msg;
 System.out.println(bytesMessage.getStringProperty("byte"));
 } else if (msg instanceof StreamMessage) {// 5.stream message
 StreamMessage streamMessage = (StreamMessage) msg;
 System.out.println(streamMessage.getStringProperty("stream"));
 }

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

}

2.In destinations-service.xml, add topic mbean

<?xml version="1.0" encoding="UTF-8"?>
<server>
 <mbean code="org.jboss.mq.server.jmx.Queue" name="jboss.mq.destination:service=Queue,name=ztfQueue">
 <attribute name="JNDIName">queue/ztfQueue</attribute>
 <depends optional-attribute-name="DestinationManager">jboss.mq:service=DestinationManager</depends>
 </mbean>
 <mbean code="org.jboss.mq.server.jmx.Topic" name="jboss.mq.destination:service=Topic,name=weatherTopic">
 <attribute name="JNDIName">topic/weatherTopic</attribute>
 <depends optional-attribute-name="DestinationManager">jboss.mq:service=DestinationManager</depends>
 </mbean>
</server>

Make sure the propertyValue of destination in TopicEJB class is same of attribute of JNDIName in destinations-service.xml

3. Re-deploy the MessageDrivenEJB project into jboss5 server

4. Re-start jboss5 server

5. Create a MessageDrivenEJB class in MessageDrivenEJBClient project

import java.util.Properties;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.StreamMessage;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class TopicMDBClient {

 public static void main(String[] args) {
 Properties env = new Properties();
 env.put("java.naming.factory.initial",
 "org.jnp.interfaces.NamingContextFactory");
 env.put("java.naming.factory.url.pkgs",
 "org.jboss.naming:org.jnp.interfaces");
 env.put("java.naming.provider.url", "localhost");

 InitialContext ctx;
 try {
 ctx = new InitialContext(env);

 TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx
 .lookup("ConnectionFactory");
 TopicConnection topicConnection = topicConnectionFactory
 .createTopicConnection();
 TopicSession session =
 topicConnection.createTopicSession(false,
 Session.CLIENT_ACKNOWLEDGE);

 // find the topic
 Topic topic = (Topic) ctx.lookup("topic/weatherTopic");
 TopicPublisher publisher = session.createPublisher(topic);

 /**
 * There are five type message
 */

 // 1. text message
 TextMessage msg = session
 .createTextMessage("Hello, this is a text message. I got it.");
 publisher.send(msg);

 // 2. map message
 MapMessage mapMessage = session.createMapMessage();
 mapMessage.setString("hello",
 "I have seen the part of the world of Map Message");
 publisher.send(mapMessage);

 // 3. byte message
 BytesMessage bytesMessage = session.createBytesMessage();
 bytesMessage.setStringProperty("byte", "This is a byte message");
 publisher.send(bytesMessage);

 // 4. object message
 ObjectMessage objectMessage = session.createObjectMessage();
 objectMessage.setObject(new String(
 "The object can be any type of object"));
 publisher.send(objectMessage);

 // 5. stream message
 StreamMessage streamMessage = session.createStreamMessage();
 streamMessage.setStringProperty("stream",
 "stream messages usually are file and picture");
 publisher.send(streamMessage);

 } catch (JMSException e) {
 e.printStackTrace();
 } catch (NamingException e) {
 e.printStackTrace();
 }
 }

}

6.Run TopicMDBClient in MessageDrivenEJBClient project

7.Switch to jboss5 Console

12:16:40,109 INFO  [STDOUT] JBossTopic[weatherTopic]
12:16:40,109 INFO  [STDOUT] JBossTopic[weatherTopic]
12:16:40,109 INFO  [STDOUT] Hello, this is a text message. I got it.
12:16:40,109 INFO  [STDOUT] JBossTopic[weatherTopic]
12:16:40,109 INFO  [STDOUT] This is a byte message
12:16:40,109 INFO  [STDOUT] stream messages usually are file and picture
12:16:40,109 INFO  [STDOUT] JBossTopic[weatherTopic]
12:16:40,109 INFO  [STDOUT] JBossTopic[weatherTopic]
12:16:40,109 INFO  [STDOUT] I have seen the part of the world of Map Message
12:16:40,109 INFO  [STDOUT] The object can be any type of object

Create Message Driven Bean (2) –JMS Queue Client

Filed under: ejb, java, jboss, myeclipse — Tags: , , , — kaisechen @ 2:04 am

1. Create a Java project in MyEclipse, which name is MessageDrivenEJBClient

2.Import Jboss5 User Library in this project

3.Build a client class

import java.util.Properties;

import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.StreamMessage;
import javax.jms.TextMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class QueueMDBClient {

 public static void main(String[] args) {
 Properties env = new Properties();
 env.put("java.naming.factory.initial",
 "org.jnp.interfaces.NamingContextFactory");
 env.put("java.naming.factory.url.pkgs",
 "org.jboss.naming:org.jnp.interfaces");
 env.put("java.naming.provider.url", "localhost");

 InitialContext ctx;
 try {
 ctx = new InitialContext(env);

 QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory");
 QueueConnection conn = factory.createQueueConnection();

 QueueSession session = conn.createQueueSession(false,QueueSession.AUTO_ACKNOWLEDGE);
 // find the destination
 Destination destination  = (Destination) ctx.lookup("queue/ztfQueue");
 MessageProducer producer = session.createProducer(destination);

 /**
 * There are five type message
 */
 // 1. text message (Yes)
 TextMessage msg = session
 .createTextMessage("Hello, this is a text message. I got it.");
 producer.send(msg);
 // 2. map message (No)
 MapMessage mapMessage = session.createMapMessage();
 mapMessage.setString("hello", "I have seen the part of the world of Map Message");
 producer.send(mapMessage);
 // 3. byte message (No)
 BytesMessage bytesMessage = session.createBytesMessage();
 bytesMessage.setStringProperty("byte", "This is a byte message");
 producer.send(bytesMessage);
 // 4. object message (No)
 ObjectMessage objectMessage = session.createObjectMessage();
 objectMessage.setObject(new String("The object can be any type of object"));
 producer.send(objectMessage);
 // 5. stream message (OK)
 StreamMessage streamMessage = session.createStreamMessage();
 streamMessage.setStringProperty("stream", "stream messages usually are file and picture");
 producer.send(streamMessage);
 producer.close();
 //EJB 2.1 rule
 Queue queue = (Queue)ctx.lookup("queue/ztfQueue");
 QueueSender sender = session.createSender(queue);
 msg = session.createTextMessage("Now, we use EJB 2.1 rule to send message.Hello, this is a text message.");
 sender.send(msg);
 sender.send(mapMessage);
 sender.send(bytesMessage);
 sender.send(objectMessage);
 sender.send(streamMessage);
 sender.close();
 //close session
 session.close();
 //close connection
 conn.close();
 } catch (JMSException e) {
 e.printStackTrace();
 } catch (NamingException e) {
 e.printStackTrace();
 }
 }
}

4. Run the java project

5. Swith to jboss5 Server Console in MyEclipse

We can see that the Queue MDB receives variety messages and prints them to console.

1:55:02,390 INFO  [STDOUT] JBossQueue[ztfQueue]
11:55:02,390 INFO  [STDOUT] JBossQueue[ztfQueue]
11:55:02,390 INFO  [STDOUT] JBossQueue[ztfQueue]
11:55:02,390 INFO  [STDOUT] JBossQueue[ztfQueue]
11:55:02,390 INFO  [STDOUT] JBossQueue[ztfQueue]
11:55:02,390 INFO  [STDOUT] Now, we use EJB 2.1 rule to send message.Hello, this is a text message.
11:55:02,390 INFO  [STDOUT] JBossQueue[ztfQueue]
11:55:02,406 INFO  [STDOUT] JBossQueue[ztfQueue]
11:55:02,406 INFO  [STDOUT] This is a byte message
11:55:02,406 INFO  [STDOUT] JBossQueue[ztfQueue]
11:55:02,406 INFO  [STDOUT] JBossQueue[ztfQueue]
11:55:02,406 INFO  [STDOUT] This is a byte message
11:55:02,406 INFO  [STDOUT] JBossQueue[ztfQueue]
11:55:02,406 INFO  [STDOUT] I have seen the part of the world of Map Message
11:55:02,406 INFO  [STDOUT] Hello, this is a text message. I got it.
11:55:02,406 INFO  [STDOUT] stream messages usually are file and picture
11:55:02,406 INFO  [STDOUT] stream messages usually are file and picture
11:55:02,421 INFO  [STDOUT] The object can be any type of object
11:55:02,421 INFO  [STDOUT] The object can be any type of object
11:55:02,421 INFO  [STDOUT] I have seen the part of the world of Map Message

Create Message Driven Bean (1) –JMS Queue

Filed under: ejb, java, jboss, myeclipse — Tags: , , — kaisechen @ 1:43 am

1. Create a new EJB project in MyEclipse, which name is MessageDrivenEJB

chose EJB3.0, don’t tick ‘Add support for Entity beans’

2.create a new Message Driven Bean class


chose Queue Destination Type

3. The QueueEJB class will automatically implements MessageListener and it will add MessageDriven etc annotation.

add ‘@ActivationConfigProperty(propertyName = “destination”, propertyValue = “queue/ztfQueue”)’

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.StreamMessage;
import javax.jms.TextMessage;

@MessageDriven(mappedName = "jms/QueueEJB", activationConfig = {
 @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
 @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/ztfQueue"),
 @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") })
public class QueueEJB implements MessageListener {

 public void onMessage(Message msg) {
 try {
 if(msg ==null){
 System.out.println("msg is null");
 return;
 }
 System.out.println(msg.getJMSDestination());// the name of message queue
 if (msg instanceof TextMessage) { //         1.text message
 TextMessage message = (TextMessage) msg;
 System.out.println(message.getText());
 } else if (msg instanceof MapMessage) {//    2.map message
 MapMessage mapMessage = (MapMessage) msg;
 if(mapMessage!=null){
 System.out.println(mapMessage.getString("hello"));
 }else{
 System.out.println(mapMessage);
 }
 } else if (msg instanceof ObjectMessage) {// 3. object message
 ObjectMessage objectMessage = (ObjectMessage) msg;
 if(objectMessage!=null){
 System.out.println(objectMessage.getObject());
 }else{
 System.out.println("objectMessage is null");
 }
 } else if (msg instanceof BytesMessage) {//  4. byte message
 BytesMessage bytesMessage = (BytesMessage) msg;
 System.out.println(bytesMessage.getStringProperty("byte"));
 } else if (msg instanceof StreamMessage) {// 5.stream message
 StreamMessage streamMessage = (StreamMessage) msg;
 System.out.println(streamMessage.getStringProperty("stream"));
 }
 } catch (JMSException e) {
 e.printStackTrace();
 }
 }

}

4.Build a destinations-service.xml under META-INF directory in MessageDrivenEJB project

destinations-service.xml

<?xml version="1.0" encoding="UTF-8"?>
<server>
<mbean code="org.jboss.mq.server.jmx.Queue" name="jboss.mq.destination:service=Queue,name=ztfQueue">
<attribute name="JNDIName">queue/ztfQueue</attribute>
<depends optional-attribute-name="DestinationManager">jboss.mq:service=DestinationManager</depends>
</mbean>
<mbean code="org.jboss.mq.server.jmx.Topic" name="jboss.mq.destination:service=Topic,name=weatherTopic">
<attribute name="JNDIName">topic/weatherTopic</attribute>
<depends optional-attribute-name="DestinationManager">jboss.mq:service=DestinationManager</depends>
</mbean>
</server>

5.run or restart Jboss5 server

6. Deploy the project into Jboss5 server


7. The result shown in console

11:38:48,203 INFO  [EJBContainer] STARTED EJB: com.jack.ejb.QueueEJB ejbName: QueueEJB
11:38:48,531 INFO  [EJBContainer] STARTED EJB: com.jack.ejb.TopicEJB ejbName: TopicEJB
11:38:48,859 INFO  [QueueService] Queue[queue/ztfQueue] started, fullSize=200000, pageSize=2000, downCacheSize=2000
11:38:49,062 INFO  [TopicService] Topic[topic/weatherTopic] started, fullSize=200000, pageSize=2000, downCacheSize=2000

July 26, 2010

EJB3 Annotation

Filed under: ejb, java, Technology — Tags: , , — kaisechen @ 6:06 am

1. Bean Types and Transaction and Security

2. Callbacks and Resources

3.Interceptors, Ealier View Client, Queries, ResultSetMapping

4.Object-Relational-Mapping

5.Relations, Inheritance

6.Embedded Values,Generators,Legend

Create EJB Enitiy Bean Example In MyEclipse (2)

Filed under: ejb, java, jboss, myeclipse, Technology — Tags: , , , — kaisechen @ 2:35 am

Now, we will create a JAVA project as the remote client invoking stateless session bean in EntityEJBUserManager project.

1. Create a Java project which name is ‘EntityEJBUserManagerClient’

2.import ‘EntityEJBUserManager.jar’ which exported through ‘EntityEJBUserManager’ project

3.import Jboss5 User Library which includes all jar in D:/jboss5/client/

4.import Hibernate3 User Library which includes the necessary jar of Hibernate 3.3.1

5. Create a client class

import java.util.List;
import java.util.Properties;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.jack.ejb.domain.User;
import com.jack.ejb.inter.UserDAO;

public class UserDAOClient {

 /**
 * @param args
 */
 public static void main(String[] args) {
 Properties env = new Properties();
 env.put("java.naming.factory.initial",
 "org.jnp.interfaces.NamingContextFactory");
 env.put("java.naming.factory.url.pkgs",
 "org.jboss.naming:org.jnp.interfaces");
 env.put("java.naming.provider.url", "localhost");

 InitialContext ctx;
 UserDAO userdao;
 try {
 ctx = new InitialContext(env);
 userdao = (UserDAO) ctx.lookup("UserDAOBean/remote");

 System.out.println(".................................");
 System.out.println("Insert a user....................");
 boolean re = userdao.insert("Hello World", "Male");
 System.out.println("The result of insert a user is "+re);
 re = userdao.insert("EntityBean", "FeMale");
 System.out.println("The result of insert a user is "+re);

 System.out.println(".................................");
 System.out.println("Get a user.......................");

 User user = userdao.get(1);
 System.out.println("ID:1 and Name:"+user.getName()+" Sex:"+user.getSex());

 System.out.println(".................................");
 System.out.println("Update a user ...................");

 User user1 = userdao.get(1);
 user1.setName("UpdateEJB");
 userdao.update(user1);

 System.out.println("ID:"+user1.getId()+" and Name:"+user1.getName()+" Sex:"+user1.getSex());

 System.out.println(".................................");
 System.out.println("Get a user list..................");

 List<User> userlist = userdao.getUserList();
 for(User u:userlist){
 System.out.println("ID:"+u.getId()+" and Name:"+u.getName()+" Sex:"+u.getSex());
 }

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

}

6.run the java project and will get the result listed below

7. Check the MySQL database, and will have the result listed below

8. Check the admin console of jboss5, we can get more information

URL:http://localhost:8082/jmx-console/

Create EJB Enitiy Bean Example In MyEclipse (1)

Filed under: ejb, java, myeclipse, Technology — Tags: , , — kaisechen @ 1:59 am

EJB3 becomes more continent than EJB2. It saves a lot of time to build a EJB project using MyEclipse.

1. Create a new EJB project in MyEclipse, which name is ‘EntityEJBUserManager

Chose EJB3.0 , tick ‘Add support for Entity beans(add JPA capabilities)’

2.MyEclipse will automatically produce a “persistence.xml” file

2.1 configue jta data source,’java:/DefaultMySQLDS’

2.2 add property

<properties>
 <property name="hibernate.hbm2ddl.auto" value="create"/>
 </properties>

3. import MySQL  driver

4. copy D:\jboss5\docs\examples\jca\mysql-ds.xml and modify it, then copy the file into D:\jboss5\server\default\deploy

<?xml version="1.0" encoding="UTF-8"?>

<!-- $Id: mysql-ds.xml 41017 2006-02-07 14:26:14Z acoliver $ -->
<!--  Datasource config for MySQL using 3.0.9 available from:
http://www.mysql.com/downloads/api-jdbc-stable.html
-->

<datasources>
 <local-tx-datasource>
 <jndi-name>DefaultMySQLDS</jndi-name>
 <connection-url>jdbc:mysql://localhost:3308/ejb</connection-url>
 <driver-class>com.mysql.jdbc.Driver</driver-class>
 <user-name>ejb</user-name>
 <password>ejb</password>
 <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
 <!-- should only be used on drivers after 3.22.1 with "ping" support
 <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
 -->
 <!-- sql to call when connection is created
 <new-connection-sql>some arbitrary sql</new-connection-sql>
 -->
 <!-- sql to call on an existing pooled connection when it is obtained from pool - MySQLValidConnectionChecker is preferred for newer drivers
 <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
 -->

 <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
 <metadata>
 <type-mapping>mySQL</type-mapping>
 </metadata>
 </local-tx-datasource>
</datasources>

Please notice: the name of jndi-name is ‘DefaultMySQLDS’, match the jta-data-source in persistence.xml

5. Create a Entity Bean ‘User’

please notice annotation ‘Entity’ and ‘Table’ above class  and ‘ID’ above id property.

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="User")
public class User implements Serializable {
 /**
 *
 */
 private static final long serialVersionUID = 6136720247591443052L;
 private int id;
 private String name;
 private String sex;

 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 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 getSex() {
 return sex;
 }

 public void setSex(String sex) {
 this.sex = sex;
 }

}

6. Create a interface ‘UserDAO’

import java.util.List;

import com.jack.ejb.domain.User;

public interface UserDAO {
 public boolean insert(String name,String sex);
 public User get(int id);
 public List<User> getUserList();
 public boolean update(User user);
}

7. Create a stateless session bean ‘UserDAOBean’ implements UserDAO

please notice it uses ‘Remote’ annotation

import java.util.List;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.jack.ejb.domain.User;
import com.jack.ejb.inter.UserDAO;

@Stateless
@Remote(UserDAO.class)
public class UserDAOBean implements UserDAO {
 @PersistenceContext
 protected EntityManager em; 

 public User get(int id) {
 User user = em.find(User.class, Integer.valueOf(id));
 return user;
 }

 @SuppressWarnings("unchecked")
 public List<User> getUserList() {
 Query query = em.createQuery("from User order by name");
 return (List<User>)query.getResultList();
 }

 public boolean insert(String name, String sex) {
 User user = new User();
 user.setName(name);
 user.setSex(sex);
 em.persist(user);
 return true;
 }

 public boolean update(User user) {
 em.merge(user);
 return true;
 }

}

8. Export ‘User’ class and ‘UserDAO’ interface into ‘EntityEJBUserManager.jar’, so java client project can import it later.

9. run jboss 5 server

10. Deploy the EJB project into Jboss 5 server

July 25, 2010

Web Service Interview Questions and Answers

Filed under: Technology, webservice — Tags: , — kaisechen @ 6:24 am

What is a Web service?
Many people and companies have debated the exact definition of Web services. At a minimum, however, a Web service is any piece of software that makes itself available over the Internet and uses a standardized XML messaging system.
XML is used to encode all communications to a Web service. For example, a client invokes a Web service by sending an XML message, then waits for a corresponding XML response. Because all communication is in XML, Web services are not tied to any one operating system or programming language–Java can talk with Perl; Windows applications can talk with Unix applications.
Beyond this basic definition, a Web service may also have two additional (and desirable) properties:
First, a Web service can have a public interface, defined in a common XML grammar. The interface describes all the methods available to clients and specifies the signature for each method. Currently, interface definition is accomplished via the Web Service Description Language (WSDL). (See FAQ number 7.)
Second, if you create a Web service, there should be some relatively simple mechanism for you to publish this fact. Likewise, there should be some simple mechanism for interested parties to locate the service and locate its public interface. The most prominent directory of Web services is currently available via UDDI, or Universal Description, Discovery, and Integration. (See FAQ number 8.)
Web services currently run a wide gamut from news syndication and stock-market data to weather reports and package-tracking systems. For a quick look at the range of Web services currently available, check out the XMethods directory of Web services.

What is new about Web services?
People have been using Remote Procedure Calls (RPC) for some time now, and they long ago discovered how to send such calls over HTTP.
So, what is really new about Web services? The answer is XML.
XML lies at the core of Web services, and provides a common language for describing Remote Procedure Calls, Web services, and Web service directories.
Prior to XML, one could share data among different applications, but XML makes this so much easier to do. In the same vein, one can share services and code without Web services, but XML makes it easier to do these as well.
By standardizing on XML, different applications can more easily talk to one another, and this makes software a whole lot more interesting.

I keep reading about Web services, but I have never actually seen one. Can you show me a real Web service in action?
If you want a more intuitive feel for Web services, try out the IBM Web Services Browser, available on the IBM Alphaworks site. The browser provides a series of Web services demonstrations. Behind the scenes, it ties together SOAP, WSDL, and UDDI to provide a simple plug-and-play interface for finding and invoking Web services. For example, you can find a stock-quote service, a traffic-report service, and a weather service. Each service is independent, and you can stack services like building blocks. You can, therefore, create a single page that displays multiple services–where the end result looks like a stripped-down version of my.yahoo or my.excite.

What is the Web service protocol stack?

The Web service protocol stack is an evolving set of protocols used to define, discover, and implement Web services. The core protocol stack consists of four layers:
Service Transport: This layer is responsible for transporting messages between applications. Currently, this includes HTTP, SMTP, FTP, and newer protocols, such as Blocks Extensible Exchange Protocol (BEEP).
XML Messaging: This layer is responsible for encoding messages in a common XML format so that messages can be understood at either end. Currently, this includes XML-RPC and SOAP.
Service Description: This layer is responsible for describing the public interface to a specific Web service. Currently, service description is handled via the WSDL.
Service Discovery: This layer is responsible for centralizing services into a common registry, and providing easy publish/find functionality. Currently, service discovery is handled via the UDDI.
Beyond the essentials of XML-RPC, SOAP, WSDL, and UDDI, the Web service protocol stack includes a whole zoo of newer, evolving protocols. These include WSFL (Web Services Flow Language), SOAP-DSIG (SOAP Security Extensions: Digital Signature), and USML (UDDI Search Markup Language). For an overview of these protocols, check out Pavel Kulchenko’s article, Web Services Acronyms, Demystified, on XML.com.
Fortunately, you do not need to understand the full protocol stack to get started with Web services. Assuming you already know the basics of HTTP, it is best to start at the XML Messaging layer and work your way up.

What is XML-RPC?
XML-RPC is a protocol that uses XML messages to perform Remote Procedure Calls. Requests are encoded in XML and sent via HTTP POST; XML responses are embedded in the body of the HTTP response.
More succinctly, XML-RPC = HTTP + XML + Remote Procedure Calls.
Because XML-RPC is platform independent, diverse applications can communicate with one another. For example, a Java client can speak XML-RPC to a Perl server.
To get a quick sense of XML-RPC, here is a sample XML-RPC request to a weather service (with the HTTP Headers omitted):
<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<methodCall>
<methodName>weather.getWeather</methodName>
<params>
<param><value>10016</value></param>
</params>
</methodCall>
The request consists of a simple element, which specifies the method name (getWeather) and any method parameters (zip code).

Here is a sample XML-RPC response from the weather service:

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<methodResponse>
<params>
<param>
<value><int>65</int></value>
</param>
</params>
</methodResponse>
The response consists of a single element, which specifies the return value (the current temperature). In this case, the return value is specified as an integer.
In many ways, XML-RPC is much simpler than SOAP, and therefore represents the easiest way to get started with Web services.
The official XML-RPC specification is available at XML-RPC.com. Dozens of XML-RPC implementations are available in Perl, Python, Java, and Ruby. See the XML-RPC home page for a complete list of implementations.

What is SOAP?
SOAP is an XML-based protocol for exchanging information between computers. Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport protocols, the main focus of SOAP is Remote Procedure Calls (RPC) transported via HTTP. Like XML-RPC, SOAP is platform independent, and therefore enables diverse applications to communicate with one another.

To get a quick sense of SOAP, here is a sample SOAP request to a weather service (with the HTTP Headers omitted):

<?xml version=’1.0′ encoding=’UTF-8′?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV=”http://www.w3.org/2001/09/soap-envelope&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xmlns:xsd=”http://www.w3.org/2001/XMLSchema”&gt;
<SOAP-ENV:Body>
<ns1:getWeather
xmlns:ns1=”urn:examples:weatherservice”
SOAP-ENV:encodingStyle=” http://www.w3.org/2001/09/soap-encoding
<zipcode xsi:type=”xsd:string”>10016</zipcode>
</ns1:getWeather>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
As you can see, the request is slightly more complicated than XML-RPC and makes use of both XML namespaces and XML Schemas. Much like XML-RPC, however, the body of the request specifies both a method name (getWeather), and a list of parameters (zipcode).

Here is a sample SOAP response from the weather service:

<?xml version=’1.0′ encoding=’UTF-8′?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV=”http://www.w3.org/2001/09/soap-envelope&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xmlns:xsd=”http://www.w3.org/2001/XMLSchema”&gt;
<SOAP-ENV:Body>
<ns1:getWeatherResponse
xmlns:ns1=”urn:examples:weatherservice”
SOAP-ENV:encodingStyle=”http://www.w3.org/2001/09/soap-encoding”&gt;
<return xsi:type=”xsd:int”>65</return>
</ns1:getWeatherResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The response indicates a single integer return value (the current temperature).
The World Wide Web Consortium (W3C) is in the process of creating a SOAP standard. The latest working draft is designated as SOAP 1.2, and the specification is now broken into two parts. Part 1 describes the SOAP messaging framework and envelope specification. Part 2 describes the SOAP encoding rules, the SOAP-RPC convention, and HTTP binding details.

What is WSDL?

The Web Services Description Language (WSDL) currently represents the service description layer within the Web service protocol stack.
In a nutshell, WSDL is an XML grammar for specifying a public interface for a Web service. This public interface can include the following:

Information on all publicly available functions.
Data type information for all XML messages.
Binding information about the specific transport protocol to be used.
Address information for locating the specified service.

WSDL is not necessarily tied to a specific XML messaging system, but it does include built-in extensions for describing SOAP services.

Below is a sample WSDL file. This file describes the public interface for the weather service used in the SOAP example above. Obviously, there are many details to understanding the example. For now, just consider two points.
First, the <message> elements specify the individual XML messages that are transferred between computers. In this case, we have a getWeatherRequest and a getWeatherResponse. Second, the element specifies that the service is available via SOAP and is available at a specific URL.

<?xml version=”1.0″ encoding=”UTF-8″?>
<definitions name=”WeatherService”
targetNamespace=”http://www.ecerami.com/wsdl/WeatherService.wsdl&#8221;
xmlns=”http://schemas.xmlsoap.org/wsdl/&#8221;
xmlns:soap=”http://schemas.xmlsoap.org/wsdl/soap/&#8221;
xmlns:tns=”http://www.ecerami.com/wsdl/WeatherService.wsdl&#8221;
xmlns:xsd=”http://www.w3.org/2001/XMLSchema”&gt;
<message name=”getWeatherRequest”>
<part name=”zipcode” type=”xsd:string”/>
</message>
<message name=”getWeatherResponse”>
<part name=”temperature” type=”xsd:int”/>
</message>

<portType name=”Weather_PortType”>
<operation name=”getWeather”>
<input message=”tns:getWeatherRequest”/>
<output message=”tns:getWeatherResponse”/>
</operation>
</portType>

<binding name=”Weather_Binding” type=”tns:Weather_PortType”>
<soap:binding style=”rpc”
transport=”http://schemas.xmlsoap.org/soap/http”/&gt;
<operation name=”getWeather”>
<soap:operation soapAction=””/>
<input>
<soap:body
encodingStyle=”http://schemas.xmlsoap.org/soap/encoding/&#8221;
namespace=”urn:examples:weatherservice”
use=”encoded”/>
</input>
<output>
<soap:body
encodingStyle=”http://schemas.xmlsoap.org/soap/encoding/&#8221;
namespace=”urn:examples:weatherservice”
use=”encoded”/>
</output>
</operation>
</binding>

<service name=”Weather_Service”>
<documentation>WSDL File for Weather Service</documentation>
<port binding=”tns:Weather_Binding” name=”Weather_Port”>
<soap:address
location=”http://localhost:8080/soap/servlet/rpcrouter”/&gt;
</port>
</service>
</definitions>
Using WSDL, a client can locate a Web service, and invoke any of the publicly available functions. With WSDL-aware tools, this process can be entirely automated, enabling applications to easily integrate new services with little or no manual code. For example, check out the GLUE platform from the Mind Electric.
WSDL has been submitted to the W3C, but it currently has no official status within the W3C. See this W3C page for the latest draft.

What is UDDI?
UDDI (Universal Description, Discovery, and Integration) currently represents the discovery layer within the Web services protocol stack.
UDDI was originally created by Microsoft, IBM, and Ariba, and represents a technical specification for publishing and finding businesses and Web services.
At its core, UDDI consists of two parts.
First, UDDI is a technical specification for building a distributed directory of businesses and Web services. Data is stored within a specific XML format, and the UDDI specification includes API details for searching existing data and publishing new data.
Second, the UDDI Business Registry is a fully operational implementation of the UDDI specification. Launched in May 2001 by Microsoft and IBM, the UDDI registry now enables anyone to search existing UDDI data. It also enables any company to register themselves and their services.
The data captured within UDDI is divided into three main categories:
White Pages: This includes general information about a specific company. For example, business name, business description, and address.
Yellow Pages: This includes general classification data for either the company or the service offered. For example, this data may include industry, product, or geographic codes based on standard taxonomies.
Green Pages: This includes technical information about a Web service. Generally, this includes a pointer to an external specification, and an address for invoking the Web service.
You can view the Microsoft UDDI site, or the IBM UDDI site. The complete UDDI specification is available at uddi.org.
Beta versions of UDDI Version 2 are available at:
Hewlett Packard
IBM
Microsoft
SAP

How do I get started with Web Services?
The easiest way to get started with Web services is to learn XML-RPC. Check out the XML-RPC specification. O’Reilly has also recently released a book on Programming Web Services with XML-RPC by Simon St.Laurent, Joe Johnston, and Edd Dumbill.
Once you have learned the basics of XML-RPC, move onto SOAP, WSDL, and UDDI. These topics are also covered in Web Services Essentials. For a comprehensive treatment of SOAP, check out O’Reilly’s Programming Web Services with SOAP, by Doug Tidwell, James Snell, and Pavel Kulchenko.

Does the W3C support any Web service standards?
The World Wide Web Consortium (W3C) is actively pursuing standardization of Web service protocols. In September 2000, the W3C established an XML Protocol Activity. The goal of the group is to establish a formal standard for SOAP. A draft version of SOAP 1.2 is currently under review, and progressing through the official W3C recommendation process.
On January 25, 2002, the W3C also announced the formation of a Web Service Activity. This new activity will include the current SOAP work as well as two new groups. The first new group is the Web Services Description Working Group, which will take up work on WSDL. The second new group is the Web Services Architecture Working Group, which will attempt to create a cohesive framework for Web service protocols.

Older Posts »

Create a free website or blog at WordPress.com.