Showing posts with label jersey. Show all posts
Showing posts with label jersey. Show all posts

Wednesday, 16 November 2016

Getting started Jersey.

1. Project build and management configuration is described in the pom.xml located in the project root
directory.
REF : pom elements
2. Project sources are located under src/main/java.
3. Project resources are located under src/main/resources.
4. Project web application files are located under src/main/webapp.

5. To compile and package the application into a WAR, invoke the following maven command in your
console:

ex : mvn clean package

logs :

Packaging webapp
[INFO] Assembling webapp [simple-service-webapp] in [.../simple-service-webapp/target/[INFO] Processing war project
[INFO] Building war: .../simple-service-webapp/target/simple-service-webapp.war

Now you are ready to take the packaged WAR (located under ./target/simple-servicewebapp.
war) and deploy it to a Servlet container of your choice.

Jersey dependency maven :

1) jersey-server, jersey-json, jersey-multipart.

Spring dependency :

spring-core,context,context-support,web,aop.

spring security.

security-web,security-config,security-taglib,security-core,security-acl

spring+jersey

spring,core,web,beans,context,asm,aop.

jackson:

jackson-jaxrs-json-provider


apache commons :

utility for string manipulation

connection pool :

dbcp

Apache-commns :

Apache Commons Codec provides implementations of common encoders and decoders such as Base64, Hex, Phonetic and URLs.

Hibernate :

hibernate-core

spring-transaction:

REF : transaction   why we go for spring transaction

hibernate entity manager
table mapping

spring-orm



6. Root Resource Classes
Root resource classes are POJOs (Plain Old Java Objects) that are annotated with @Path

7. @Produces
annotation is used to specify the MIME media types of representations a resource can produce and send back to the
client.
Using multiple output MIME types
@Produces({"application/xml", "application/json"})


@Consumes
annotation is used to specify the MIME media types of representations that can be consumed by a resource.

@QueryParam
is used to extract query parameters from the Query component of the request URL.

