REST Application in Java

Below are the basic steps to create a working REST API Application in java, using Eclipse.
The demo shows just a “To Uppercase String” application

Steps:

  • In Eclipse, create a new Project(Dynamic Web Project)
  • Create the new Project and give it a suitable name.
  • after project creation, right click on the project, and select Configure-> Convert to Maven Project
  • After process completion, a pom.xml would be made available.
  • Add the dependencies from the pom.xml that I have presented below.
  • Create new Class as sample shown below and create methods that you need to expose.
  • Add business logic as per need.
  • Add Annotations to the class as shown below
  • In the Web Content folder, modify the web.xml as shown in the sample web.xml

The basic mode is complete. Now just configure your local web server and deploy your application to the web server.

Use any REST Client like Postman(Chrome Plugin) to test the app.

Code Samples

Unirest: Lightweight HTTP Request Client Libraries

UniRest

Unirest is a set of lightweight HTTP libraries available in multiple languages, built and maintained by the Mashape team.

Unirest.post("http://httpbin.org/post")
  .queryString("name", "Mark")
  .field("last", "Polo")
  .asJson()

Features

  • Make GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS requests
  • Both syncronous and asynchronous (non-blocking) requests
  • It supports form parameters, file uploads and custom body entities
  • Easily add route parameters without ugly string concatenations
  • Supports gzip
  • Supports Basic Authentication natively
  • Customizable timeout, concurrency levels and proxy settings
  • Customizable default headers for every request (DRY)
  • Customizable HttpClient and HttpAsyncClient implementation
  • Automatic JSON parsing into a native object for JSON responses
  • Customizable binding, with mapping from response body to java Object

Installing

Is easy as pie. Kidding. It’s about as easy as doing these little steps:

With Maven

You can use Maven by including the library:

<dependency>
    <groupId>com.mashape.unirest</groupId>
    <artifactId>unirest-java</artifactId>
    <version>1.4.7</version>
</dependency>

There are dependencies for Unirest-Java, these should be already installed, and they are as follows:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.3.6</version>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpasyncclient</artifactId>
  <version>4.0.2</version>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpmime</artifactId>
  <version>4.3.6</version>
</dependency>
<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20140107</version>
</dependency>

If you would like to run tests, also add the following dependency along with the others:

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
  <scope>test</scope>
</dependency>

Without Maven

Alternatively if you don’t use Maven, you can directly include the JAR file in the classpath:http://oss.sonatype.org/content/repositories/releases/com/mashape/unirest/unirest-java/1.4.7/unirest-java-1.4.7.jar

Don’t forget to also install the dependencies (org.json, httpclient 4.3.6, httpmime 4.3.6,httpasyncclient 4.0.2) in the classpath too.

There is also a way to generate a Unirest-Java JAR file that already includes the required dependencies, but you will need Maven to generate it. Follow the instructions at http://blog.mashape.com/post/69117323931/installing-unirest-java-with-the-maven-assembly-plugin

Creating Request

So you’re probably wondering how using Unirest makes creating requests in Java easier, here is a basic POST request that will explain everything:

HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
  .header("accept", "application/json")
  .queryString("apiKey", "123")
  .field("parameter", "value")
  .field("foo", "bar")
  .asJson();

Requests are made when as[Type]() is invoked, possible types include Json, Binary, String, Object.

If the request supports and it is of type HttpRequestWithBody, a body it can be passed along with.body(String|JsonNode|Object). For using .body(Object) some pre-configuration is needed (see below).

If you already have a map of parameters or do not wish to use seperate field methods for each one there is a.fields(Map<String, Object> fields) method that will serialize each key – value to form parameters on your request.

.headers(Map<String, String> headers) is also supported in replacement of multiple header methods.

Full Documentation @ unirest.io

SOAP Version Mismatch: SOAP Version “SOAP 1.2 Protocol” in request does not match the SOAP version “SOAP 1.1 Protocol” of the Web service.

We were getting the below error in our project, when trying to invoke a web service.

[Server:server-one] 07:29:12,927 ERROR [stderr] (http-/10.99.12.28:8080-13) org.springframework.ws.soap.client.SoapFaultClientException: [ISS.0088.9168] SOAP Version Mismatch: SOAP Version "SOAP 1.2 Protocol" in request does not match the SOAP version "SOAP 1.1 Protocol" of the Web service.
[Server:server-one] 07:29:12,928 ERROR [stderr] (http-/10.99.12.28:8080-13) at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:37)
[Server:server-one] 07:29:12,929 ERROR [stderr] (http-/10.99.12.28:8080-13) at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:774)
[Server:server-one] 07:29:12,929 ERROR [stderr] (http-/10.99.12.28:8080-13) at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:600)
[Server:server-one] 07:29:12,929 ERROR [stderr] (http-/10.99.12.28:8080-13) at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:537)
[Server:server-one] 07:29:12,930 ERROR [stderr] (http-/10.99.12.28:8080-13) at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:384)
[Server:server-one] 07:29:12,930 ERROR [stderr] (http-/10.99.12.28:8080-13) at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:378)
[Server:server-one] 07:29:12,931 ERROR [stderr] (http-/10.99.12.28:8080-13) at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:370)

