Monday, April 12, 2010

JAX-WS Web service with Maven

One of my earlier post Building JAX-WS Webservice was using Ant as build tool for developing web services. With each passing day Maven is gaining more popularity and became preferred build tool for many developers. I used to get emails from several readers about working JAX-WS examples with Maven as build tool. In this post I will try to demonstrate to publish and consume a JAX-WS web service using Maven.

The source code used in this post is available here, which will be referred at several places in this post.

The jaxws-maven-plugin has two goals wsgen and wsimport.

  • wsgen - This reads a service endpoint implementation class and generates all of the portable artifacts for a JAX-WS web service. With newer versions (tested with 2.2) of JAX-WS, execution of this task is not required for publishing webservice
  • wsimport - This tool reads WSDL and generates client side artifacts. We will be using this goal for generating client and consuming a web service.

Publish Web service

For publishing a web service we need to write an interface and its implementation then annotate them with relevant annotations. The JAX-WS libraries should be added as dependency in pom.xml. A sample (partial) build script is shown below-

<dependencies>
    <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-rt</artifactId>
        <scope>compile</scope>
        <version>2.2</version>
    </dependency>
</dependencies>
. . .
<build>
    <plugins>
        <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>maven-jetty-plugin</artifactId>
            <configuration>
                <scanIntervalSeconds>10</scanIntervalSeconds>
                <connectors>
                    <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                        <port>8080</port>
                        <maxIdleTime>60000</maxIdleTime>
                    </connector>
                </connectors>
            </configuration>
        </plugin>
    </plugins>
</build>

We can see in the above Maven script that the wsgen is not required. The JAX-WS implementation will take care of that at runtime. To make testing easier I have used Jetty plugin, which will publish the web service for further consumption by the client in next step. To publish the web service invoke following command in 'webservice' directory of the source code of this post-
mvn -e clean compile jetty:run

Create Client

For creating web service client the wsimport goal of jaxws-maven-plugin will be used. The wsimport goal creates portable client artifacts by parsing a WSDL. In this example the WSDL URL is the one which was published by starting the web service at previous step. The pom.xml of client side application will look like below-

<dependencies>
    <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-rt</artifactId>
        <scope>compile</scope>
        <version>2.2</version>
    </dependency>
</dependencies>
. . .
<build>
    <plugins>
        <!-- Generate client using WSDL -->
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jaxws-maven-plugin</artifactId>
            <configuration>
                <packageName>wsclient</packageName>
                <wsdlUrls>
                    <wsdlUrl>http://localhost:8080/webservice/myService?wsdl</wsdlUrl>
                </wsdlUrls>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.1</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>client.WsClient</mainClass>
            </configuration>
        </plugin>
    </plubins>
</build>

For the sake of simplicity I have used exec-maven-plugin here, which will run the test class to invoke the web service from build script itself. To generate client and run the test class, trigger the build from 'webservice-client' directorty using following command-
mvn -e clean compile exec:java


The examples shown above were tested with following configuration-
  • Java 1.6.18
  • JAX-WS 2.
  • Maven 2.2.1
  • Windows XP

