Showing posts with label Starting with Web Services. Show all posts
Showing posts with label Starting with Web Services. Show all posts

Friday, May 6, 2016

Starting with: REST web services, server and client examples.

1) Open Eclipse IDE
2) Create dynamic web project named "startingWithRESTWebServiceServer" (and set 3 at dynamic module version)
3)Download from jersey download page last available JAX-RS 2.0 API jar distribution
4)Unzip it and copy all jars under api, ext and lib folders under WEB-INF/lib
5)Ensure that you have your "Web App Libraries" configured in your project build path.
6) right-click on src folder and create a new package name com.webservices
7)Then create User class with this content:

package com.webservices;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "user")
public class User implements Serializable {

   private static final long serialVersionUID = 1L;
   private int id;
   private String name;
   private String profession;

   public User(){}
  
   public User(int id, String name, String profession){
      this.id = id;
      this.name = name;
      this.profession = profession;
   }

   public int getId() {
      return id;
   }

   @XmlElement
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   @XmlElement
   public void setName(String name) {
      this.name = name;
   }
   public String getProfession() {
      return profession;
   }
   @XmlElement
   public void setProfession(String profession) {
      this.profession = profession;
   }       
}


8)Then create UserDao class with this content:

package com.webservices;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
   public List<User> getAllUsers(){
      List<User> userList = null;
      try {
         File file = new File("Users.dat");
         if (!file.exists()) {
            User user = new User(1, "Maurizio", "Fisherman");
            userList = new ArrayList<User>();
            userList.add(user);
            saveUserList(userList);       
         }
         else{
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);
            userList = (List<User>) ois.readObject();
            ois.close();
         }
      } catch (IOException e) {
         e.printStackTrace();
      } catch (ClassNotFoundException e) {
         e.printStackTrace();
      }       
      return userList;
   }

   private void saveUserList(List<User> userList){
      try {
         File file = new File("Users.dat");
         FileOutputStream fos;

         fos = new FileOutputStream(file);

         ObjectOutputStream oos = new ObjectOutputStream(fos);
         oos.writeObject(userList);
         oos.close();
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }  
}


9)Then create UserService class with this content:
10)Then create or update web.xml file(under WebContent folder) with this content:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">
   <display-name>startingWithRESTWebServiceServer</display-name>
   <servlet>
      <servlet-name>REST Wer Service server example</servlet-name>
      <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
         <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.webservices</param-value>
         </init-param>
      </servlet>
   <servlet-mapping>
   <servlet-name>REST Wer Service server example</servlet-name>
      <url-pattern>/rest/*</url-pattern>
   </servlet-mapping> 
</web-app>




11)Now we are ready to deploy the application.
So deploy the exported project as war file under tomcat or configure it internal bundled and add the project to it.
Then we can use a chrome plugin extension(as SimpleRestClient) to test it.
Pointing to url:
http://localhost:8080/startingWithRESTWebServiceServer/rest/UserService/users

That's all....
Bye...
 

Friday, March 21, 2014

Starting with Web Services(Eclipse Kepler, Tomcat 7)

Here is a small guide to learn how web services run and how Eclipse simplifies the developer job.

The configuration expected is
Java 6
Eclipse Kepler for JavaEE developer
Tomcat 7 (Eclipse embedded configuration)

1) Under Eclipse create a new Dynamic Web Project.
Choose a custom name(remember this will be the server side appl), the target runtime(Tomcat 7 previously configurated) and after in the "Dynamic Web Module Version" combo menu choose the 2.5 specific. Then finish(if you want customize the other fields to choose in the others windows.

2) I create 2 classes.
One is my bean class that is the object that "travel" in the communication between my smalls server and client applications.... 
It's com.test.TestMessage and this is the content:

package com.test;

/**
 * 
 * Test bean class with simple string message property
 * 
 * @author Maurizio Franco
 *         http://maurizio-franco.blogspot.it
 *         maurizio.franco@ymail.com
 */
public class TestMessage {
   
    private String message ;

    /**
     * @return the message
     */
    public String getMessage() {
        return message;
    }

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



3) This is the com.test.TestProvider that is the class that will provide the methods(in this case only one: getMessage) as endpoints for this server side application.


package com.test;

/**
 *
 * Test class, provides a simple method that returns a TestMessage instance.
 *
 * @author Maurizio Franco
 *         http://maurizio-franco.blogspot.it
 *         maurizio.franco@ymail.com
 */
public class TestProvider {

    public TestMessage getMessage () {
        TestMessage tm = new TestMessage () ;
        tm.setMessage("Prova messaggio di test...");
        return tm ;
    }
   
}



4) Now we are ready to produce the wsdl file that is at the base of the WebServices architecture.
Click on the project and choose New --> Web Service
In the Service implementation we have to choose the TestProvider class
(so put the complete name com.test.TestProvider)
Then we can choose the only Deploy service setting(see the image above) and ensure that under "Configuration:" you have
- Server runtime Tomcat v.7.0 Server (or the server runtime you prefer)
- Web service runtime: Apache Axis (that's the lib Eclipse will use to produce the wsdl)
- Service project: StartingWithWebServices_Server (that's the name of my project, so you select the yours)
Then click on Finish

Well, you have ended the procedure to build your server side application.
Ensure Eclipse have added into Tomcat(embedded) the application into the deployed list. If no add it.
Now we have to create a client side application.

5) Create another Dynamic Web Project with the same specifics of the previously(this will be the client side appl).

6) Point on the TestProvider.wsdl that is in the previously project(the server side application) into WebContent/wsdl folder
Select "Test client", the as hight as possible option and then click on finish.
Ensure you have on the right, under Configuration: Client project: that your project name is correctly indicated(TestWSClient is the current name of my project).
We choose the "Test client" option to produce also, the tests jsp files for quickly try all the "game".





Ensure you have the client application into Tomcat(embedded) deployed applications.

Go under your browser and point to:
http://loaclhost:8080/StartingWithWSClient/sampleTestProviderProxy/TestClient.jsp

where  StartingWithWSClient is the Context name that I give to my project....

Here you can see three methods added as default from wsdl generator, more the method contained into the TestProvider class.
The getMessage method.
If you click on it in the center frame you can see two buttons; clicking on invoke button, in the above frame you can see the result of the method invocation on the server side application.

This should be a quick way to see how to invoke from a jsp file a method, and relative response from the server side application, all through web service architecture.


You can find these small applications(the client and the server sided) under sourceforge.net site, ready to download, via SVN.
The url are:
svn://svn.code.sf.net/p/mauriziofranco/code/StartingWithWebServices/trunk/StartingWithWebServices_Server
svn://svn.code.sf.net/p/mauriziofranco/code/StartingWithWebServices/trunk/StartingWithWebServices_Client
And the istructions from command line are:
svn checkout svn://svn.code.sf.net/p/mauriziofranco/code/StartingWithWebServices/trunk/StartingWithWebServices_Server  mauriziofranco-code
svn checkout svn://svn.code.sf.net/p/mauriziofranco/code/StartingWithWebServices/trunk/StartingWithWebServices_Client  mauriziofranco-code

That's all.....
Bye..