Jetty RESTFul Web Service
In last tutorial you saw how to create Jetty server and integrate Servlet with it. If you want to create full fledged RESTFul web service with Jetty you can create it easily, although many choices are there and I will Jersey with Jetty to create RESTFul web service.
- Create maven project name: JettyRESTFulWebService as full project structure shown below:
- pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javahonk</groupId> <version>0.0.1</version> <artifactId>JettyRESTFulWebService</artifactId> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <org.springframework.version>4.1.5.RELEASE</org.springframework.version> <org.apache.log4j.version>2.1</org.apache.log4j.version> </properties> <dependencies> <!-- Jetty/Jersey dependency --> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-json</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.8.8</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.8.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.1.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <version>8.1.12.v20130726</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-servlet</artifactId> <version>8.1.12.v20130726</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.5</version> </dependency> <!-- Apache HTTP client --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.6</version> </dependency> <!-- Log4j --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${org.apache.log4j.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${org.apache.log4j.version}</version> </dependency> </dependencies> </project>
- JettyServer.java:
package com.javahonk; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import com.sun.jersey.spi.container.servlet.ServletContainer; public class JettyServer { public static void main(String[] args) throws Exception { ServletHolder sh = new ServletHolder(ServletContainer.class); sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig"); sh.setInitParameter("com.sun.jersey.config.property.packages", "com.javahonk.restful.resource"); sh.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true"); Server server = new Server(1002); ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); context.addServlet(sh, "/*"); server.start(); server.join(); } }
RESTFulResource.java:
package com.javahonk.restful.resource; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.javahonk.model.Person; @Path("/javahonkJetty") public class RESTFulResource { @GET @Path("/person/{name}") @Produces(MediaType.TEXT_HTML) public String getHTMLData(@PathParam("name") String name) { return name; } @GET @Path("/person/xml/{name}") @Produces(MediaType.APPLICATION_XML) public Person getXMLData( @PathParam("name") String name ) { if (name.equalsIgnoreCase("Java")) { return new Person("Java Honk","NY"); } else { return new Person("Some Other Person","NY"); } } @GET @Path("/person/json/{name}") @Produces(MediaType.APPLICATION_JSON) public Person getJASONData (@PathParam("name") String name ) { if (name.equalsIgnoreCase("Java")) { return new Person("Java Honk","NY"); } else { return new Person("Some Other Person","NY"); } } @POST @Path("/postdata/applicationOctetStream") @Consumes(MediaType.APPLICATION_OCTET_STREAM) public Response postDataStream(@Context HttpServletRequest request, @Context HttpServletResponse response) { String body = null; StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null; try { InputStream inputStream = request.getInputStream(); if (inputStream != null) { bufferedReader = new BufferedReader(new InputStreamReader( inputStream)); char[] charBuffer = new char[128]; int bytesRead = -1; while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { stringBuilder.append(charBuffer, 0, bytesRead); } } else { stringBuilder.append(""); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException ex) { ex.printStackTrace(); } } } body = stringBuilder.toString(); return Response.status(200).entity(body).build(); } }
- Model class: Person.java:
package com.javahonk.model; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Person { private String name; private String location; public Person() { super(); } public Person(String name, String location) { this.name = name; this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } }
- To test MediaType.APPLICATION_OCTET_STREAM from java you can use HttpClientPostTest.java:
package com.javahonk; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.HttpClientBuilder; public class HttpClientPostTest { public static void main(String[] args) { postHttpPost("http://localhost:1002/javahonkJetty/postdata/applicationOctetStream", new String("Java Honk").getBytes()); } private static void postHttpPost(String url, byte[] message) { try { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost postRequest = new HttpPost(url); ByteArrayEntity entity = new ByteArrayEntity(message); entity.setContentType(MediaType.APPLICATION_OCTET_STREAM); postRequest.setEntity(entity); HttpResponse response = httpClient.execute(postRequest); if (response.getStatusLine().getStatusCode() != Response.Status.OK .getStatusCode()) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (response.getEntity().getContent()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
- To test XML data you could use: XMLClientTest.java:
package com.javahonk; import com.javahonk.model.Person; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; public class XMLClientTest { public static void main(String[] args) { WebResource webResource = Client.create().resource("http://localhost:1002/javahonkJetty/person/xml/java"); ClientResponse response = webResource.accept("application/xml").get(ClientResponse.class); if (200 != response.getStatus()) { System.out.println("Fail to process response : " + response.getStatus()); } Person person = response.getEntity(Person.class); System.out.println("Response from server: "); System.out.println("Name:"+person.getName()+" Location: "+person.getLocation()); } }
- That’s it. To test this application start JettyServer as java application and mentioned in RESTFulResource.java, we have created multiple resources for HTML, XML, JSON, APPLICATION_OCTET_STREAM and you can test easily with any RESTful tools I have used Postman below are some outputs:
- For more information please visit Jetty documentation here
Download Project: JettyRESTFulWebService
How can i runs this on a ubuntu server so i can do requests against this webservice?