Note:- If JAX-WS 2.2 is used with older versions of Java 6 (e.g. Java 1.6.03) then you may encounter errors like shown below-
SEVERE: WSSERVLET11: failed to parse runtime descriptor: java.lang.LinkageError: JAXB 2.1 API is being loaded from the bootstrap classloader, but this RI (from jar:file:/C:/Documents%20and%20Settings/Vinod%20Singh/.m2/repository/com/sun/xml/bind/jaxb-impl/2.2/jaxb-impl-2.2.jar!/com/sun/xml/bind/v2/model/impl/ModelBuilder.class) needs 2.2 API. Use the endorsed directory mechanism to place jaxb-api.jar in the bootstrap classloader. (See http://java.sun.com/j2se/1.6.0/docs/guide/standards/)
java.lang.LinkageError: JAXB 2.1 API is being loaded from the bootstrap classloader, but this RI (from jar:file:/C:/Documents%20and%20Settings/Vinod%20Singh/.m2/repository/com/sun/xml/bind/jaxb-impl/2.2/jaxb-impl-2.2.jar!/com/sun/xml/bind/v2/model/impl/ModelBuilder.class) needs 2.2 API. Use the endorsed directory mechanism to place jaxb-api.jar in the bootstrap classloader. (See http://java.sun.com/j2se/1.6.0/docs/guide/standards/) at com.sun.xml.bind.v2.model.impl.ModelBuilder.(ModelBuilder.java:173)

The reason of these errors is that the earlier versions of Java 6 are using lower versions of JAX-WS while we are trying to use higher version of JAX-WS. To overcome these errors either we need to downgrade the JAX-WS version in our runtime environment or use endorsed directory mechanism.

Hope this will be useful to some of the readers.

Thursday, December 10, 2009

Send XML data over web service

Occasionally I am being asked a common question, "How to send XML data over web service?". In Java (in fact in any programming language) XML is just a string (sequence of characters). So sending XML as request parameter or receiving it in response is just like handling any other string data.

For the following XML data from web service client and server-

XML from client
<name>vinod</name>

XML from server
<greeting>Hello! vinod</greeting>

This is the web service (JAX-WS) request and response-
REQUEST
<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:xmlData xmlns:ns2="http://vinodsingh.com">
            <data>&lt;name&gt;vinod&lt;/name&gt;</data>
        </ns2:xmlData>
    </S:Body>
</S:Envelope>

RESPONSE
<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:xmlDataResponse xmlns:ns2="http://vinodsingh.com">
            <return>&lt;greeting>Hello! vinod&lt;/greeting></return>
        </ns2:xmlDataResponse>
    </S:Body>
</S:Envelope>

The above example clearly shows that JAX-WS runtime handles XML strings pretty well. The source code available here includes an example of sending bigger XML data.

Thursday, March 12, 2009

How to get operation name in JAX-WS handler

With web services at times one needs to know the name of the method (operation) being invoked before it is really invoked. A typical scenario is the authorization, where access to method is restricted to certain roles only. The JAX-WS RI 2.0 used to hold the name of the operation being invoked in SOAPMessageContext, which can be obtained in following manner-

soapMessageContext.get(MessageContext.WSDL_OPERATION);

Unfortunately JAX-WS RI 2.1.x no longer have this information and JAX-WS team is not ready to provide it as they said this is optional. Then what is the workaround when someone really needs it? Looking for clues I ran JAX-WS RI 2.1.5 code in Eclispe debugger and found operation name in non-public classes / variables as shown in the following screenshot-



Now equipped with this information operation name can be extracted using reflection API-

    private String getMethodName(SOAPMessageContext context, boolean isRequest) {
    try {
        Field field = context.getClass().getSuperclass().getDeclaredField(
            "packet");
        field.setAccessible(true);
        Packet packet = (Packet) field.get(context);

        if (isRequest)
        return ((StreamMessage) packet.getMessage())
            .getPayloadLocalPart();

        return ((JAXBMessage) packet.getMessage()).getPayloadLocalPart();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
    }
Though this is not a clean way and may not work with future releases of JAX-WS RI but works for now :-)

Saturday, December 20, 2008

Let Spring load service class for JAX-WS

During deployment JAX-WS RI by default creates an instance (singleton) of web service implementation class and uses that to serve requests. At times we may want to customize the instantiation of the web service implementation class e.g. let Spring configure and load the object.

JAX-WS Commons has an extension for Spring integration, which delegates total configuration to Spring and makes RI specific files (sun-jaxws.xml) redundant. Currently I am happy with the way JAX-WS RI exposes web services and do not want everything to move to Spring or something else. I was just looking for a way to load the service implementation class by my code instead of RI doing so. JAX-WS RI has a poorly documented (or may be I am not able find it easily) feature called InstanceResolver, which lets developers to customize the way service implementation class is loaded. The code snippets below demostrate how to so-

public class MyResolver extends InstanceResolver<Object> {

    private final Object serviceImpl;

    /**
     * @param clazz
     */
    public MyResolver(Class<?> clazz) {
        serviceImpl= . . . load the class here or get it from Spring or somewhere else . . .;
    }

    /**
     * @see com.sun.xml.ws.api.server.InstanceResolver#resolve(com.sun.xml.ws.api.message.Packet)
     */
    @Override
    public Object resolve(Packet request) {
        return serviceImpl;
    }

}

// Now create an Annotation, which has @InstanceResolverAnnotation with MyResolver.class
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@InstanceResolverAnnotation(MyResolver.class)
public @interface MyWs {
}

// Now annotate the service class with above-mentioned annotation
@WebService(endpointInterface = "com.vinodsingh.Address")
@MyWs
public class AddressImpl implements Address {
    . . .
}

During deployment (WSServletContextListener) JAX-WS RI iterates through all annotations on the service class and sees if there is any annotation annotated with @InstanceResolverAnnotation. On finding one it will delegate the task of creating instance of the service class to the user defined InstanceResolver. With this I am able to load service classes using Spring.

Sunday, December 07, 2008

Locally packaged WSDL

As discussed in my earlier post Consuming web services with Spring, web service client initialization might fail due to non-availability of the running web service. We can overcome this limiting factor by packaging the WSDL with client and using that for creating the instance of client stub and during service method invocation use the live URL of the service. Have a look at Packaging dynamic resources with Maven to know more about packaging. The following code snippet shows how to use locally packaged WSDL and live service URL-

// during instantiation use the locally packaged WSDL
WebServiceClient ann = AddressService.class.getAnnotation(WebServiceClient.class);  
URL wsdlURL = this.getClass().getResource("/wsdl/AddressService.wsdl");

AddressService serviceObj = new AddressService(wsdlURL, new QName(ann.targetNamespace(), ann.name()));
Address service = serviceObj.getAddressPort();
BindingProvider bp = ((BindingProvider) service);
Map<String, Object> context = bp.getRequestContext();

// set the live URL of the service, which will be used during service method invocations
context.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "LIVE URL OF THE WEB SERVICE");

Sunday, November 23, 2008

Consuming web services with Spring

Consuming web services with Spring framework is amazingly easy. It avoids the need of creating client side stubs during compile time and does the same at run time. A typical web service client can be configured as shown below-

<bean id="myWebService" class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean">
    <property name="serviceInterface" value="pkg.MyService"/>
    <property name="wsdlDocumentUrl" value="http://localhost:8080/testws/myService?wsdl"/>
    <property name="namespaceUri" value="http://com.pkg/"/>
    <property name="serviceName" value="MyService"/>
    <property name="portName" value="MyServicePort"/>
</bean>
Where serviceInterface is the business interface that clients will use for invoking service methods. wsdlDocumentUrl is the URL for the published WSDL file. Spring will download WSDL from the given URL and generate the client side stubs when it creates the bean usually during application start up. namespaceUri corresponds to the targetNamespace in the .wsdl file. serviceName corresponds to the service name in the .wsdl file. portName corresponds to the port name in the .wsdl file.

Now accessing web service pretty easy, just get the bean from Spring context and use that to invoke methods-
MyService myService = springContext.getBean("myWebService");
myService.someMethod(. . .);
One downside of this approach is that the web service must be up running when consumer application is being deployed. To avoid this problem one can use lazy-init="true" to lazily initialize the beans when they are first requested but all this quickly becomes unmanageable when we have an array of SOA based applications. In such a scenario one have to strictly follow the order of application deployment else deployment might fail.

Thursday, September 25, 2008

Using JAX-WS Handlers

The JAX-WS provides a good facility to do pre/post processing on SOAP messages using SOAPHandler. The handlers are useful for auditing, logging and potentialy some more functionality. In this entry I will try to explain a typical usage of handlers for logging the SOAP messages. Every handler class needs to implement javax.xml.ws.handler.soap.SOAPHandler interface as shown below-
public class LoggingHandler implements SOAPHandler<SOAPMessageContext> {

    @Override
    public Set<QName> getHeaders() {
        return null;
    }

    @Override
    public void close(MessageContext context) {
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        logToSystemOut(context);
        return true;
    }

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        logToSystemOut(context);
        return true;
    }

    private void logToSystemOut(SOAPMessageContext smc) {
        Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

        if (outboundProperty.booleanValue()) {
            System.out.println("\nOutgoing message:");
        } else {
            System.out.println("\nIncoming message:");
        }

        SOAPMessage message = smc.getMessage();
        try {
            message.writeTo(System.out);
        } catch (Exception e) {
            System.out.println("Exception in handler: " + e);
        }
    }

}
Now create a handler confiuration file say 'handlers.xml' as shown below and put it in 'WEB-INF' directory of your application.

