Webservices

Webservices and Soap:

Webservices communicate via soap messaging.  Soap is an xml-based notation that allows sending rpc requests  and responses across the network.  Classes can be mapped between different languages.  Some soap envelope examples appear below.  Along with RMI (and CORBA), SOAP provides a mechanism for distributed computing.

QNames: QNames were introduced by XML Namespaces in order to be used as URI references[1]. QName stands for "qualified name" and defines a valid identifier for elements and attributes. QNames are generally used to reference particular elements or attributes within XML documents. Since URI references can be long and may contain prohibited characters for element/attribute naming, QNames are used to create a mapping between the URI and a namespace prefix. The mapping enables the abbreviation of URIs, therefore it achieves a more convenient way to write XML documents.  So in the xml

<?xml version='1.0'?>
  <doc xmlns:x="http://example.com/ns/foo">
    <x:p/>
  </doc>

x:p is a QName.

Note: You may need to upgrade your java to 1.6 U4.  I could not get the clients to work even when I used endorsed directory for jaxb.

 

Building webservices and clients in netbeans http://www.netbeans.org/kb/55/websvc-jax-ws.html

Creating a Web Service

The goal of this exercise is to create a project appropriate to the deployment container that you decide to use. Once you have a project, you will create a web service in it.

Choosing a Container

You can either deploy your web service in a web container or in an EJB container. This depends on implementation choices. For example, if you plan to deploy to the Tomcat Web Server, which only has a web container, you should choose to create a web application, and not an EJB module.

  1. Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Web category or EJB Module from the Enterprise category.
  2. Name the project CalculatorWSApplication.
  3. Depending on the deployment server that you want to use, do the following:
    • For the Sun Java System Application Server, set the J2EE Version to Java EE 5.
    • For the Tomcat Web Server, unselect the Set Source Level to 1.4 checkbox.
  4. Click Finish.

Creating a Web Service from a Java Class

  1. Right-click the CalculatorWSApplication node and choose New > Web Service.
  2. Name the web service CalculatorWS, type org.me.calculator in Package, and click Finish.

The Projects window displays the new web service. For example, for web applications the Projects window now looks as follows:

Projects window displaying the web service

The IDE automatically creates the deployment descriptors required for the server, if any. For the Sun Java System Application Server, no deployment descriptor is needed. For web services deployed to the Tomcat Web Server, sun-jaxws.xml and a WSServlet item in web.xml are added.

Summary

In this exercise, you created a NetBeans project and set up the web service.

Coding the Web Service

The goal of this exercise is to do something meaningful with the files and code that the IDE has generated for you. You will add an operation that will add two numbers received from a client.

Adding Business Logic to the Web Service

  1. Expand the Web Services node and double-click the CalculatorWS node. The web service opens in the Source Editor. Note that an operation exists in the code already. It is commented out. Here, we create a new operation from scratch. Another way of creating the operation would be to remove the lines that comment out the code.
  2. Right-click within the body of the class, either above or below the code that is commented out, and choose Web Service > Add Operation.
  3. In the upper part of the Add Operation dialog box, type add in Name and choose int from the Return Type drop-down list.
  4. In the lower part of the Add Operation dialog box, click Add and create a parameter of type int named i. Click OK.
  5. Click Add again and create a parameter of type int called j.
  6. Click OK at the bottom of the Add Operation dialog box. Notice that a skeleton for the add method has been added to the Source Editor:
7.               @WebMethod
8.               public int add(@WebParam(name = "i") int i, @WebParam(name = "j") int j) {
9.                   // TODO implement operation
10.               return 0;
            }
  1. Change the add method to the following (changes are in bold):
12.           @WebMethod
13.           public int add(@WebParam(name = "i") int i, @WebParam(name = "j") int j) {
14.               int k = i + j;
15.               return k;
        }

Summary

In this exercise, you added code to the web service.

Deploying and Testing the Web Service

When you deploy a web service to a web container, the IDE lets you test the web service to see if it functions as you expect. The Tester application, provided by the Sun Java System Application Server, is integrated into the IDE for this purpose. For the Tomcat Web Server, there is a similar tool. However, while the Sun Java System Application Server's Tester page lets you enter values and test them, the Tomcat Web Server does not. In the latter case, you can only see that the web service is deployed, you cannot test the values. No facility for testing whether an EJB module is deployed successfully is currently available.

To test successful deployment to a web container:

  1. Right-click the project node, choose Properties, and click Run. Depending on the deployment server that you want to use, do the following:
    • For the Sun Java System Application Server, type /CalculatorWSService?Tester in the Relative URL field.
    • For the Tomcat Web Server, type /CalculatorWS?Tester in the Relative URL field.

Note: Since the result of a deployed EJB module is not displayed in a browser, you cannot take the step above if you are working with an EJB module.

  1. Right-click the project node and choose Run Project.

The IDE starts the application server, builds the application, and opens the tester page in your browser, if you deployed a web application to the Sun Java System Application Server. For the Tomcat Web Server and deployment of EJB modules, the situation is different:

    • If you deployed to the Tomcat Web Server, you will see the following instead, which indicates that you have successfully deployed your web service:

Web page displayed when web service was successfully deployed to Tomcat server

    • If you deployed an EJB module, successful deployment is indicated by the following messages in the Output window:
o                         Deployment of application CalculatorWSApplication  completed successfully
o                         Enable of CalculatorWSApplication in target server   completed successfully
o                         Enable of application in all targets  completed successfully
o                         All operations completed successfully
o                         run-deploy:
o                         run:
    BUILD SUCCESSFUL
    • If you deployed to the Sun Java System Application Server, type two numbers in the tester page, as shown below:

Web service tester page when service successfully deployed to Sun Java System Application Server

The sum of the two numbers is displayed:

Web page showing result of web service test

Summary

In this exercise, you deployed a web service and tested it.

Consuming the Web Service

Now that we have deployed our web service, we need to create a client to make use of the web service's add method. Here, we create three clients— a Java class in a Java SE application, a servlet, and a JSP page in a web application.

Client 1: Java Class in Java SE Application

  1. Choose File > New Project (Ctrl-Shift-N). Select Java Application from the General category. Name the project CalculatorWS_Client_Application.

Note: At the time of writing, issue Issue 10 was unresolved; therefore, you must create your web service client in a project folder that does not contain spaces in its path. For example, the path should not be "C:\Documents and Settings\...".

Click Finish.

  1. Right-click the CalculatorWS_Client_Application node and choose New > Web Service Client.
  2. In Project, click Browse. Browse to the web service that you want to consume. When you have selected the web service, click OK.
  3. Type org.me.calculator.client in Package, and click Finish.

The Projects window displays the new web service client:

New web service client in Java SE application displayed in the Projects window

  1. Double-click Main.java so that it opens in the Source Editor. Delete the TODO comment and right-click in that line. Choose Web Service Client Resources > Call Web Service Operation.
  2. Browse to the Add operation and click OK.
  3. Change the line that is underlined in red to the following:
    System.out.println("Sum: " + port.add(3,4));
  1. Right-click the project node and choose Run Project.

The Output window should now show the following:

    compile:
    run:
    Sum: 7
        BUILD SUCCESSFUL (total time: 1 second)

Client 2: Servlet in Web Application

  1. Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Web category. Name the project CalculatorWSServletClient.

Note: At the time of writing, issue Issue 10 was unresolved; therefore, you must create your web service client in a project folder that does not contain spaces in its path. For example, the path should not be "C:\Documents and Settings\...".

Click Finish.

  1. Right-click the CalculatorWSServletClient node and choose New > Web Service Client.
  2. In Project, click Browse. Browse to the web service that you want to consume. When you have selected the web service, click OK.
  3. Type org.me.calculator.client in Package, and click Finish.

The Projects window displays the new web service client:

New web service client in servlet displayed in the Projects window

  1. Right-click the project node and choose New > Servlet. Name the servlet ClientServlet and house it in a package called org.me.calculator.client. Click Finish. To make the servlet the entry point to your application, right-click the project node, choose Properties, click Run, and type /ClientServlet in Relative URL. Click OK.
  2. In the Source Editor, remove the line that comments out the body of the processRequest method. This is the line that starts the section that comments out the code:
    /* TODO output your page here

Next, delete the line that ends the section of commented out code:

    */

