Monday, August 22, 2011

NetBeans Web Services

Sun Microsystems is developing a java.net project called Metro. Metro is a complete web services stack, covering all of a developer's needs from simple "Hello, World!" demonstrations to reliable, secured, and transacted web services. For more information, see the Metro home page.

SOAP/WSDL-based. In traditional web service models, web service interfaces are exposed through WSDL documents (a type of XML), which have URLs. Subsequent message exchange is in SOAP, another type of XML document.
In SOAP-based web services, Java utilites create a WSDL file based on the Java code in the web service. The WSDL is exposed on the net. Parties interested in using the web service create a Java client based on the WSDL. Messages are exchanged in SOAP format. The range of operations that can be passed in SOAP is much broader than what is available in REST, especially in security.
SOAP-based web services are suitable for heavyweight applications using complicated operations and for applications requiring sophisticated security, reliability or other WS-* standards-supported features. They are also suitable when a transport protocol other than HTTP has to be used. Many of Amazon's web services, particularly those involving commercial transactions, and the web services used by banks and government agencies are SOAP-based.
The Java API for XML Web Services (JAX-WS) is the current model for SOAP-based web services in Metro. JAX-WS is built on the earlier JAX-RPC model but uses specific Java EE 5 features, such as annotations, to simplify the task of developing web services. Because it uses SOAP for messaging, JAX-WS is transport neutral. It also supports a wide range of modular WS-* specifications, such as WS-Security and WS-ReliableMessaging.
Note: Although we strongly recommend using the JAX-WS model for creating SOAP services, the IDE continues to support JAX-RPC web services for legacy reasons. Install the "JAX-RPC Web Services" plug-in to develop them.
When you create a web service client, you have the option of using either the JAX-WS or JAX-RPC model. This is because some older JAX-RPC services use a binding style that is not supported by JAX-WS. These services can only be consumed by JAX-RPC clients

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 your choice of implementation. If you are creating a Java EE 6 application, use a web container in any case, because you can put EJBs directly in a web application. For example, if you plan to deploy to the Tomcat Web Server, which only has a web container, create a web application, not an EJB module.
  1. Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Java Web category or EJB Module from the Java EE category.
    You can create a JAX-WS web service in a Maven project. Choose File > New Project (Ctrl-Shift-N) and then Maven Web Application or Maven EJB module from the Maven category. If you haven't used Maven with NetBeans before, see Maven Best Practices.
  2. Name the project CalculatorWSApplication. Select a location for the project. Click Next.
  3. Select your server and Java EE version and click Finish.
    To use the Oracle WebLogic server, register the server with the IDE. Also, if you are using the WebLogic server, watch the screencast on Deploying a Web Application to Oracle WebLogic.

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 and type org.me.calculator in Package. Leave Create Web Service from Scratch selected.
  3. If you are creating a Java EE 6 project, select Implement Web Service as a Stateless Session Bean.
    New Web Service Wizard for EE 6, with bean options
  4. Click Finish. The Projects window displays the structure of the new web service and the source code is shown in the editor area.

Adding an Operation to the Web Service

The goal of this exercise is to add to the web service an operation that adds two numbers received from a client. The NetBeans IDE provides a dialog for adding an operation to a web service. You can open this dialog either in the web service visual designer or in the web service context menu.
Warning: The visual designer is not available in Maven projects.
To add an operation to the web service:
  1. Either:
    • Change to the Design view in the editor.
      Design view of web service editor
    Or:
    • Find the web service's node in the Projects window. Right-click that node. A context menu opens.
      Web service node's context menu with Add Operation item highlighted
  2. Click Add Operation in either the visual designer or the context menu. A dialog box appears where you can define the new operation.
  3. In the upper part of the Add Operation dialog box, type add in Name and type int in the Return Type drop-down list. In the lower part of the Add Operation dialog box, click Add and create a parameter of type int named i. Then click Add again and create a parameter of type int called j. You now see the following:

    Add Operation dialog
  4. Click OK at the bottom of the Add Operation dialog box. The visual designer now displays the following:

    Web service visual designer showing added operation
  5. Click Source and view the code that you generated in the previous steps. It differs whether you created the service as an EE6 stateless bean or not. Can you see the difference in the screenshots below?
    Result: EE5Result: EE 6 stateless bean
  6. In the editor, extend the skeleton add operation to the following (changes are in bold):
    @WebMethod
        public int add(@WebParam(name = "i") int i, @WebParam(name = "j") int j) {
            int k = i + j;
            return k;
          }