<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
   <handler-chain>
      <handler>
         <handler-class>my.server.pkg.LoggingHandler</handler-class>
      </handler>
   </handler-chain>
</handler-chains>
Using @HandlerChain annotation we can instruct the JAX-WS runtime to apply the handlers configured in the above-mentioned configuration on a web service endpoint-
@WebService(endpointInterface = "my.server.pkg.IMyService")
@HandlerChain(file = "handlers.xml")
public class MyServiceImpl implements IMyService {
Now all incoming and outgoing SOAP messages will be logged to standard output stream. Source code for this example is available here.
For developing and deploying web services see my earlier posts-
http://blog.vinodsingh.com/2008/09/building-jax-ws-web-service.html
http://blog.vinodsingh.com/2008/09/jax-ws-web-service-and-jboss.html

Friday, September 19, 2008

JAX-WS web service and JBoss

Yesterday I wrote an entry about building JAX-WS web service. So thought about testing them on latest versions of JBoss. I chose 4.2.3 and 5.0.0 CR2 (released yesterday), both with Java 6.

JBoss 4.2.3
The deployment of web service failed with following error-

Error configuring application listener of class com.sun.xml.ws.transport.http.servlet.WSServletContextListener
java.lang.ClassNotFoundException: com.sun.xml.ws.transport.http.servlet.WSServletContextListener


which looks quite natural as JBoss has its own implementation of JAX-WS, so it does not have the RI classes. After bundling RI jars with application deployment was error free. I created a small standalone program to invoke the web service, which succeeded without any errors.

What about if web service consumer is also a web application? To test this scenario I created a small web application to consume the above-mentioned service and deployed on JBoss. On invoking web service the following exception was thrown-

org.jboss.ws.metadata.wsdl.WSDLException: Invalid default namespace: null

I thought that by bundling JAX-WS jars with the application, I can overcome this error. But faced another exception-
com.sun.xml.ws.client.WSServiceDelegate cannot be cast to javax.xml.ws.spi.ServiceDelegate21

Now I started scratching my head :-/ When in difficulty the developer community takes help of Google, but here Google did not gave clues. After investigating the JBoss directory structure and their contents I discovered an endorsed directory at ‘jboss-4.2.3.GA\lib\endorsed’ location. Then I deleted all jars (related to JAXB, JAXWS and JAAS) from there except the following ones-
  • Serializer.jar
  • Xalan.jar
  • xercesImpl.jar
and copied JAX-WS RI jars here. Now everything worked even no need to bundle the JAX-WS jars with the applications.

JBoss 5 RC2
Making the web service work on this version of the JBoss also required same steps as with 4.2.3 and service was consumed by a standalone application without any hiccups. Then tried to consume the service using same web application as used for 4.2.3 and with JBoss 5 also it failed with similar error on trying to invoke a service method-

org.jboss.ws.metadata.wsdl.WSDLException: Invalid default namespace: null

On bundling JAX-WS RI jars with the consumer application everything worked fine, so no more ClassCastException or using the endorsed directory mechanism. This is a good improvement over previous versions of JBoss.

Wednesday, September 17, 2008

Building JAX-WS web service

Last year I wrote a small step by step guide to build JAX-RPC web services. Now JAX-RPC has been replaced by new standard JAX-WS, so I thought it is good time to write an entry for JAX-WS as well. Building web services with JAX-WS is pretty straight forward though it might look cumbersome to a newbie. In this entry I am going explain the basic steps for building a Java first web service, which I developed and tested with JAX-WS 2.1.4, Java 6 update 6 and Tomcat 6.0.16.

Step #1 - Write an interface

@WebService(targetNamespace = "http://vinodsingh.com", name = "MyService")
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL)
public interface MyService {