Add some empty lines after this line:

    out.println("<h1>Servlet ClientServlet at " + request.getContextPath () + "</h1>");

Now, right-click in one of the empty lines that you added. Choose Web Service Client Resources > Call Web Service Operation. The Select Operation to Invoke dialog box appears.

  1. Browse to the add operation and click OK.

The processRequest method now looks as follows (the added code is in bold below):

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet ClientServlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet ClientServlet at " + request.getContextPath () + "</h1>");
 
        try { // Call Web Service Operation
            org.me.calculator.client.CalculatorWSService service = new org.me.calculator.client.CalculatorWSService();
            org.me.calculator.client.CalculatorWS port = service.getCalculatorWSPort();
            // TODO initialize WS operation arguments here
            int arg0 = 0;
            int arg1 = 0;
            // TODO process result here
            int result = port.add(arg0, arg1);
            System.out.println("Result = "+result);
        } catch (Exception ex) {
            // TODO handle custom exceptions here
        }
 
        out.println("</body>");
        out.println("</html>");
        out.close();
            }

Change the value for arg0 and arg1 to other numbers, such as 3 and 4.

Change the System.out.println statement to out.println.

Add a line that prints out an exception, if an exception is thrown.

The try/catch block should now look as follows (new and changed lines are highlighted):

    try { // Call Web Service Operation
        org.me.calculator.client.CalculatorWSService service = new org.me.calculator.client.CalculatorWSService();
        org.me.calculator.client.CalculatorWSApplication port = service.getCalculatorWSApplicationPort();
        // TODO initialize WS operation arguments here
        int arg0 = 3;
        int arg1 = 4;
        // TODO process result here
        int result = port.add(arg0, arg1);
        out.println("<p>Result: " + result);
    } catch (Exception ex) {
        out.println("<p>Exception: " + ex);
            }
  1. Right-click the project node and choose Run Project.

 

  

 

Client 3: JSP Page in Web Application

  1. Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Web category. Name the project CalculatorWSJSPClient.

Note: At the time of writing, issue Issue 10 was unresolved; therefore, you must create your web service client in a project folder that does not contain spaces in its path. For example, the path should not be "C:\Documents and Settings\...".

Click Finish.

  1. Right-click the CalculatorWSJSPClient node and choose New > Web Service Client.
  2. In Project, click Browse. Browse to the web service that you want to consume. When you have selected the web service, click OK.
  3. Type org.me.calculator.client in Package, and click Finish.

The Projects window displays the new web service client.

  1. In the Web Pages folder, double-click index.jsp so that it opens in the Source Editor.
  2. In the Web Service References node, expand the node that represents the web service. The add operation, which you want to invoke from the client, is now exposed.
  3. Drag the add operation to the client's index.jsp page, and drop it below the H1 tags. The code for invoking the service's operation is now generated in the index.jsp page.

Change the value for arg0 and arg1 to other numbers, such as 3 and 4.

  1. Right-click the project node and choose Run Project.

The server starts, if it wasn't running already; the application is built and deployed, and the browser opens, displaying the calculation result:

JSP page showing result

 

 

 

 

 

 

 

http://java.sun.com/javaee/5/docs/tutorial/doc/bnazd.html

 

  • May need Glassfish
  • Download javaee-5-doc-tutorial-1.0-0.5.zip

 

Creating a Simple Web Service and Client with JAX-WS

This section shows how to build and deploy a simple web service and client. The source code for the service is in tut-install/javaeetutorial5/examples/jaxws/helloservice/ and the client is in tut-install/javaeetutorial5/examples/jaxws/simpleclient/.

Figure 16-1 illustrates how JAX-WS technology manages communication between a web service and client.

Figure 16-1 Communication between a JAX-WS Web Service and a Client

Diagram showing a client and web service communicating through a SOAP message.

The starting point for developing a JAX-WS web service is a Java class annotated with the javax.jws.WebService annotation. The @WebService annotation defines the class as a web service endpoint.

A service endpoint interface or service endpoint implementation (SEI) is a Java interface or class, respectively, that declares the methods that a client can invoke on the service. An interface is not required when building a JAX-WS endpoint. The web service implementation class implicitly defines an SEI.

You may specify an explicit interface by adding the endpointInterface element to the @WebService annotation in the implementation class. You must then provide an interface that defines the public methods made available in the endpoint implementation class.

You use the endpoint implementation class and the wsgen tool to generate the web service artifacts that connect a web service client to the JAX-WS runtime. For reference documentation on wsgen, see the Sun Java System Application Server 9.1 Reference Manual.

Together, the wsgen tool and the Application Server provide the Application Server’s implementation of JAX-WS.

These are the basic steps for creating the web service and client:

1.                 Code the implementation class.

2.                 Compile the implementation class.

3.                 Use wsgen to generate the artifacts required to deploy the service.

4.                 Package the files into a WAR file.

5.                 Deploy the WAR file. The web service artifacts (which are used to communicate with clients) are generated by the Application Server during deployment.

6.                 Code the client class.

7.                 Use wsimport to generate and compile the web service artifacts needed to connect to the service.

8.                 Compile the client class.

9.                 Run the client.

The sections that follow cover these steps in greater detail.

Requirements of a JAX-WS Endpoint

JAX-WS endpoints must follow these requirements:

*                  The implementing class must be annotated with either the javax.jws.WebService or javax.jws.WebServiceProvider annotation.

*                  The implementing class may explicitly reference an SEI through the endpointInterface element of the @WebService annotation, but is not required to do so. If no endpointInterface is specified in @WebService, an SEI is implicitly defined for the implementing class.

*                  The business methods of the implementing class must be public, and must not be declared static or final.

*                  Business methods that are exposed to web service clients must be annotated with javax.jws.WebMethod.

*                  Business methods that are exposed to web service clients must have JAXB-compatible parameters and return types. See Default Data Type Bindings.

*                  The implementing class must not be declared final and must not be abstract.

*                  The implementing class must have a default public constructor.

*                  The implementing class must not define the finalize method.

*                  The implementing class may use the javax.annotation.PostConstruct or javax.annotation.PreDestroy annotations on its methods for life cycle event callbacks.

The @PostConstruct method is called by the container before the implementing class begins responding to web service clients.

The @PreDestroy method is called by the container before the endpoint is removed from operation.

Coding the Service Endpoint Implementation Class

In this example, the implementation class, Hello, is annotated as a web service endpoint using the @WebService annotation. Hello declares a single method named sayHello, annotated with the @WebMethod annotation. @WebMethod exposes the annotated method to web service clients. sayHello returns a greeting to the client, using the name passed to sayHello to compose the greeting. The implementation class also must define a default, public, no-argument constructor.

package helloservice.endpoint;

 

import javax.jws.WebService;

 

@WebService

public class Hello {

    private String message = new String("Hello, ");

 

    public void Hello() {}

 

    @WebMethod

    public String sayHello(String name) {

        return message + name + ".";

    }

}

Building, Packaging, and Deploying the Service

You can build, package, and deploy the helloservice application using either NetBeans IDE or ant.

Building, Packaging, and Deploying the Service Using NetBeans IDE

Follow these instructions to build, package, and deploy the helloservice example to your Application Server instance using the NetBeans IDE IDE.

1.                 In NetBeans IDE, select File→Open Project.

2.                 In the Open Project dialog, navigate to tut-install/javaeetutorial5/examples/jaxws/.

3.                 Select the helloservice folder.

4.                 Select the Open as Main Project check box.

5.                 Click Open Project.

6.                 In the Projects tab, right-click the helloservice project and select Undeploy and Deploy.

This builds and packages to application into helloservice.war, located in tut-install/javaeetutorial5/examples/jaxws/helloservice/dist/, and deploys this WAR file to your Application Server instance.

Building, Packaging, and Deploying the Service Using Ant

To build and package helloservice using Ant, in a terminal window, go to the tut-install/javaeetutorial5/examples/jaxws/helloservice/ directory and type the following:

ant

This command calls the default target, which builds and packages the application into an WAR file, helloservice.war, located in the dist directory.

To deploy the helloservice example, follow these steps:

1.                 In a terminal window, go to tut-install/javaeetutorial5/examples/jaxws/helloservice/.