@DefaultValue
annotation, will be assigned to the step method parameter. If the
"step" value cannot be parsed as a 32 bit signed integer then a HTTP 404
ex :
 public Response smooth(
4 @DefaultValue("2") @QueryParam("step") int step

@FormParam

it extracts information from a request representation that is of the MIME media type
"application/x-www-form-urlencoded"

@Context HttpHeaders headers,

@Singleton
annotation says that the resource
will be managed as singleton and not in request scope. The sub-resource locator method returns a class which means that the runtime will managed the resource instance and its life-cycle. If the method would return instance instead, the Singleton annotation would have no effect and the returned instance would be used.


Securiry -- done
Multipart  -- progress -- 8.3
Filters -- 9.0







Wednesday, 24 August 2016

@JsonIgnore

@JsonIgnore

If we want to serialize object to json, during this process some of the property can be null/empty can be ignored.
this can be achived using @jsonIgnore.

ex :
1. @JsonIgnore(Include.NON_NULL)
2. @JsonIgnore(Include.NON_EMPTY)
3. @JsonIgnore(Include.NON_DEFAULT)

Ref : wilddiary

com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException


com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
 at [Source: org.apache.catalina.connector.CoyoteInputStream@76ab2e75; line: 3, column: 25] (through reference chain: com.group.dto.EmployeeDto["orderDto"])

Solution :
1. Json mapping should be done, when list object is added as property.

ex : Customer {
private int id;
private int name;
// missing json mapping annotation
private List<OrderDto> orderDto;
}
OrderDto {
pivate int orderId;
private String orderName;

}
2. Changes add @JsonProperty("orderList")

Customer {
private int id;
private int name;
// missing json mapping annotation
private List<OrderDto> orderDto;
}

Sunday, 21 August 2016

The ResourceConfig instance does not contain any root resource classes

When created a  maven web project.
1. Make sure to delete all the jsp file. 
2. Refresh and build

Method 2 :
1. In eclipse right click go to properties
2. Go ro java build path
3. Order and export
4. Add "JRE and system library","Maven library". and click ok
5. Right click on project
5.1 Go to run.
5.2 maven install.

Thursday, 7 July 2016

spring jersey intigration

steps 1 :

in web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>Archetype Created Web Application</display-name>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>\WEB-INF\ApplicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
<servlet-name>jerseyService</servlet-name>
<servlet-class> com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.spi.spring.container.servlet.SpringServlet</param-name>
<param-value>com.jersey.api</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jerseyService</servlet-name>
<url-pattern>/v1/*</url-pattern>
</servlet-mapping>

</web-app>

step 2: application context in web-inf folder.
include namepace for spring module.
ref : http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/xsd-config.html

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
 
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd " >

<context:component-scan base-package="com.jersey.api" />

 
</beans>

step 3: configure pom with spring,spring-jersey depencdency

<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/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.myjersey</groupId>
  <artifactId>Onejersey</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Onejersey Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <properties>
  <jersey.spring>1.9</jersey.spring>
  </properties>
 




  <dependencies>


  <!-- spring  -->
 
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>4.1.4.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-beans</artifactId>
   <version>4.1.3.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>4.1.3.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>4.1.3.RELEASE</version>
</dependency>


 

  <!-- spring  -->


  <!-- jersey  -->
  <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.contribs</groupId>
   <artifactId>jersey-multipart</artifactId>
   <version>1.9</version>
</dependency>


  <!-- jersey -->
 
    <!-- spring-jersey  -->
  <dependency>
   <groupId>com.sun.jersey.contribs</groupId>
   <artifactId>jersey-spring</artifactId>
   <version>${jersey.spring}</version>
   <exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-asm</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</exclusion>
   
   </exclusions>
</dependency>

<!-- jackson -jaxrs  -->
<dependency>
   <groupId>com.fasterxml.jackson.jaxrs</groupId>
   <artifactId>jackson-jaxrs-json-provider</artifactId>
   <version>2.5.5</version>
</dependency>
<!-- jackson -jaxrs  -->


    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>Onejersey</finalName>
  </build>
</project>






step 4 : java application



/**
 *
 */
package com.jersey.api;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;

import org.springframework.stereotype.Service;

/**
 * @author voice
 *
 */
@Service
@Path("/hello")
public class Employee {

@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response helloWorld(){
ResponseBuilder rs = Response.status(Status.OK);
System.out.println("HI this is jagdeesh");
return rs.build();
}

}





ref :
spring-jersey
spring module

Monday, 27 June 2016

java.lang.IllegalStateException: LifecycleProcessor not initialized

java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: Root WebApplicationContext: startup date


check the configuration in
1. applicationcontext.xml
2.pom.xml

observation :
1. make sure to upgrade dependency to 4.0 release or 3.0 release.




Wednesday, 15 June 2016

Jersey java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

Jersey java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer


solution : In eclipse 
go to  project -> properties -> development assembly -> add -> java build path entries.

Monday, 6 June 2016

com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException

com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException

SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('"' (code 34)): was expecting comma to separate OBJECT entries

Ex :
error :
{
"name" : "voice"
"email" : "voice@gmail.com"

}
corrected :
{
"name" : "voice" ,
"email" : "voice@gmail.com"

}

Solution :  In the corrected solution put a comma.

Saturday, 21 May 2016

Difference between pathparam and QueryParam in Rest.

Difference between pathparam and QueryParam in Rest.

Pathparam : used get the part of the string from URL.
ex:  @Pathparam("id")
ex : http://localhost:8080/voice{id}

QueryParam  : using this we are able to access the key,value after from URL after "?"
ex:  @QueryParam("id")
ex : http://localhost:8080/voice?id=1009

Thursday, 7 April 2016


Jersey :
com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.

In the service class provide the root path. if root is not provide or we have not annoted class with @Path.

ex :

@Service
@Path("/test")     // provide the root path
public class voice {

@Path("/hello")
public class HelloWorldService {

@GET
@Path("/{param}")
public Response getMsg(@PathParam("param") String msg) {

String output = "Jersey say : " + msg;

return Response.status(200).entity(output).build();

}

}

}

Tuesday, 29 March 2016

File upload with  data  using angular js and jersey webservice

1. jersey service.

        @POST
@Path("/public")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void get(
                               @FormDataParam("file") byte[] fileInputStream,
            @FormDataParam("file") FormDataContentDisposition fileInputDetails,
            @FormDataParam("id")String userid){

System.out.println("THis is the ID "+userid);
System.out.println("File Details : "+ fileInputDetails.getFileName());

System.out.println("Reading the String data "+ fileInputStream.toString());

String s = new String(fileInputStream);
   System.out.println("Text Decryted : " + s);

}

2.  create the angular js service,directive,controller

Service.

service('myFileService',["$http",function($http){
console.log("service is called");

this.post = function(uploadUrl, data){

var fd = new FormData();   // bunch of  key,value

console.log("uploaded URL "+uploadUrl);
console.log("uploaded data "+data);

for(var key in data) {

console.log("key is : "+ key + " , value :  "+ data[key]);
fd.append(key, data[key]);
}

$http.post(uploadUrl, fd, {
transformRequest: angular.indentity,
headers: { 'Content-Type': undefined }
})
.success(function(){
console.log("from service success");
})
.error(function(){
console.log("from service failure");
})

}


}]);

Directive : to bind the file data

directive('fileModel', ['$parse', function($parse){
return {
restrict: 'A',
link : function(scope, element, attrs){

var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(changeEvent){
scope.$apply(function(){
                         modelSetter(scope, changeEvent.target.files[0]);
                });

});
}

};
}]);

Controller :

controller("postCTRL",['$scope','myFileService',function($scope,myFileService){
$scope.sample = {};
$scope.Submit = function(){
console.log($scope.sample.name);
var uploadedURL = "/public";
var data = $scope.sample;
myFileService.post(uploadedURL,data);
 
}
 }]);

3. HTML FORM

<form>


<p> Name : <input type="text" name="name" ng-model="sample.id" required /></p>
   
<input type="file" id="exampleInputFile" file-model="sample.file">  
   
<button ng-click="Submit()">Submit</button>

</form>
{{sample}}

</div>



Ref :
1. stackoverflow



Client API

JAX-RS Client API, which is a fluent Java based API for communication
with RESTful Web services. This standard API that is also part of Java EE 7 is designed to make it very easy to consume a Web service exposed via HTTP protocol and enables developers to concisely and efficiently implement portable client-side solutions that leverage existing and well established client-side HTTP connector implementations.

The goals of the client API are threefold:
1. Encapsulate a key constraint of the REST architectural style, namely the Uniform Interface Constraint
and associated data elements, as client-side Java artifacts;
2. Make it as easy to consume RESTful Web services exposed over HTTP, same as the JAX-RS serverside
API makes it easy to develop RESTful Web services; and
3. Share common concepts and extensibility points of the JAX-RS API between the server and the client
side programming models.

Friday, 18 March 2016


Jersey :
severe the runtimeexception could not be mapped to a response re-throwing to the http container

REF url : Stackoverflow