    String sayHello(@WebParam(name = "name") String name);
}

Step #2 - Implement the interface
@WebService(endpointInterface = "pkg.MyService")
public class MyServiceImpl implements MyService {

    @Override
    public String sayHello(String name) {
        return "Hello " + name + "!";
    }
}

Step #3 - Configure web.xml

The JAX-WS context listener and servlet are required to be configured in deployment descriptor (web.xml). The WSServletContextListener initializes and configures the web service endpoint and WSServlet serves the service requests using implementing class.
<listener>
    <listener-class>
        com.sun.xml.ws.transport.http.servlet.WSServletContextListener
    </listener-class>
</listener>
<servlet>
    <servlet-name>jaxws</servlet-name>
    <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>jaxws</servlet-name>
    <url-pattern>/myService</url-pattern>
</servlet-mapping>

Step #4 - sun-jaxws.xml

The JAX-WS RI uses information available in this file while initializing and configuring a web service endpoint. This file should be present in WEB-INF directory.
<endpoints
    xmlns='http://java.sun.com/xml/ns/jax-ws/ri/runtime'
    version='2.0'>
    <endpoint
        name='myService'
        implementation='pkg.MyServiceImpl'
        url-pattern='/myService' />
</endpoints>

Step #5 - Build and deploy

Here is an Ant script to prepare the server side stuff-
<!-- Define classpath. -->
<path id="jaxws.classpath">
    <pathelement location="${java.home}/../lib/tools.jar" />
    <fileset dir="${jaxws.lib.dir}">
        <include name="*.jar" />
    </fileset>