As you can see from the preceding code, the web service simply receives two numbers and then returns their sum. In the next section, you use the IDE to test the web service.

Deploying and Testing the Web Service

After you deploy a web service to a server, you can use the IDE to open the server's test client, if the server has a test client. The GlassFish and WebLogic servers provide test clients. If you are using the Tomcat Web Server, there is no test client, but the IDE can open a page showing that the web service is deployed. No facility for testing whether an EJB module is deployed successfully is currently available.
To test successful deployment to a server:
  1. Right-click the project and choose Deploy. The IDE starts the application server, builds the application, and deploys the application to the server. You can follow the progress of these operations in the CalculatorWSApplication (run-deploy) and the GlassFish server or Tomcat tabs in the Output view.
  2. In the IDE's Projects tab, expand the Web Services node of the CalculatorWSApplication project. Right-click the CalculatorWS node, and choose Test Web Service.
    Projects tab showing Test Web Service context menu option The IDE opens the tester page in your browser, if you deployed a web application to the GlassFish server. For the Tomcat Web Server and deployment of EJB modules, the situation is different:
    • If you deployed to the GlassFish server, type two numbers in the tester page, as shown below:
      Web service tester page when service successfully deployed to the GlassFish server The sum of the two numbers is displayed:

      Web page showing result of web service test
    • 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
    • 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 GlassFish 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.

Samples

You can open a complete EE6 version of the Calculator service by choosing File > New Project (Ctrl-Shift-N) and navigating to Samples > Java Web Services > Calculator (EE6).
A Maven Calculator Service and a Maven Calculator Client are available in Samples > Maven.


Note By Rehan: if glass fish or tomcat server is unable to start, then check that 8080 port is not already in use.

Consuming the Web Service

Now that you have deployed the web service, you need to create a client to make use of the web service's add method. Here, you create three clients— a Java class in a Java SE application, a servlet, and a JSP page in a web application.
Note: A more advanced tutorial focusing on clients is Developing JAX-WS Web Service Clients.

Client 1: Java Class in Java SE Application

In this section, you create a standard Java application. The wizard that you use to create the application also creates a Java class. You then use the IDE's tools to create a client and consume the web service that you created at the start of this tutorial.
  1. Choose File > New Project (Ctrl-Shift-N). Select Java Application from the Java category. Name the project CalculatorWS_Client_Application. Leave Create Main Class selected and accept all other default settings. Click Finish.
  2. Right-click the CalculatorWS_Client_Application node and choose New > Web Service Client. The New Web Service Client wizard opens.
  3. Select Project as the WSDL source. Click Browse. Browse to the CalculatorWS web service in the CalculatorWSApplication project. When you have selected the web service, click OK.
    Browse Web Services dialog showing CalculatorWS service
  4. In NetBeans IDE 7.0, you can select a package for the client java artifacts. Leave this field empty.
    New Web Service Client wizard showing package name
  5. Leave the other settings at default and click Finish. The Projects window displays the new web service client, with a node for the add method that you created:

    New web service client in Java SE application displayed in the Projects window
  6. Double-click your main class so that it opens in the Source Editor. Drag the add node below the main() method.
    Dragging and dropping the add operation into the main class body You now see the following:
    public static void main(String[] args) {
        // TODO code application logic here
    }
    private static int add(int i, int j) {
        org.me.calculator.CalculatorWS_Service service = new org.me.calculator.CalculatorWS_Service();
        org.me.calculator.CalculatorWS port = service.getCalculatorWSPort();
        return port.add(i, j);
    }
    Note: Alternatively, instead of dragging the add node, you can right-click in the editor and then choose Insert Code > Call Web Service Operation.
  7. In the main() method body, replace the TODO comment with code that initializes values for i and j, calls add(), and prints the result.
    public static void main(String[] args) {
        int i = 3;
        int j = 4;
        int result = add(i, j);
        System.out.println("Result = " + result);
    }
  8. Surround the main() method code with a try/catch block that prints an exception.
    public static void main(String[] args) {
        try {
            int i = 3;
            int j = 4;
            int result = add(i, j);
            System.out.println("Result = " + result);
        } catch (Exception ex) {
            System.out.println("Exception: " + ex);
        }
    }
  9. Right-click the project node and choose Run. The Output window now shows the sum:
    compile:
        run:
        Result = 7
          BUILD SUCCESSFUL (total time: 1 second)

Client 2: Servlet in Web Application