2.                 Make sure the Application Server is started.

3.                 Run ant deploy.

You can view the WSDL file of the deployed service by requesting the URL http://localhost:8080/helloservice/hello?WSDL in a web browser. Now you are ready to create a client that accesses this service.

Undeploying the Service

At this point in the tutorial, do not undeploy the service. When you are finished with this example, you can undeploy the service by typing this command:

ant undeploy

The all Task

As a convenience, the all task will build, package, and deploy the application. To do this, enter the following command:

ant all

Testing the Service without a Client

The Application Server Admin Console allows you to test the methods of a web service endpoint. To test the sayHello method of HelloService, do the following:

1.                 Open the Admin Console by typing the following URL in a web browser:

http://localhost:4848/

2.                 Enter the admin user name and password to log in to the Admin Console.

3.                 Click Web Services in the left pane of the Admin Console.

4.                 Click Hello.

5.                 Click Test.

6.                 Under Methods, enter a name as the parameter to the sayHello method.

7.                 Click the sayHello button.

This will take you to the sayHello Method invocation page.

8.                 Under Method returned, you’ll see the response from the endpoint.

A Simple JAX-WS Client

HelloClient is a stand-alone Java program that accesses the sayHello method of HelloService. It makes this call through a port, a local object that acts as a proxy for the remote service. The port is created at development time by the wsimport tool, which generates JAX-WS portable artifacts based on a WSDL file.

Coding the Client

When invoking the remote methods on the port, the client performs these steps:

1.                 Uses the javax.xml.ws.WebServiceRef annotation to declare a reference to a web service. @WebServiceRef uses the wsdlLocation element to specify the URI of the deployed service’s WSDL file.

2.                      @WebServiceRef(wsdlLocation="http://localhost:8080/helloservice/hello?wsdl")

static HelloService service;

3.                 Retrieves a proxy to the service, also known as a port, by invoking getHelloPort on the service.

Hello port = service.getHelloPort();

The port implements the SEI defined by the service.

4.                 Invokes the port’s sayHello method, passing to the service a name.

String response = port.sayHello(name);

Here is the full source of HelloClient, which is located in the tut-install/javaeetutorial5/examples/jaxws/simpleclient/src/java/ directory.

package simpleclient;

 

import javax.xml.ws.WebServiceRef;

import helloservice.endpoint.HelloService;

import helloservice.endpoint.Hello;

 

public class HelloClient {