</path>

<!-- Declare ant tasks required to generate service and client. -->
<taskdef name="apt" classname="com.sun.tools.ws.ant.Apt" classpathref="jaxws.classpath" />
<taskdef name="wsgen" classname="com.sun.tools.ws.ant.WsGen" classpathref="jaxws.classpath" />
<taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport" classpathref="jaxws.classpath" />

<!-- Run the 'apt' tool on annotated code to generate server side stuff. -->
<target name="buildService">
    <apt fork="true" destdir="${classes.dir}" 
         sourcepath="${src.main.dir}" 
         sourcedestdir="${gensrc.dir}" 
         debug="${debug}" verbose="${verbose}" classpathref="jaxws.classpath">
        <source dir="${src.main.dir}">
            <include name="**/MyServiceImpl.java" />
        </source>
    </apt>

    <jar destfile="${build.home}/server.jar" basedir="${classes.dir}" compress="true" />
</target>

Now package all this in a WAR file and deploy on the server. The web service can be accessed at http://localhost:8080/testws/myService (URL may change according to the server configuration).

Update Feb 13, 2009: With latest versions of Java 6 and JAX-WS, apt task is optional. See this comment below.

Step #6 - Generate client

And this script will generate client side stubs. Here first we are generating WSDL and then using that to generate client side stubs. Though we can avoid the WSDL generation and use the live URL by deploying the web service on a server but usually that is not feasible in a project where build process is automated.
<!-- Generate the client, for that first WSDL needs to be generated. -->
<target name="genClient" depends="buildServer">
    <wsgen sei="pkg.MyServiceImpl" 
        resourcedestdir="${gen.wsdl.dir}" 
        sourcedestdir="${gensrc.dir}/client" 
        destdir="${classes.dir}/client" 
        genwsdl="true" verbose="${verbose}" keep="true">
        <classpath>
            <pathelement location="${classes.dir}/server" />
        </classpath>
    </wsgen>

    <wsimport destdir="${classes.dir}/client" 
        sourcedestdir="${gensrc.dir}/client" 
        package="pkg" debug="${debug}" 
        wsdl="${gen.wsdl.dir}\MyServiceImplService.wsdl" 
        xendorsed="true" keep="true" />

    <jar jarfile="${build.home}/ws-client.jar" basedir="${classes.dir}/client" compress="true" />
</target>

Step #7 - Invoke the service

Here is the sample code to invoke the web service, which we just built and deployed.
// Get a handle to web service client interface
WebServiceClient ann = MyServiceImplService.class.getAnnotation(WebServiceClient.class);
MyServiceImplService service = new MyServiceImplService(new URL(
    "http://localhost:8080/testws/myService"), 
    new QName(ann.targetNamespace(), ann.name()));
MyService myService = service.getMyServiceImplPort();

// Invoke methods
String hello = myService.sayHello("Vinod");
System.out.println(hello);

Thats it. We are done. Source code of this example is available here.

Update Apr 12, 2010 - A new post JAX-WS Web service with Maven shows usage of Maven as build script for building JAX-WS web services.

Friday, September 05, 2008

AnyType object over webservice and Hibernate

Recently I came across a requirement of moving objects over the network using web services (JAX-WS 2.1). The application was CRUD in nature and Hibernate was used as data tier on the server. In case of web service usually we have WSDL, which clearly defines the kind of objects it expects in request and response. So we can have add/modify/delete/retrieve methods for each type of entity in the WSDL. This approach seems to be doable when we have very few entities. But in our case we were having too many entities and the WSDL was going to be very huge and repetitive in nature. Then what is the way out!!!