Solution:
The solution lies in the configuration files used by spring.
Here in our project, the version specified in this file was 1.2 where as the web service was expecting 1.1






How to put time restriction on web service function call?

Add the following 2 imports

import com.sun.xml.ws.developer.JAXWSProperties;
import javax.xml.ws.BindingProvider;

Just add this before the function call where you call web service.


((BindingProvider)port).getRequestContext()
.put(JAXWSProperties.CONNECT_TIMEOUT, 100);
((BindingProvider)port).getRequestContext()
.put(JAXWSProperties.REQUEST_TIMEOUT, 100);

The prefix “jaxb” for element “jaxb:globalBindings” is not bound.

I’m using xjc to compile XML Schema into JAXB objects and the
compiling is fine unless I try to define jaxb bindings. For instance,
if I try adding this code in the schema:




bindingStyle="modelGroupBinding"
choiceContentProperty="true" >


<jaxb:javaType name="short"
xmlType="xs:long"
printMethod="javax.xml.bind.DatatypeConverter.printShort"
parseMethod="javax.xml.bind.DatatypeConverter.parseShort"/>



xjc complains with:
[ERROR] The prefix “jaxb” for element “jaxb:globalBindings” is not
bound.

SOLUTION
========

Missing namespace declaration. There should be something like this:
xmlns:jaxb=”URI”
Just look for the other namespace definitions (i.e. xmlns:s) and
add the above attribute to the end.

Source : http://www.velocityreviews.com/forums/t137983-problem-in-xjc-with-recognizing-jaxb-prefix.html

xsd:date maps to java.util.Calendar

My schema has an element of type xs:date, which jaxb maps to a java.util.Calendar. If I create a Calendar object with Calendar.getInstance(), it marshalls to “2003-11-24-05:00”.

How can I get it to marshall to just “2003-11-24”?

SOLUTION:
Write a converter class (see MyConverter below) and added an annotation/appinfo to the xml schema, also shown below.

public class MyConverter
{
static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
static public String printCalendar(Calendar c)
{
return df.format(c.getTime());
}

static public Calendar parseCalendar(String c) throws ParseException
{
Date d = df.parse(c);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
return cal;
}
}




<jaxb:globalBindings
<jaxb:javaType name="java.util.Calendar" xmlType="xsd:date"
printMethod="MyConverter.printCalendar"
parseMethod="MyConverter.parseCalendar"
/>



...

Source : https://forums.oracle.com/forums/thread.jspa?threadID=1624090

Building Java Web Services with NetBeans 7.0

Create web services using Netbeans 7.0

Here is a complete tutorial with screenshots and very well explained.

http://www.theserverside.com/tip/Building-Java-Web-services-with-NetBeans-7

How to create a sample Web Service using JDeveloper

Thanks to Hussain for creating this tutorial. I am just extending his learning with some additions of mine.

The Sample WebService will return Credit Rating of the customer if the customer Id is Valid else it will give response as Invalid Customer Id

1) Open JDeveloper, Create New Application and Project as shown below

2) Create a Java Class, Right Click on Project->New->General->JavaClass

3) Enter Class Name as CreditRating and Package name as com.ws

4) Write a Method called getCreditRating inside the class CreditRating class.
the method should accept customer id and return a CreditRating of the customer.

package com.ws;
import java.io.Serializable;

public class CreditRating implements Serializable
{
public CreditRating()
{
}
/**
* Do read this link for help
* in case of issues : http://programming.itags.org/development-tools/123309/
* @webmethod
*/
public String getCreditRating(String customerId)
{
String rating;
if("abc".equalsIgnoreCase(customerId) ||
"xyz".equalsIgnoreCase(customerId) )
{
rating="1000";
}
else if("pqr".equalsIgnoreCase(customerId))
{
rating="2000";
}
else
{
rating = "Invalid Customer id";
}
return rating;
}
}

5) Compile your Project, After Successful Compilation, Right Click your Project->Business Tier-> Web Services-> Java Web Service

6)Enter WebService Name and Select the CreditRating Class as Component to Publish and click Next

7) Once You Successfully generate the Java Web Service, You need to deploy it and Test the working of the Web Service
8) Right Click on MyWebService1 and Select Run. You’ll see a URL in the Log window as shown below.