Showing posts with label Tomcat. Show all posts
Showing posts with label Tomcat. Show all posts

Friday, January 20, 2017

JAX-RS, Rest Service in Java with Jersey


JAX-RS stands for JAVA API for RESTful Web Services. JAX-RS is a JAVA based programming language API and specification to provide support for created RESTful Webservices. JAX-RS makes heavy use of annotations available since Java SE 5 to simplify development of JAVA based web services creation and deployment. It also provides supports for creating clients for RESTful web services..

In this case, we are going to use build a RESTful Web Service in Java using Jersey. But, what is Jersey? According to Jersey website (https://jersey.java.net/): 

"Jersey framework is more than the JAX-RS Reference Implementation. Jersey provides it’s own API that extend the JAX-RS toolkit with additional features and utilities to further simplify RESTful service and client development. Jersey also exposes numerous extension SPIs so that developers may extend Jersey to best suit their needs.

Goals of Jersey project can be summarized in the following points:
  • Track the JAX-RS API and provide regular releases of production quality Reference Implementations that ships with GlassFish;
  • Provide APIs to extend Jersey & Build a community of users and developers; and finally
  • Make it easy to build RESTful Web services utilising Java and the Java Virtual Machine."
For this exercise we are going to use:
  • Java 1.7
  • Tomcat 7
  • Jersey
  • Eclipse IDE
Open Eclipse and create a Web Dynamic Project. Let's name the project JAX-RS-Jersey. We don't need to create an EAR to our project, so unselect that option.



then, click next and on Web Module screen, select "Generate web.xml deployment descriptor" option 




Then, we need to place Jersey .jars in: Webcontent/WEB-INF/lib folder. You can get them @ https://jersey.java.net/ . Also I'll include all these files in my GitHub account, I'll explain at the end of this tutorial. Your workspace should show you the jars. If you don't see them, refresh the project



In Eclipse, go to Java Resources folder, right click on "src" and add a new package, let's name it: com.rolandoFebrero.rest (you can change these names to anything you want, this is a free country, don't worry). Now, create a new class inside that package: Hello.java

Again, create another package com.rolandoFebrero.restclient and inside that, create another java class, let's name it ClientTest.java. Your workspace should look like this:




In Hello.java, paste this code:



package com.rolandoFebrero.rest;

/**
 * Created by: Carlos Rolando Febrero
 * 
 */

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/hello")
public class Hello {
  @GET
  @Produces(MediaType.TEXT_PLAIN)
  public String sayPlainTextHello() {
    return "Hello there, RESTfull service with Jersey (plain)";
  }
  // This method is called if XML is request
  @GET
  @Produces(MediaType.TEXT_XML)
  public String sayXMLHello() {
    return "<?xml version=\"1.0\"?>" + "<hello> Hello there, RESTfull service with Jersey (xml)" + "</hello>";
  }

  // This method is called if HTML is request
  @GET
  @Produces(MediaType.TEXT_HTML)
  public String sayHtmlHello() {
    return "<html> " + "<title>" + "Hello Jersey" + "</title>"
        + "<body><h1>" + "Hello there, RESTfull service with Jersey (html)" + "</h1></body>" + "</html> ";
  }

} 


In ClientTest.java, paste this code:



package com.rolandoFebrero.restClient;

/**
 * Created by: Carlos Rolando Febrero
 * 
 */

import java.net.URI;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.jersey.client.ClientConfig;

public class ClientTest {
  public static void main(String[] args) {
    ClientConfig config = new ClientConfig();
    Client client = ClientBuilder.newClient(config);
    WebTarget target = client.target(getBaseURI());

    System.out.println(target.path("rest").path("hello").request().accept(MediaType.TEXT_PLAIN).get(String.class));
    System.out.println(target.path("rest").path("hello").request().accept(MediaType.TEXT_XML).get(String.class));
    System.out.println(target.path("rest").path("hello").request().accept(MediaType.TEXT_HTML).get(String.class));
  }