I created a base class say BaseEntity.java, which is just a place holder having no variables or methods. Each entity was made to extend BaseEntity.java. The methods in web service interface were having signature like-

@XmlSeeAlso( { MyActualEntity.class })
public interface DataService {

   public void add(BaseEntity object);
}
In the implementing class of the web service interface, Hibernate can determine the actual class name handles that properly to insert the data in correct table. So all seems to be set on the server side, what about client side?

After generating client side stubs when I tried to add an instance of MyActualEntity.java, JAXB complaint that it does not know anything about MyActualEntity. JAXB was absolutely right, it knows only about those data types, which are mentioned in WSDL and MyActualEntity was not part of the WSDL. Then how shall I tell the JAXB about the real entities :-/

We can add the complexType definitions for all entities in the WSDL, but lazy resisted that ;-)
After doing some research I found @XmlSeeAlso annotation., which can be applied on the web service interface. When wsgen task encounters the @XmlSeeAlso annotation, it will include those classes in the WSDL. Now JAXB knows about MyActualEntity and sends that across the wire.

Seems to be a good trick :-)

Saturday, May 31, 2008

Webservice endpoint

The Java JAX-RPC implementation used to create simple to use web service clients, where developer can easily change the web service endpoint as shown below-

MyWsImpl stub = new MyWsImplService_Impl().getXXX();
((Stub) stub)._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, "http://myHost/myWs/myWs");

See this entry for details about building JAX-RPC web services.

The JAX-WS has changed the way it generates the clients. As a general practice people keep the WSDL along with their code and create the client side stubs at the build time. The JAX-WS hard codes the WSDL path in the client stub. See the one such generated code below-
package cache;

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.WebServiceClient;

@WebServiceClient(name = "MyServiceImplService", targetNamespace = "http://c.b.a/", wsdlLocation = "file:/D:/Test/temp/wsdl/MyServiceImplService.wsdl")
public class MyServiceImplService extends Service {

private final static URL MYSERVICEIMPLSERVICE_WSDL_LOCATION;
private final static Logger logger = Logger
.getLogger(MyServiceImplService.class.getName());

static {
URL url = null;
try {
URL baseUrl;
baseUrl = MyServiceImplService.class.getResource(".");
url = new URL(baseUrl,
"file:/D:/Test/temp/wsdl/MyServiceImplService.wsdl");
} catch (MalformedURLException e) {
logger.warning("Failed to create URL for the wsdl Location: 'file:/D:/Test/temp/wsdl/MyServiceImplService.wsdl', retrying as a local file");
logger.warning(e.getMessage());
}
MYSERVICEIMPLSERVICE_WSDL_LOCATION = url;
}

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

public MyServiceImplService() {
super(MYSERVICEIMPLSERVICE_WSDL_LOCATION, new QName("http://c.b.a/",
"MyServiceImplService"));
}
}
If one tries to create an instance of client using the default constructor then it looks for the WSDL file at the location hard coded in the class and might fail with FileNotFoundException. The workaround for this problem is to call the another consturcutor, passing the endpoint URL and QName. Creating this QName is quite annoying and also that may change in future changes to WSDL. Then what is the easy wayout?

If you look closely at the web service client, it has an annotation @WebServiceClient, which has all the information to create the QName dynamically.
WebServiceClient ann = MyServiceImplService.class
.getAnnotation(WebServiceClient.class);
MyServiceImplService service = new MyServiceImplService(
new URL("ENDPOINT URL OF MY SERVICE"),
new QName(ann.targetNamespace(), ann.name()));

Now it looks pretty simple, is not it?

Monday, May 05, 2008