    @WebServiceRef(wsdlLocation="http://localhost:8080/

            helloservice/hello?wsdl")

    static HelloService service;

 

    public static void main(String[] args) {

        try {

            HelloClient client = new HelloClient();

            client.doTest(args);

        } catch(Exception e) {

            e.printStackTrace();

        }

    }

 

    public void doTest(String[] args) {

        try {

            System.out.println("Retrieving the port from

                     the following service: " + service);

            Hello port = service.getHelloPort();

            System.out.println("Invoking the sayHello operation

                     on the port.");

 

            String name;

            if (args.length > 0) {

                name = args[0];

            } else {

                name = "No Name";

            }

 

            String response = port.sayHello(name);

            System.out.println(response);

        } catch(Exception e) {

            e.printStackTrace();

        }

    }

}

Building and Running the Client

You can build and run the simpleclient application using either NetBeans IDE or ant. To build the client, you must first have deployed helloservice, as described in Building, Packaging, and Deploying the Service.

 

Note – I could only get these clients to build in Netbeans, not from ant.

Building and Running the Client in NetBeans IDE

Do the following to build and run simpleclient:

1.                 In NetBeans IDE, select File→Open Project.

2.                 In the Open Project dialog, navigate to tut-install/javaeetutorial5/examples/jaxws/.

3.                 Select the simpleclient folder.

4.                 Select the Open as Main Project check box.

5.                 Click Open Project.

6.                 In the Projects tab, right-click the simpleclient project and select Run.

You will see the output of the application client in the Output pane.

Building and Running the Client Using Ant

In a terminal navigate to tut-install/examples/jaxws/simpleclient/ and type the following command:

ant

This command calls the default target, which builds and packages the application into a JAR file, simpleclient.jar, located in the dist directory.

The run the client, type the following command:

ant run

 

Some documentation at http://java.sun.com/javaee/5/docs/tutorial/doc/bnazd.html

Common Build Instructions for Sample Applications with JavaEETutorial code.

The sample applications use the Java BluePrints build system that employs a set of Ant build scripts (XML files) in the samples/bp-project directory.

Procedure

In the instructions below, <javaee.home> refers to the path where you installed the Java EE 5 SDK (for Windows, the default path is c:/Sun/AppServer). Follow these steps to build a sample application:

  1. Add <javaee.home>/lib/ant/bin directory to your PATH environment variable. 
  2. Edit the file <javaee.home>/samples/bp-project/build.properties and set the value of javaee.server.passwordfile (see below). Note: the Java EE 5 SDK installer automatically sets default values for some of these properties. 

Property Name

Description

Examples

javaee.home

The installation directory of the Java EE 5 SDK

c:/Sun/AppServer

javaee.server.name

Host name of the server where the Java EE 5 SDK is installed

localhost

javaee.server.port

The port number for the server you chose while installing Java EE 5 SDK

8080

javaee.server.username

The administrator username specified for the serve while installing Java EE 5 SDK

admin

javaee.server.passwordfile

The path to a file containing the admin password for the Java EE 5 SDK. The password file needs to be in the following format:

AS_ADMIN_PASSWORD=<javaeesdk-admin-password>

Where you will replace <javaeesdk-admin-password> with the admin password for the Java EE 5 SDK.

/path/to/passwordfile

javaee.adminserver.port

The port number for admin server you chose while installing the Java EE 5 SDK

4848

proxy.host

The host name of your HTTP proxy server, if the server running Java EE SDK is behind a firewall. Leave blank otherwise

myproxy.mydomain

proxy.port

The port number of your HTTP proxy server, if the server running Java EE SDK is behind a firewall. Leave blank otherwise

9090

  1.  
  2. Start the application server and the JavaDB database. To do so, open a command prompt and change directory to <javaee.home>/bin and issue the following commands:
    asadmin start-domain
    asadmin start-database
  3. Follow the process specific to a sample application to build and run it.
  4. Common build targets are
    • all: compiles, packages the archive, deploys the application and run the sample
    • compile: compiles the sample application
    • package-module: packages the archive
    • default: compiles, packages the archive
    • run: runs the sample application
    • clean: undeploys the application, removes the generated directories like build and dist
  5. See Using Java DB with Sample applications for information on configuring the built-in Java DB database and corresponding JDBC resources.
  6. See Monitoring Web Services for information on how to monitor web services applications.
  7. All the samples are NetBeans ready and can be opened as netbeans projects in NetBeans IDE.
    • Download and install NetBeans IDE
    • Configure the browser which the NetBeans IDE will use by selecting Tools->Options->General->WebBrowser
    • Configure and start the application server using runtime tab of netbeans
    • Open any sample as a netbeans project and right click to execute the ant targets, say run
    • Detailed instructions are given in the sample specific documentation including any pre-requisites

 

These examples don’t have a lot of documentation.

An EJB helloservice:

package com.sun.tutorial.javaee.ejb.helloservice;

 

import javax.ejb.Stateless;

import javax.jws.WebMethod;

import javax.jws.WebService;

 

 

/**

 * HelloServiceBean is a web service endpoint implemented as a stateless

 * session bean.

 * Created Jan 9, 2006 3:07:38 PM

 * @author ian

 */

@Stateless

@WebService

public class HelloServiceBean {

    private String message = "Hello, ";

 

    public void HelloServiceBean() {

    }

 

    @WebMethod

    public String sayHello(String name) {

        return message + name + ".";

    }

}

 

 

The client for this fails to build using ant, so I tried using Netbeans, (as in webservices htm using netbeans…new java app project…new webservice client) which also didn’t work using the browse setting for webservice but did work if I entered the url:

http://localhost:8080/HelloServiceBeanService/HelloServiceBean?WSDL

 

in the main class, rt-click, add code, call webservice method.  This generates an error because of some problem with the helloservice config file, but does generate code:

 

try { // Call Web Service Operation

            com.sun.tutorial.javaee.ejb.helloservice.HelloServiceBeanService service = new com.sun.tutorial.javaee.ejb.helloservice.HelloServiceBeanService();

            com.sun.tutorial.javaee.ejb.helloservice.HelloServiceBean port = service.getHelloServiceBeanPort();

            // TODO initialize WS operation arguments here

            java.lang.String arg0 = "put something here";//my message

            // TODO process result here

            java.lang.String result = port.sayHello(arg0);

            System.out.println("Result = "+result);

        } catch (Exception ex) {

            // TODO handle custom exceptions here

        }

 

And despite problems with the wsdl file, it does run:

run:

Result = Hello, put something here.

BUILD SUCCESSFUL (total time: 5 seconds)

 

 

 

This example uses Netbeans and works… up to running tests:

http://developers.sun.com/webtier/reference/techart/websvcs_nb.html#1

 

Service works… very easy using Netbeans. http://java.sun.com/javaee/5/docs/tutorial/doc/bnayn.html but client doesn’t run.

 

 

 

From netbeans http://www.netbeans.org/kb/60/websvc/jax-ws.html#Exercise_1

 

 

JAXB Architecture

This section describes the components and interactions in the JAXB processing model.

Architectural Overview

Figure 17-1 shows the components that make up a JAXB implementation.

Figure 17-1 JAXB Architectural Overview

Diagram of JAXB architecture, showing Schema on left, Schema Generator and Schema Compiler in the middle, and Application Code on the right.

A JAXB implementation consists of the following architectural components:

*                  Schema compiler: Binds a source schema to a set of schema-derived program elements. The binding is described by an XML-based binding language.

*                  Schema generator: Maps a set of existing program elements to a derived schema. The mapping is described by program annotations.

*                  Binding runtime framework: Provides unmarshalling (reading) and marshalling (writing) operations for accessing, manipulating, and validating XML content using either schema-derived or existing program elements.

The JAXB Binding Process

Figure 17-2 shows what occurs during the JAXB binding process.

Figure 17-2 Steps in the JAXB Binding Process

Diagram of the JAXB Binding Process: Schema, JAXB mapped classes, Document, and Objects

The general steps in the JAXB data binding process are:

1.                 Generate classes: An XML schema is used as input to the JAXB binding compiler to generate JAXB classes based on that schema.

2.                 Compile classes: All of the generated classes, source files, and application code must be compiled.

3.                 Unmarshal: XML documents written according to the constraints in the source schema are unmarshalled by the JAXB binding framework. Note that JAXB also supports unmarshalling XML data from sources other than files/documents, such as DOM nodes, string buffers, SAX Sources, and so forth.

4.                 Generate content tree: The unmarshalling process generates a content tree of data objects instantiated from the generated JAXB classes; this content tree represents the structure and content of the source XML documents.

5.                 Validate (optional): The unmarshalling process optionally involves validation of the source XML documents before generating the content tree. Note that if you modify the content tree in Step 6, below, you can also use the JAXB Validate operation to validate the changes before marshalling the content back to an XML document.

6.                 Process content: The client application can modify the XML data represented by the Java content tree by means of interfaces generated by the binding compiler.

7.                 Marshal: The processed content tree is marshalled out to one or more XML output documents. The content may be validated before marshalling.

More about Unmarshalling

Unmarshalling provides a client application the ability to convert XML data into JAXB-derived Java objects.

More about Marshalling

Marshalling provides a client application the ability to convert a JAXB-derived Java object tree back into XML data.

By default, the Marshaller uses UTF-8 encoding when generating XML data.

Client applications are not required to validate the Java content tree before marshalling. There is also no requirement that the Java content tree be valid with respect to its original schema to marshal it back into XML data.

More about Validation

Validation is the process of verifying that an XML document meets all the constraints expressed in the schema. JAXB 1.0 provided validation at unmarshal time and also enabled on-demand validation on a JAXB content tree. JAXB 2.0 only allows validation at unmarshal and marshal time. A web service processing model is to be lax in reading in data and strict on writing it out. To meet that model, validation was added to marshal time so one could confirm that they did not invalidate the XML document when modifying the document in JAXB form.

Binding XML Schemas

This section describes the default XML-to-Java bindings used by JAXB. All of these bindings can be overridden on global or case-by-case levels by means of a custom binding declaration. See the JAXB Specification for complete information about the default JAXB bindings.

Simple Type Definitions

A schema component using a simple type definition typically binds to a Java property. Since there are different kinds of such schema components, the following Java property attributes (common to the schema components) include:

*                  Base type

*                  Collection type, if any

*                  Predicate

The rest of the Java property attributes are specified in the schema component using the simple type definition.

Default Data Type Bindings

The following sections explain the default schema-to-Java, JAXBElement, and Java-to-schema data type bindings.

Schema-to-Java Mapping

The Java language provides a richer set of data type than XML schema. Table 17-1 lists the mapping of XML data types to Java data types in JAXB.

Table 17-1 JAXB Mapping of XML Schema Built-in Data Types

XML Schema Type

Java Data Type

xsd:string

java.lang.String

xsd:integer

java.math.BigInteger

xsd:int

int

xsd.long

long

xsd:short

short

xsd:decimal

java.math.BigDecimal

xsd:float

float

xsd:double

double

xsd:boolean

boolean

xsd:byte

byte

xsd:QName

javax.xml.namespace.QName

xsd:dateTime

javax.xml.datatype.XMLGregorianCalendar

xsd:base64Binary

byte[]

xsd:hexBinary

byte[]

xsd:unsignedInt

long

xsd:unsignedShort

int

xsd:unsignedByte

short

xsd:time

javax.xml.datatype.XMLGregorianCalendar

xsd:date

javax.xml.datatype.XMLGregorianCalendar

xsd:g

javax.xml.datatype.XMLGregorianCalendar

xsd:anySimpleType

java.lang.Object

xsd:anySimpleType

java.lang.String

xsd:duration

javax.xml.datatype.Duration

xsd:NOTATION

javax.xml.namespace.QName

JAXBElement Object

When XML element information can not be inferred by the derived Java representation of the XML content, a JAXBElement object is provided. This object has methods for getting and setting the object name and object value.

Java-to-Schema Mapping

Table 17-2 shows the default mapping of Java classes to XML data types.

Table 17-2 JAXB Mapping of XML Data Types to Java Classes

Java Class

XML Data Type

java.lang.String

xs:string

java.math.BigInteger

xs:integer

java.math.BigDecimal

xs:decimal

java.util.Calendar

xs:dateTime

java.util.Date

xs:dateTime

javax.xml.namespace.QName

xs:QName

java.net.URI

xs:string

javax.xml.datatype.XMLGregorianCalendar

xs:anySimpleType

javax.xml.datatype.Duration

xs:duration

java.lang.Object

xs:anyType

java.awt.Image

xs:base64Binary

javax.activation.DataHandler

xs:base64Binary

javax.xml.transform.Source

xs:base64Binary

java.util.UUID

xs:string

Customizing Generated Classes and Java Program Elements

The following sections explain how to customize generated JAXB classes and Java program elements.

Schema-to-Java

Custom JAXB binding declarations allow you to customize your generated JAXB classes beyond the XML-specific constraints in an XML schema to include Java-specific refinements, such as class and package name mappings.

JAXB provides two ways to customize an XML schema:

*                  As inline annotations in a source XML schema

*                  As declarations in an external binding customization file that is passed to the JAXB binding compiler

Code examples that show how to customize JAXB bindings are provided later in this chapter.

Java-to-Schema

The JAXB annotations defined in the javax.xml.bind.annotations package can be used to customize Java program elements to XML schema mapping. Table 17-3 summarizes the JAXB annotations that can be used with a Java package.

Table 17-3 JAXB Annotations Associated with a Java Package

Annotation

Description and Default Setting

@XmlSchema

Maps a package to an XML target namespace. Default Settings:

@XmlSchema (

   xmlns = {},

   namespace = "",

   elementFormDefault = XmlNsForm.UNSET,

   attributeFormDefault = XmlNsForm.UNSET

)

@XmlAccessorType

Controls default serialization of fields and properties. Default Settings:

@XmlAccessorType (

   value = AccessType.PUBLIC_MEMBER

)

@XmlAccessorOrder

Controls the default ordering of properties and fields mapped to XML elements. Default Settings:

@XmlAccessorOrder (

   value = AccessorOrder.UNDEFINED

)

@XmlSchemaType

Allows a customized mapping to an XML Schema built-in type. Default Settings:

@XmlSchemaType (

   namespace = "http://www.w3.org/2001/XMLSchema",

   type = DEFAULT.class

)

@XmlSchemaTypes

A container annotation for defining multiple @XmlSchemaType annotations. Default Settings:

None

Table 17-4 summarizes JAXB annotations that can be used with a Java class.

Table 17-4 JAXB Annotations Associated with a Java Class

Annotation

Description and Default Setting

@XmlType

Maps a Java class to a schema type. Default Settings:

@XmlType (

   name = "##default",

   propOrder = {""},

   namespace = "##default",

   factoryClass = DEFAULT.class,

   factoryMethod = ""

)

@XmlRootElement

Associates a global element with the schema type to which the class is mapped. Default Settings:

@XmlRootElement (

   name = "##default",

   namespace = "##default"

)

Table 17-5 summarizes JAXB annotations that can be used with a Java enum type.

Table 17-5 JAXB Annotations Associated with a Java enum Type

Annotation

Description and Default Setting

@XmlEnum

Maps a Java type to an XML simple type. Default Settings:

@XmlEnum ( value = String.class )

@XmlEnumValue

Maps a Java type to an XML simple type. Default Settings:

None

@XmlType

Maps a Java class to a schema type. Default Settings:

@XmlType (

   name = "##default",

   propOrder = {""},

   namespace = "##default",

   factoryClass = DEFAULT.class,

   factoryMethod = ""

)

@XmlRootElement

Associates a global element with the schema type to which the class is mapped. Default Settings:

@XmlRootElement (

   name = "##default",

   namespace = "##default"

)

Table 17-6 summarizes JAXB annotations that can be used with Java properties and fields.

Table 17-6 JAXB Annotations Associated with Java Properties and Fields

Annotation

Description and Default Setting

@XmlElement

Maps a JavaBeans property/field to an XML element derived from a property/field name. Default Settings:

@XmlElement (

   name = "##default",

   nillable = false,

   namespace = "##default",

   type = DEFAULT.class,

   defaultValue = "\u0000"

)

@XmlElements

A container annotation for defining multiple @XmlElement annotations. Default Settings:

None

@XmlElementRef

Maps a JavaBeans property/field to an XML element derived from a property/field’s type. Default Settings:

@XmlElementRef (

   name = "##default",

   namespace = "##default",

   type = DEFAULT.class

)

@XmlElementRefs

A container annotation for defining multiple @XmlElementRef annotations. Default Settings:

None

@XmlElementWrapper

Generates a wrapper element around an XML representation. Typically a wrapper XML element around collections. Default Settings:

@XmlElementWrapper (

   name = "##default",

   namespace = "##default",

   nillable = false

)

@XmlAnyElement

Maps a JavaBeans property to an XML infoset representation and/or JAXB element. Default Settings:

@XmlAnyElement (

   lax = false,

   value = W3CDomHandler.class

)

@XmlAttribute

Maps a JavaBeans property to an XML attribute. Default Settings:

@XmlAttribute (

   name = ##default,

   required = false,

   namespace = "##default"

)

@XmlAnyAttribute

Maps a JavaBeans property to a map of wildcard attributes. Default Settings:

None

@XmlTransient

Prevents the mapping of a JavaBeans property to an XML representation. Default Settings:

None

@XmlValue

Defines mapping of a class to an XML Schema complex type with a simpleContent or an XML Schema simple type. Default Settings:

None

@XmlID

Maps a JavaBeans property to an XML ID. Default Settings:

None

@XmlIDREF

Maps a JavaBeans property to an XML IDREF. Default Settings:

None

@XmlList

Maps a property to a list simple type. Default Settings:

None

@XmlMixed

Marks a JavaBeans multi-valued property to support mixed content. Default Settings:

None

@XmlMimeType

Associates the MIME type that controls the XML representation of the property. Default Settings:

None

@XmlAttachmentRef

Marks a field/property that its XML form is a URI reference to mime content. Default Settings:

None

@XmlInlineBinaryData

Disables consideration of XOP encoding for data types that are bound to base64-encoded binary data in XML. Default Settings:

None

Table 17-7 summarizes the JAXB annotation that can be used with object factories.

Table 17-7 JAXB Annotations Associated with Object Factories

Annotation

Description and Default Setting

@XmlElementDecl

Maps a factory method to an XML element. Default Settings:

@XmlElementDecl (

   scope = GLOBAL.class,

   namespace = "##default",

   substitutionHeadNamespace = "##default",

   substitutionHeadName = ""

)

Table 17-8 summarizes JAXB annotations that can be used with adapters.

Table 17-8 JAXB Annotations Associated with Adapters

Annotation

Description and Default Setting

@XmlJavaTypeAdapter

Use the adapter that implements the @XmlAdapter annotation for custom marshalling. Default Settings:

@XmlJavaTypeAdapter ( type = DEFAULT.class )

@XmlJavaTypeAdapters

A container annotation for defining multiple @XmlJavaTypeAdapter annotations at the package level. Default Settings:

None

 

 

 

http://www.eclipse.org/webtools/community/tutorials/BottomUpAxis2WebService/bu_tutorial.html

 

Building axis webservice from scratch  … see http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html

 

You can see my FtoC and CtoF services posted.

 

Building webservices with maven http://blogs.sun.com/enterprisetechtips/entry/using_jax_ws_with_maven

 

Creating the Project and Subprojects

In this sample, you create a main project, that is, a parent project, named jaxws-maven-sample. The parent project has two subprojects: HelloService, for the web service, and HelloClient, for the web service client. Here is what the project structure looks like:

   jaxws-maven-sample (POM Project)
     helloservice (WAR project)
     helloclient (JAR Project)

To reduce redundancy, the parent project POM holds configuration parameters that are in common between HelloService and HelloClient. To create the project and subprojects, do the following:

  1. Create the parent (POM project), jaxws-maven-sample.  
    • Select New Project from the File menu.
    • Choose the Maven category then the Maven project.
    • Click the Next button.
    • Select the Maven Quickstart Project archetype (the default).
    • On the next screen specify the following project settings, also known as Maven project coordinates:  

          - ProjectName:
      jaxws-maven-sample
          - ProjectLocation: Specify a directory to contain the project, for example,
      Users/ramapulavarthi.
          - Version: 1.0-SNAPSHOT
          - GroupId:
      com.example.maven.jaxws
          - Package:
      com.example.maven.jaxws  
    • Click the Finish button to create the project.


You should now see the project in NetBeans Projects window.
 

  1. Change the project properties from jar to pom.  
    • Right-click the jaxws-maven-sample in the Projects window.
    • Select the Properties option from the menu.
    • In the General category, change the Packaging value from jar to pom.
    • Click the OK button. Notice that the entry in the Projects window now shows jaxws-maven-sample (pom).

 

  1. Remove unwanted dependencies and files created by default. Because this is a POM project, it will have submodules instead of sources/tests. So you need to remove sources from the project. Also, there are no unit tests in this project so you need to remove any JUnit dependencies.  
    • Click the Files tab (next to Projects tab).
    • In the Files window, right-click the src directory below jaxws-maven-sample and choose Delete.
    • In the Projects window, expand the TestLibraries node of jaxws-maven-sample, right-click on the junit-3.8.1.jar, and select Remove Dependency.

 

  1. Change the source to Java 5. You need Java 5 to create web services. However, the default is Java 1.4.  
    • Right-click the jaxws-maven-sample in the Projects window.
    • Select the Properties option from the menu.
    • In the Sources category, change the Source/Binary Format value from 1.4 to 1.5.
    • Click the OK button.

 

If you examine the
pom.xml file in the Project Files below jaxws-maven-sample, you'll notice the configuration source and target values are changed to 1.5.
 

  1. Create the subproject (WAR project), helloservice.  

    Repeat the steps in step 1, "Create the parent (POM project),
    jaxws-maven-sample" except instead of selecting the Maven Quickstart Project archetype, select Maven WebApp archetype. Also specify the settings as follows:  

           - ProjectName:
    helloservice
           - ProjectLocation: Specify the directory that contains the
    jaxws-maven-sample project, for example, /Users/ramapulavarthi/jaxws-maven-sample.
           - Version: 1.0-SNAPSHOT
           - GroupId:
    com.example.maven.jaxws
           - Package:
    com.example.maven.jaxws.helloservice  
    • Click the Finish button to create the project.
      You should now see
      helloservice Maven Webapp (war) in the NetBeans Projects window. Notice that the pom.xml file for helloservice has a reference to the parent project, jaxws-maven-sample, and the pom.xml file for jaxws-maven-sample now specifies a module for helloservice.

 

  1. Remove unwanted dependencies and files for helloservice.  
    • Click the Files tab (next to Projects tab).
    • In the Files window, expand the src directory below helloservice Maven webapp, right-click the test directory and choose Delete.
    • In the Projects window, expand the TestLibraries node of helloservice Maven webapp, right-click on junit-3.8.1.jar, and select Remove Dependency.

 

  1. Create the subproject (JAR project), helloclient.  

    Repeat the steps in step 1, "Create the parent (POM project),
    jaxws-maven-sample" except specify the settings as follows:  

           - ProjectName:
    helloclient
           - ProjectLocation: Specify the directory that contains the
    jaxws-maven-sample project, for example, /Users/ramapulavarthi/jaxws-maven-sample.
           - Version: 1.0-SNAPSHOT
           - GroupId:
    com.example.maven.jaxws
           - Package:
    com.example.maven.jaxws.helloclient  
    • Click the Finish button to create the project.
      You should now see
      helloclient (jar) in the NetBeans Projects window. Notice that the pom.xml file for helloclient has a reference to the parent project, jaxws-maven-sample, and the pom.xml file for jaxws-maven-sample now specifies a module for helloclient.

 

  1. Remove unwanted dependencies and files for helloclient.  
    • Click the Files tab (next to Projects tab).
    • In the Files window, expand the src directory below helloclient, right-click the test directory and choose Delete.
    • In the Projects window, expand the TestLibraries node of helloclient, right-click on junit-3.8.1.jar, and select Remove Dependency.
    • Remove com.example.maven.jaxws.App.java from the SourcePackages directory

Add JAX-WS JARs and Repositories

Now that you've created the project and its subprojects, you need to couple them with needed JAX-WS jar files and repositories.

  1. Add a dependency on jaxws-rt.jar.  
    • Expand jaxws-maven-sample in the Projects window and right-click on Libraries.
    • Select "Add Library..." and then enter the following information in the Add Library popup window:  

      - GroupId:
      com.sun.xml.ws
      - ArtifactId: jaxws-rt
      - Version: 2.1.3
      - Scope: compile (The scope determines if the artifact is required for compile time or runtime).
    • Click the OK button.

Notice that the pom.xml file for jaxws-maven-sample now has a compile-time dependency on jaxws-rt.jar and specifies a scope of compile -- the jaxws-rt.jar file is required to be available for the service and client at runtime.

GlassFish includes JAX-WS, so if you use GlassFish as the deployment container, you can set the Scope value to "provided". In this case, Maven creates a "skinny" WAR file, that is, it doesn't bundle the jax-ws jar files into the WAR.

  1. Add repository for the jax-ws jars. Maven uses this information to get the jaxws-maven-plugin and its dependent artifacts.  
    • Expand the Project Files node for jaxws-maven-sample and open the pom.xml file.
    • Add the following repository information for downloading JAX-WS JARs:  

         <repositories>
           <repository>
             <id>maven-repository.dev.java.net</id>
             <name>Java.net Repository for Maven 1</name>
             <url>http://download.java.net/maven/1/</url>
             <layout>legacy</layout>
           </repository>
           <repository>
             <id>maven2-repository.dev.java.net</id>
             <name>Java.net Repository for Maven 2</name>
             <url>http://download.java.net/maven/2/</url>
           </repository>
         </repositories>  


This adds information for both the Maven 1 and Maven 2 repositories. (Some of the JAX-WS dependencies exist in both repositories.)
 

  1. Add plugin repository information for the jaxws-maven-plugin to the pom.xml file, as follows:  

       <pluginRepositories>
         <pluginRepository>
           <id>maven2-repository.dev.java.net</id>
           <url>http://download.java.net/maven/2/</url>
         </pluginRepository>
       </pluginRepositories>  

    Because all the configuration specifications are in the
    pom.xml file of the parent project, the configuration is shared by the subprojects helloservice and helloclient.

Build the Web Service

  1. Add logic to helloservice.  
    • Right-click the SourcePackages node in the helloservice project.
    • Select New, then Java Class.
    • In the New Java Class window, specify:  

          - Class Name: Hello
          - Package:
      com.example.maven.jaxws.helloservice  
    • Click the Finish button.
    • Update the source code for the Hello class to annotate it as a WebService and include a method sayHello. The updated source code should look as follows:  

         package com.example.maven.jaxws.helloservice;
         import javax.jws.WebService;
         @WebService
         public class Hello {
           public String sayHello(String param) {
           ;  return "Hello " + param;
           }
         }  

 

  1. Run the jaxws-maven-plugin:wsgen on the SEI class.  
    • Open the pom.xml file of helloservice.
    • Add the following code under the build section in the pom.xml file:
       

            <plugins>      
              <plugin>
              <groupId>org.codehaus.mojo&lg;/groupId>
              <artifactId>jaxws-maven-plugin&lg;/artifactId>
                <executions>
                  <execution>
                    <goals>
                      <goal>wsgen</goal>
                    </goals>
                    <configuration>
                    <sei>com.example.maven.jaxws.helloservice.Hello
                    </sei>
                    <!--for demo purpose only, the webapp does not-->
                    <!--need the generated wsdl files-->
                    <genWsdl>true</genWsdl>           
                    <keep>true&lg;/keep>
                    </configuration>
                  </execution>
                </executions>
              </plugin>
            </plugins>
       


As mentioned earlier, the
jaxws-maven-plugin:wsgen goal is automatically invoked during the process-classes life cycle phase. The <sei> element value com.example.maven.jaxws.helloservice.Hello will be passed to the goal as a parameter.

Deploy the Web Service

  1. Specify deployment information.  
    • If you use GlassFish or any other Java EE 5 container to deploy the web service, change the default web.xml file to use version "2.5". To do that:  

          - Expand the Web Pages node in the
      helloservice project.
          - Expand the WEB-INF node and select the
      web.xml file.
          - Click the XML view button above the source editor window to view the XML contents of the file.
          - Replace the contents of the
      web.xml file with the following:  

         <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">
           <welcome–file–list>
           <welcome–file>index.jsp</welcome–file>
           </welcome–file–list>
         </web–app>  

      Make sure to remove the <!DOCTYPE> element at the beginning of the file.
       

          - Save the file.
       

  2. Deploy the artifacts to GlassFish.  
    • Right-click the helloservice project and select Properties.
    • In the Run category, specify the following:  

          - Server: GlassFish v2
          - Context Path:
      /helloservice
          - Click the OK button.
       

You can also optionally check the Display Browser on Run checkbox and enter HelloService?wsdl in the Relative URL field. If you make these optional specifications, NetBeans will open a browser showing the helloservice WSDL after the helloservice service is deployed.
In response, the
pom.xml file for helloservice is updated to deploy the artifacts to GlassFish.

Run the Service

*       Right-Click on helloservice and select Run.  

NetBeans runs Maven to build the web application and automatically deploys the WAR file to GlassFish. You can see the process in the NetBeans Output window. You can access the WSDL for the service to check if the service is successfully deployed. If you checked the Display Browser on Run checkbox as described in previous step, NetBeans opens a browser showing the WSDL of the deployed web service. If you did not check the Display Browser on Run checkbox, you can display the WSDL for the web service by opening
http://localhost:8080/helloservice/HelloService?wsdl in your browser.  

*        

Create a Client to Invoke the Web Service

Run jaxws-maven-plugin:wsimport on the helloservice WSDL:  

    • Open the pom.xml file of helloclient.
    • Add the following code to the pom.xml file:  

         <build>
           <plugins>
             <plugin>
               <groupId>org.codehaus.mojo</groupId>
                 <artifactId>jaxws-maven-plugin</artifactId>
                 <executions>
                   <execution>
                     <goals>
                       <goal>wsimport</goal>
                     </goals>
                     <configuration>
                       <wsdlUrls>
                         <wsdlUrl>
               http://localhost:8080/helloservice/HelloService?wsdl
                         </wsdlUrl>
                       </wsdlUrls>
                   <packageName>com.example.maven.jaxws.helloclient
                   </packageName>
                     </configuration>
                   </execution>
                 </executions>
             </plugin>
           </plugins>
         <bulid>

 

The
jaxws-maven-plugin:wsimport goal is run during the life cycle phase generate-sources. As you can see in the above configuration, wsimport is run on the WSDL located at http://localhost:8080/helloservice/HelloService?wsdl to generate Java classes in the com.example.maven.jaxws.helloclient package.  

  1. Build the client.  
    • Right-click on the helloclient project and select build. Maven builds the project, runs wsimport, and generates all the Web Service artifacts that you see in the target folder. (To see the generated files, open then Files window and expand helloclient/target).
    • Expand the Source packages node in the helloclient project and right-click on com.example.maven.jaxws.helloclient
    • Select New, then Java class.
    • Specify the class name as HelloClient.
    • Click the Finish button.
    • Update the HelloClient class with the following source code:  

         package com.example.maven.jaxws.helloclient;
         public class HelloClient {
           public static void main(String[] args) {
           HelloService service = new HelloService();
           Hello port= service.getHelloPort();
           System.out.println(port.sayHello("Duke"));
           }
         }  
  2. Associate the NetBeans IDE action "Run" to build the jar and run HelloClient.  
    • Right-click on helloclient and select Properties.
    • Under Run category, enter com.example.maven.jaxws.helloclient.HelloClient as the Main class.
    • Click the OK button.

Run the Client

*       Right click on helloclient and choose Run.  

Maven runs
wsimport on the WSDL file, creates Java classes, compiles HelloClient, and runs it. In the NetBeans Output window you should see the following result of the web service invocation:  

   Hello Duke
 

(My note: This all worked)

 

Summary

Using Maven you can easily create JAX-WS-based web services. Although this tip showed you how to do that using NetBeans, you can also can create JAX-WS-based web services using Maven manually, that is, without using NetBeans. To do so, use the mvn CLI and edit the pom files as needed. However, NetBeans makes it easier to use Maven for your projects and saves you from having to worry about configuration syntax.

For more information about using Maven to create JAX-WS-based web services, see the Metro User's Guide.

 

Sidebar on endorsed: I found that putting the endorsed dir in the java_home/lib/ was not working and I had to put it into java_home/jre/lib.  (Your jaxb-api-2.1.jar must be put here to override system class loader if that loads v.2.0) Even so, I wound up installing a new version of java: 1.6U17  --- and then the ws clients worked.

 

 

http://wiki.eclipse.org/COSMOS_Axis2_Framework#Downloading_and_Installing_a_Build

 

Installing AXIS… instructions… http://ws.apache.org/axis/java/install.html#Step2SettingUpTheLibraries

 

Get war file from: http://ws.apache.org/axis2/download/1_3/download.cgi

(2.1.5.war did not work for me).

Although you are supposed to be able to install the webapp from your axis2 idstribution in tomcat, I did not succeed.  Instead get the war file.  Drop the axis war into tomcat.  You should see this:

And the links should work. I tried building a sample from the distribution with a pom but got an index out of bounds exception deploying it.

 

 

As in the example above, installing webservices into axis, just means putting a compiled class into the axis/lib or webapps/classes directory.  .

 

http://www.eclipse.org/webtools/community/tutorials/BottomUpAxis2WebService/bu_tutorial.html  this link builds a FtoC converter in eclipse using axis.

 

 

 

Prebuilt axis/spring webservices webappWebservices with Axis & Spring….

 

 

Installing axis

The following steps will successfully take you through the process.

1.   Get an SVN checkout of Axis2 (https://svn.apache.org/repos/asf/webservices/axis2/trunk/java) into 'axis2' directory inside your eclipse workspace. Run the maven build on this source.

2.   Start a new Java project in eclipse and set the project name as 'axis2'. Now with the default settings in eclipse it will automatically pick up the existing project contents (directories etc).

3.   In the next step of the new java project wizard you can select the source directories that you want to mount. You can browse the directories and select all 'src' and 'test' directories in each maven module (axis2/java/modules/*). Note that in the case of the security module, there's an additional source directory named 'interop'.

4.   In step 3 you can also use the "Libraries" tab to add the jars that all modules depends on. Note that you will have to add all dependent jars required by the modules that you selected/added as source.

5.   There are three places in Axis2 where there is code that don't compile. The missing classes are code generated during the maven build.

·  You can collect the code generated source of the security module - 'interop' source dir from '.../axis2/java/modules/security/target/interop/work/src' or you can code generate (XmlBeans) them with the ping.wsdl in the '.../axis2/java/modules/security/interop' dir and add them to your source in 'axis2/java/modules/security/interop' (Make sure you don't check in these classes when committing.)

·  As for the integration module - 'test' source dir, you can exclude the 'samples' package and "org.apache.axis2.om" package from the source path.

 

 

 

http://www.nandana.org/2008/08/wso2-wsfspring-apache-axis2-for-spring.html

 

here is this war running in jetty:

 

 

This example does deploy to Tomcat as per screenshot in jetty but gets a class loader exception for a springframework class which is not fixed by putting the spring.jar in the app, in tomcat/lin or on the classpath.

(The WSF page is at http://wso2.org/projects/wsf/spring  )

 

 

Now we got the demo application up and running and let's look at the source. First, let's look at the web application description file [wsfpsring/src/main/webapp/WEB-INF/web.xml]



<web-app id="WebApp_ID" version="2.4"

  xmlns="http://java.sun.com/xml/ns/j2ee"

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

  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">



  <listener>

    <listener-class>

      org.springframework.web.context.ContextLoaderListener

    </listener-class>

  </listener>

    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>

   <servlet>
   <servlet-name>axis2</servlet-name>
   <servlet-class>
     org.wso2.spring.ws.servlet.SpringAxis2Servlet
   </servlet-class>
   <load-on-startup>1</load-on-startup>
 </servlet>

   <servlet-mapping>
   <servlet-name>axis2</servlet-name>
   <url-pattern>/axis2/*</url-pattern>
 </servlet-mapping>

   <servlet-mapping>
   <servlet-name>axis2</servlet-name>
   <url-pattern>/services/*</url-pattern>
 </servlet-mapping>

   <welcome-file-list>
   <welcome-file>/axis2-web/index.jsp</welcome-file>
 </welcome-file-list>

</web-app>


SpringAxis2Servlet is defined as servelt in the web.xml and it's the servlet that takes care of all the Axis2 related stuff.

Now let's have look at the spring descriptor file [src/main/webapp/WEB-INF/applicationContext.xml] which will be the configuration file we will be working with most in WSF/Spring.

 

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

<import resource="axis2Config.xml" />

<bean id="Version" class="org.wso2.spring.ws.Version">
<property name="version" value="Hello, I am WSO2 WSF/Spring version service. My version is SNAPSHOT"/>
</bean>
<bean id="services" class="org.wso2.spring.ws.WebServices">
<property name="services">
   <list>
       <bean id="VersionService" class="org.wso2.spring.ws.SpringWebService">
           <property name="serviceBean" ref="Version"/>
           <property name="serviceName" value="Version"/>
       </bean>
   </list>
</property>
</bean>

</beans>

 


First we have imported “axis2Config.xml” and all Axis2 related configurations goes in to this file. But for the moment, let's not worry about this.
And then we have the Version bean declared and WebServices bean is used to expose it as a web service.

Next we will look at how to expose a Spring bean as a web service in “Writing your first Spring web service in WSO2 WSF/Spring”;

Put link here… http://www.nandana.org/2008/08/writing-your-first-spring-web-service.html   This builds/deploys a POJO spring bean as a web service.  This can be followed as a model… plug your own service into the axis framework provided.

 

 

 

Here is an example of building an axis 2 webservice into a webapp. Like the samples that come with axis2 and the helloworld example here, it gets errors in tomcat but deploys ok to glassfish

 

 

How to Embed an Axis2 based Web Service in your Webapp? I have a URL/zip for this tutorial but haven’t got it working.dmh

A: Let's try and deploy an Axis2 based simple web service in our own custom webapp. The first thing we need is an entry for the Axis2 Servlet in our web.xml. See snippet below for such an entry and a mapping for the url as well.

<web-app>
    <servlet>
        <servlet-name>AxisServlet</servlet-name>
        <display-name>Apache-Axis Servlet</display-name>
        <servlet-class>
            org.apache.axis2.transport.http.AxisServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
  <servlet-mapping>
    <servlet-name>AxisServlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
  </servlet-mapping>
</web-app>

Next, We need a simple web service. Let's pick a Book service with 2 operations findBook and getBooks Snippet from BookService.java:

    public Book[] getBooks() {
        return new Book[]{onlyBook};
    }
    public Book findBook(String isbn) {
        if (isbn.equals(onlyBook.getIsbn()))
           return onlyBook;
       return null;    }

Next we need a deployment descriptor for the BookService. As you can see, you can deploy a POJO using RPCMessageReceiver and you can specify a namespace for the schema as well as for the web service itself.

<serviceGroup>
        <service name=”BookService"
             targetNamespace="http://ws.apache.org/axis2/samples/book/">
        <description>Book sample service</description>
        <schema schemaNamespace="http://ws.apache.org/axis2/samples/book/xsd/"/>
        <parameter name="ServiceClass" locked="false">samples.demo.BookService</parameter>
                <operation name="getBooks">
                        <messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
                </operation>
        <operation name="findBook">
            <messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
        </operation>
       </service>
</serviceGroup>

Next, do we really need to create an aar? An aar is useful for hot deployment and service isolation, but this is an embedded scenario, so we go with the "Exploded deployment option" which means that we create a directory structure inside our WEB-INF as follows:

\---WEB-INF
    |   web.xml
    |
    \---services
       \---BookService
            \---META-INF
                   services.xml

Usually we would have dropped a BookService.aar in the services directory, here we create a directory named BookService and drop the deployment descriptor (services.xml) inside the META-INF directory under it. Hmm, did we forget something? Yes, how about an easy build environment using maven2? Here's the layout of our files for maven2.

\---book
    |   pom.xml
    |   README
    |
    \---src
        +---main
        |   |   log4j.properties
        |   |
        |   \---samples
        |       \---demo
        |               Book.java
        |               BookService.java
        |
        +---test
        \---webapp
            \---WEB-INF
                |   web.xml
                |
                \---services
                    \---BookService
                        \---META-INF
                                services.xml

All the jars needed as dependencies are automatically downloaded by maven2 from the Apache and Ibiblio respositories. So you don't even have to download Axis2 dist to build and deploy this sample. All you need to do is unzip the zip below and run

$ mvn install war:war

then rename the resultant war as axis2.war and drop it into any servlet engine. Once your servlet engine starts, you can view the wsdl for your service at:

http://yourhost:port/axis2/services/BookService?wsdl

Enjoy! Please drop an email to axis-dev@ws.apache.org if you run into problems or have comments.

Please download the entire zip here: book.zip

 

Other eclipse webservice links http://www.eclipse.org/webtools/community/tutorials/BottomUpAxis2WebService/bu_tutorial.html

http://www.eclipse.org/webtools/jst/components/ws/1.5/tutorials/TopDownWebService/TopDownWebService.html

 

 

Link for eclipse webservices http://www.eclipse.org/webtools/initial-contribution/IBM/evalGuides/WebServicesToolsEval.html#tour-bu

Similarly, this link is nice for building top down client http://www.eclipse.org/webtools/jst/components/ws/1.5/tutorials/WebServiceClient/WebServiceClient.html

 

 

Here is a general sort of Webservice using Eclipse.  Build a pojo. Add a webservice and client.  You set Axis classpath in Eclipse/window/preferences/webservice/axis preferences

Here’s my class:

 

Adding webservice wizard:

The next dialog lets you select which methods to include.

You can select webservices and test your webservice:

Using test jsp in eclipse:

 

 

 

The string value (url) of the wsdl is already set/generated in the client files by eclipse.

 

http://java.sys-con.com/node/180402  building stock quote service with eclipse

This has a zip of code to download, but no source, except the Impl and Client files below.  It shows how to use Eclipse to build bottom up webservice (meaning… you have a bean and want it to be deployed as a webservice).  It also shows how to build top-down (meaning, no bean, but you have the wsdl file for the service, and you would like to generate a bean with stubbed methods).

 

I didn’t see an interface file but this one works:

package services;

 

public interface StockService {

       

            public double getLatestPrice()throws java.rmi.RemoteException  ;

            

            public long getLatestVolume() throws java.rmi.RemoteException ;

 

            public java.util.Calendar getLatestDateTime() throws java.rmi.RemoteException;

          

            public java.lang.String getStockName() throws java.rmi.RemoteException;

          

            public void setStockName(java.lang.String nm) throws java.rmi.RemoteException;

              

            public java.lang.String getStockSymbol() throws java.rmi.RemoteException;

           

            public void setStockSymbol(java.lang.String sb) throws java.rmi.RemoteException;

              

            public void setLatestStockData(double price, long volume) throws java.rmi.RemoteException ;           

            public java.lang.String getStockHistory() throws java.rmi.RemoteException;

       

 

}

////implementing class

package services;

import java.util.*;

public class StockServiceSoapBindingImpl implements services.StockService{

        String stocknames[]={"ibm","yahoo","proctor&gamble","microsoft","boeing","GM"};

        Random r;

        public StockServiceSoapBindingImpl(){r=new Random();

        }

    public double getLatestPrice() throws java.rmi.RemoteException {

        return r.nextDouble()*1000;  // put some more meaningful code here

    }

    public long getLatestVolume() throws java.rmi.RemoteException {

        return r.nextInt(100);  // put some more meaningful code here

    }

    public java.util.Calendar getLatestDateTime() throws java.rmi.RemoteException {

        return null;  // put some more meaningful code here

    }

    public java.lang.String getStockName() throws java.rmi.RemoteException {

     int i=r.nextInt(stocknames.length);  

        return stocknames[i]; // put some more meaningful code here

    }

    public void setStockName(java.lang.String nm) throws java.rmi.RemoteException {

        // put some more meaningful code here

    }

    public java.lang.String getStockSymbol() throws java.rmi.RemoteException {

        return null; // put some more meaningful code here

    }

    public void setStockSymbol(java.lang.String sb) throws java.rmi.RemoteException {

        // put some more meaningful code here

    }

    public void setLatestStockData(double price, long volume) throws java.rmi.RemoteException {

        // put some more meaningful code here

    }

    public java.lang.String getStockHistory() throws java.rmi.RemoteException {

return null; // put some more meaningful code here

    }

}

 

You can’t create a webservice on the interface, but must select (rt-click) this implementing class, and then select “add webservice”.  In the wizard that comes up, I selected start and test client.  The wizard is fairly complicated and offers many choices.  

 

Here is the client I used:  (Some changes from the original tutorial based on the methods generated in eclipse).

package services;

/**

 * To invoke stock service

 */

public class StockServiceClient {

/**

 * To invoke stock service

 */

     public static void main(String[] args) {

        try{

               StockServiceSoapBindingImplServiceLocator wsl = new StockServiceSoapBindingImplServiceLocator();

               StockServiceSoapBindingImpl ws =  wsl.getStockServiceSoapBindingImpl();/*typically a URL would be needed here to locate this on a different machine*/

               String name = ws.getStockName();

               System.out.println("Stock name: " + name);

               double price = ws.getLatestPrice();

               System.out.println("Stock price: " + price);

               long volume = ws.getLatestVolume();

               System.out.println("Stock volume: " + volume);

        } catch (Exception e) {

               e.printStackTrace();

        }

      }

}

 

Here is the client in eclipse with generated classes and run (as application)  Note – I had the service running in Tomcat.

 

Note also, that I had already installed Axis, and you need to point Eclipse to this axis distribution. (Go to windowàpreferencesàwebservices and add the axis path to exclipse.