In this section, you create a new web application, after which you create a servlet. You then use the servlet to consume the web service that you created at the start of this tutorial.
  1. Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Java Web category. Name the project CalculatorWSServletClient. Click Next and then click Finish.
  2. Right-click the CalculatorWSServletClient node and choose New > Web Service Client. The New Web Service Client wizard appears.
  3. Select Project as the WSDL source. Click Browse. Browse to the CalculatorWS web service in the CalculatorWSApplication project. When you have selected the web service, click OK.
    Browse Web Services dialog showing CalculatorWS service
  4. In NetBeans IDE 7.0, you can select a package for the client java artifacts. Leave this field empty.
  5. Leave the other settings at default and click Finish. The Web Service References node in the Projects window displays the structure of your newly created client, including the add operation that you created earlier in this tutorial:

    New web service client in servlet displayed in the Projects window
  6. Right-click the CalculatorWSServletClient project node and choose New > Servlet. Name the servlet ClientServlet and place it in a package called org.me.calculator.client. Click Finish.
  7. To make the servlet the entry point to your application, right-click the CalculatorWSServletClient project node and choose Properties. Open the Run properties and type /ClientServlet in the Relative URL field. Click OK.
  8. If there are error icons for ClientServlet.java, right-click the project node and select Clean and Build.
  9. In the Source Editor, drag the add operation anywhere in the body of the ClientServlet class. The add() method appears at the end of the class code.
    Note: Alternatively, instead of dragging the add node, you can right-click in the editor and then choose Insert Code > Call Web Service Operation.
    private int add(int i, int j) {
        org.me.calculator.CalculatorWS port = service.getCalculatorWSPort();
        return port.add(i, j);
    }
  10. Remove the line that comments out the body of the processRequest method. This is the line:
    /* 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, add code that initializes values for i and j, calls add(), and prints the result.
    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();
        try {
            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>");
    
            int i = 3;
            int j = 4;
            int result = add(i, j);
            out.println("Result = " + result);
    
            out.println("</body>");
            out.println("</html>");
            
        } finally {            
            out.close();
        }
    }
  11. Surround the added code with a try/catch block that prints an exception.
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            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 {
                int i = 3;
                int j = 4;
                int result = add(i, j);
                out.println("Result = " + result);
            } catch (Exception ex) {
                out.println("Exception: " + ex);
            }
            out.println("</body>");
            out.println("</html>");
            
        } finally {            
            out.close();
        }
    }
  12. Right-click the project node and choose Run. The server starts, if it wasn't running already; the application is built and deployed, and the browser opens, displaying the calculation result, as shown below:
    New web service client in servlet displayed in the Projects window

Client 3: JSP Page in Web Application

In this section, you create a new web application and then consume the web service in the default JSP page that the Web Application wizard creates.
Note: If you want to run a JSP web application client on Oracle WebLogic, see Running a Java Server Faces 2.0 Application on WebLogic.
  1. Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Java Web category. Name the project CalculatorWSJSPClient. Click Finish.
  2. Right-click the CalculatorWSJSPClient node and choose New > Web Service Client.
  3. Select Project as the WSDL source. Click Browse. Browse to the CalculatorWS web service in the CalculatorWSApplication project. When you have selected the web service, click OK.
    Browse Web Services dialog showing CalculatorWS service
  4. In NetBeans IDE 7.0, you can select a package for the client java artifacts. Leave this field empty.
  5. Leave the other settings at default and click Finish. The Projects window displays the new web service client, as shown below:

    New web service client in servlet displayed in the Projects window
  6. In the Web Service References node, expand the node that represents the web service. The add operation, which you will invoke from the client, is now exposed.
  7. 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, as you can see here:
    <%
    try {
        org.me.calculator.CalculatorWSService service = new org.me.calculator.CalculatorWSService();
        org.me.calculator.CalculatorWS port = service.getCalculatorWSPort();
         // TODO initialize WS operation arguments here
        int i = 0;
        int j = 0;
        // TODO process result here
        int result = port.add(i, j);
        out.println("Result = "+result);
    } catch (Exception ex) {
        // TODO handle custom exceptions here
    }
    %>
    Change the value for i and j from 0 to other integers, such as 3 and 4. Replace the commented out TODO line in the catch block with out.println("exception" + ex);.
  8. Right-click the project node and choose Run. 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



1 comment:

  1. Nice information about test automation tools my sincere thanks for sharing post Please continue to share this post. weblogic administrator training

    ReplyDelete