  private static URI getBaseURI() {
    return UriBuilder.fromUri("http://localhost:8080/restfuljersey").build();
  }
} 


In web.xml paste this code:



<?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">
 <servlet>
    <servlet-name>Jersey REST Service</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.rolandoFebrero.rest</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app> 



Now, let's add Tomcat server to our workspace. Click in Server tab and add a new server...





Select Apache Tomcat server:




Select you Tomcat path and click Finish:



Now, that you have added Tomcat, right click and start:



Go to Console tab and make sure there are no error, if so, deelete Tomcat and added it again. After that add our project to Tomcat and restart the server:




At this point, if everything is OK, you should be able to go to: http://localhost:8080/JAX-RS-Jersey/rest/hello

You'll get the following:




Want to download the code for this project?

go to my github account: https://github.com/rolando-febrero/JAX-RS-Jersey





Programming thought of the day:


  • Unix is user friendly. It’s just selective about who its friends are.


Tuesday, December 20, 2016

Java SOAP WebService and WebService Client with Apache Axis



Creating and deploying a simple WebService is not as hard as you think. For this example we are going to work with Apache Axis WebService. Axis is essentially a SOAP engine ,a framework for constructing SOAP processors such as clients, servers, gateways, etc.
Apache Axis is a SOAP toolkit that makes it easy to create, deploy, and consume web services. By using Axis, you will be able to quickly convert existing Java functionality into web services, deploy those services, and be able to communicate with them remotely via the Internet, usually through firewalls (if necessary).

More precisely, Axis is an implementation of SOAP. Most people like to think of it as a toolkit. From the programmer's point of view, it's like an API. It makes it easy for you to communicate - with SOAP - to a remote object, without having to worry about the details associated with the protocol. In practice, it is a lot like using RPC, CORBA, RMI, or any of the other distributed computing technologies you may have experience with. The process is largely the same: you describe the target of your communication, invoke the remote method and marshall your parameters, and then demarshall the return values. Since AXIS makes this process simpler than ever, development is a breeze.

Well, let's start coding...
For this example we are going to use:
  • Java (here I'm using JDK 1.7, Click here if you need help installing Java JDK in Windows)
  • Apache Tomcat v7.xx
  • Eclipse Luna

Install Apache Tomcat and add it to Eclipse... File --> New --> Other. Type in server, and follow the wizard.

Open Eclipse and create a "Dynamic Web Project"
For project Name: JavaApacheAxisWebService




On your Eclipse project, expand Java Resources and under /src create a 
new class: MyJavaWebServiceHelloWorld 
and for Package: rolandofebrero.com.web.service



                                 


Now, double click on MyJavaWebServiceHelloWorld.java and add the following code:



Right click on MyJavaWebServiceHelloWorld.java --> Web Services --> Create Web Service


                                   



On the next screen, make sure you have selected Tomcat and Apache Axis in both service and client. Please see the image bellow:



If after clicking finish you see any error regarding to you server, make sure you can start Tomcat with no errors. If not, delete your server, and add it again. Server should start with no errors before creating WebService.

If everything was OK, your project should look like this:



If the server started correctly, JavaApacheAxisWebService and JavaApacheAxisWebServiceClient are automatically deployed to Tomcat server.

By default Eclipse provides a Web service Test Client Window in which we can consume our service



If we click on getEndpoint() link, it will provide us with the endpoint of our service, which is:

        http://localhost:14823/JavaApacheAxisWebService/services/MyJavaWebServiceHelloWorld

put that endpoint in your browser and add ?WSDL at the end. We will see the WSDL created. If you want to consume this service, you might need the WSDL, or just use SoapUI and create a soap project and start testing this new service....    
     


You can download the code for this project from my GitHub account:

https://github.com/rolando-febrero/JavaApacheAxisWebService




Programming thought of the day:


  • My software never has bugs. It just develops random features.