@Stateless + @WebService +Weblogic 10 = :-(

On my last project we have to expose some stateless session beans as web service as well. The deployment platform was Weblogic 10 MP1. For the initial few weeks everything (development, deployment and testing) went fine and then all of a sudden Weblogic refused to deploy couple of EJBs without any error messages. The general observation is, if a class has both @Stateless and @WebService on a single java class and number of code lines grow beyond some limit (our classes have around 350 lines) then Weblogic has issues with them. If we reduced the code by commenting out some code or removing some methods then deployment went well.

This is not the only issue with Weblogic, one more equally weird observation is that @EJB annotations does not work when a class has both @Stateless and @WebService.

Monday, November 19, 2007

Monitor SOAP messages

While developing Web Services at times one has to look for what is going out and coming in during web service interaction. Eclipse has a built-in TCP/IP Monitor but somehow I did not have a good experience using it.

Apache SOAP project has small utility called TCP Tunnel/Monitor, which is available here. TCP Tunnel/Monitor can be started using follwing command-

set CLASSPATH=%CLASSPATH%;./soap.jar;
java org.apache.soap.util.net.TcpTunnelGui 80 localhost 8080

Here first option 80 is the port where TcpTunnel will listen on your machine (localhost). The second parameter is the target address (the local machine in this case). The final parameter 8080 is the port where it will forward the calls to desired server as specified in 2nd parameter.

The TCP Tunnel/Monitor application is really just a simple proxy application that includes a visual interface to view the request response XML. TCP Tunnel/Monitor will display a window with two text areas:




* The text area on the left shows the request.
* The text area on the right shows the response received from the target server.

Tuesday, August 14, 2007

Bottom Up JAX-RPC web service with JWSDP

A simple step by step guide to develop a bottom up web service using Java Web Services Developer Pack.

Step #1 Install JWSDP

Download Java Web Services Developer Pack 1.6 (JWSDP) from http://java.sun.com/webservices/downloads/webservicespack.html and install it. The installation directory will be called hereafter as $JWSDP_HOME.

Step #2 Write code and Package war file

Write an interface and implementation of it. This interface will be exposed as web service through servlet end-point. Write a configuration file named jaxrpc-ri.xml and save it in WEB-INF folder of the project. This configuration file contains information about web service interface and it’s implementation, location of WSDL file, web service URL. All these information will be used by JWSDP at the time of processing input war file for generating web service.

The jaxrpc-ri.xml looks like below-

<?xml version="1.0" encoding="UTF-8"?>
  <webServices
    xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/dd"
    version="1.0"
    targetNamespaceBase="http://myhost/myService"
    typeNamespaceBase="http://myhost/types"
    urlPatternBase="/myWs">

  <endpoint
    name="MyWebService"
    displayName="My Web Service"
    description="Test JAX-RPC web service"
    wsdl="/WEB-INF/myWs.wsdl"
    interface="myPackage.MyWsInterface"
    implementation="myPackage.MyWsImplementation" />

  <endpointMapping
    endpointName="MyWebService"
    urlPatternBase="/myWs" />

</webServices>
The web.xml must have following entries-
<listener>
  <listener-class>com.sun.xml.rpc.server.http.JAXRPCContextListener</listener-class>
</listener>
<servlet>
  <servlet-name>myWs</servlet-name>
  <servlet-class>com.sun.xml.rpc.server.http.JAXRPCServlet</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>myWs</servlet-name>
  <url-pattern>/myWs</url-pattern>
</servlet-mapping>

Step #3 Process war file

Copy above created war file say myWS-in.war to $JWSDP_HOME/jaxrpc/bin directory and create a directory named tmp there. Open command prompt and go to above mentioned directory and fire following command-

$ wsdeploy -o myWs.war myWs-in.war -keep -tmpdir ./tmp -verbose

This will create a war file
myWs.war, which is ready to be deployed on Tomcat.

Step #4 Deploy Processed war file on Tomcat

Now deploy the processed war file,
myWs.war on Tomcat and start Tomcat.

Step #5 Generate Web Service client

Create a file named config.xml with following contents-
<configuration xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
  <wsdl location="http://localhost:8080/myWs/myWs?WSDL"
  packagename="myWsClient" />
</configuration>
Here location is the URL of the web service WSDL, which may change according to server installation, hence update it accordingly and packageName is the package name of the generated web service client classes, which could also be changed to anything.
Save config.xml in $JWSDP_HOME/jaxrpc/bin directory. Now fire following command-
$ wscompile -gen:client -keep config.xml

This will create a directory name
$JWSDP_HOME/jaxrpc/bin/myWsClient, create a jar file containing this directory. This way web service client is ready. This directory name depends upon the packageName specified in config.xml.

An example of client accessing web service is given below-
public class WsTest {

  public static void main(String[] args) {
    try {
      MyWsImpl stub = new MyWsImplService_Impl().getXXX();
      ((Stub)stub)._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, "http://myHost/myWs/myWs");
      // call the desired method
      stub.xxxXXX(. . .);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}