EzDevInfo.com

jersey interview questions

Top jersey frequently asked interview questions

JAX-RS / Jersey how to customize error handling?

I'm learning JAX-RS (aka, JSR-311) using Jersey. I've successfuly created a Root Resource and am playing around with parameters:

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

    @GET
    @Produces("text/html")
    public String get(
        @QueryParam("name") String name,
        @QueryParam("birthDate") Date birthDate) {

         // Return a greeting with the name and age
    }
}

This works great, and handles any format in the current locale which is understood by the Date(String) constructor (like YYYY/mm/dd and mm/dd/YYYY). But if I supply a value which is invalid or not understood, I get a 404 response.

For example:

GET /hello?name=Mark&birthDate=X

404 Not Found

How can I customize this behavior? Maybe a different response code (probably "400 Bad Request")? What about logging an error? Maybe add a description of the problem ("bad date format") in a custom header to aid troubleshooting? Or return a whole Error response with details, along with a 5xx status code?


Source: (StackOverflow)

Input and Output binary streams using JERSEY?

I'm using Jersey to implement a RESTful API that is primarily retrieve and serve JSON encoded data. But I have some situations where I need to accomplish the following:

  • Export downloadable documents, such as PDF, XLS, ZIP, or other binary files.
  • Retrieve multipart data, such some JSON plus an uploaded XLS file

I have a single-page JQuery-based web client that creates AJAX calls to this web service. At the moment, it doesn't do form submits, and uses GET and POST (with a JSON object). Should I utilize a form post to send data and an attached binary file, or can I create a multipart request with JSON plus binary file?

My application's service layer currently creates a ByteArrayOutputStream when it generates a PDF file. What is the best way to output this stream to the client via Jersey? I've created a MessageBodyWriter, but I don't know how to use it from a Jersey resource. Is that the right approach?

I've been looking through the samples included with Jersey, but haven't found anything yet that illustrates how to do either of these things. If it matters, I'm using Jersey with Jackson to do Object->JSON without the XML step and am not really utilizing JAX-RS.


Source: (StackOverflow)

Advertisements

The ResourceConfig instance does not contain any root resource classes

Whats going wrong here ?

The ResourceConfig instance does not contain any root resource classes. 
Dec 10, 2010 10:21:24 AM com.sun.jersey.spi.spring.container.servlet.SpringServlet initiate 
SEVERE: Exception occurred when intialization 
com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes. 
        at com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:103) 
        at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1182) 
        at com.sun.jersey.server.impl.application.WebApplicationImpl.access$600(WebApplicationImpl.java:161) 
        at com.sun.jersey.server.impl.application.WebApplicationImpl$12.f(WebApplicationImpl.java:698) 
        at com.sun.jersey.server.impl.application.WebApplicationImpl$12.f(WebApplicationImpl.java:695) 
        at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:197) 
        at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:695) 
        at com.sun.jersey.spi.spring.container.servlet.SpringServlet.initiate(SpringServlet.java:117) 

Filter:

<filter>

    <filter-name>JerseyFilter</filter-name>
    <filter-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</filter-class>

    <init-param>
        <param-name>com.sun.jersey.config.feature.Redirect</param-name>
        <param-value>true</param-value>
    </init-param>

    <init-param>
        <param-name>com.sun.jersey.config.property.JSPTemplatesBasePath</param-name>
        <param-value>/views/</param-value>
    </init-param>

    <init-param>
        <param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
        <param-value>/(images|css|jsp)/.*</param-value>
    </init-param>

</filter>

<filter-mapping>
    <filter-name>JerseyFilter</filter-name>
    <url-pattern>/myresource/*</url-pattern>
</filter-mapping> 

Code:

@Path ("/admin") 
public class AdminUiResource { 

  @GET 
  @Produces ("text/html") 
  @Path ("/singup") 
  public Viewable getSignUp () { 
    return new Viewable("/public/signup", "Test"); 
  } 

}

Source: (StackOverflow)

Practical advice on using Jersey and Guice for RESTful service

From what I can find online, the state of the art for Guice + Jersey integration has stagnated since 2008 when it appears both teams reached an impasse. The crux of the issue is that JAX-RS annotations perform field and method injection and this doesn't play nicely with Guice's own dependency injection.

A few examples which I've found don't go far enough to elucidate:

  • Iqbalyusuf's post on Jersey + Guice on Google App Engine Java suffers from a lot of boilerplate (manually getting and calling the injector). I want binding and injection should happen behind the scenes via Guice annotations.

  • Jonathan Curran's article Creating a RESTful service with Jersey, Guice, and JSR-250 gave me hope because it's much more current (2010), but went no further than showing how to start up a Jersey service inside of a Guice ServletModule. However, there are no examples of doing any real dependency injection. I suppose that was left as an exercise for the reader. Curran's post may in fact be the correct first step towards wiring up Guice and Jersey and so I plan on starting with that.

  • tantalizingly James Strachan writes:

    JAX-RS works well with dependency injection frameworks such as Spring, Guice, GuiceyFruit or JBossMC - you can basically pick whichever one you prefer.

    But I see no evidence that is true from a practitioner's point of view.

What I find lacking are practical examples and explanations on how to combine JAX-RS and Guice annotations. For instance:

  • I believe I cannot use constructor injection with any resource as Jersey wants to control this
  • I'm uncertain whether I can combine @Inject with @PathParam, @QueryParam, et al.
  • How to use injection in a MessageBodyWriter implementation

Does anyone have examples, preferably with source, of non-trivial application which combines Jersey and Guice without sacrificing one or the other in the process? I'm keeping on this road regardless, but the bits and pieces on the Jersey and Guice lists makes me think I'm repeating the work of others who came before me.


Source: (StackOverflow)

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

I am trying to build a simple hello world application for two days using Jersey + Google app engine. For simple AppEngine project I followed these tutorials and both works just fine https://developers.google.com/appengine/docs/java/gettingstarted/creating https://developers.google.com/appengine/docs/java/webtoolsplatform

But now I am trying to add Jersey and following this tutorial http://www.vogella.com/articles/REST/article.html.

But server keeps giving me

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

when I add these lines in web.xml:

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>TestServer</display-name>
<servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.test.myproject</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>

I have downloaded Jersey JAX-RS 2.1 RI bundle from here and have added all jar files in WEB-INF/lib folder as described in tutorial. And even after two days nothing is working. I have searched several times on Google and apparently people who are using Maven have solved it somehow but I am not using Maven neither did the guy who wrote that tutorial.

Just to check if even com.sun.jersey.spi.container.servlet.ServletContainer exists in imported Jersey jars I tried to just write this fully qualified name in Java and let the intellisense finish names but I couldn't get any intellisense after com.sun.je so my last guess is that there have been some package rearrangement in latest Jersey build and jersey is no longer inside com.sun. I am exhausted and I would appreciate any kind of help.


Source: (StackOverflow)

How do I use the Jersey JSON POJO support?

I have an object that I'd like to serve in JSON as a RESTful resource. I have Jersey's JSON POJO support turned on like so (in web.xml):

<servlet>  
    <servlet-name>Jersey Web Application</servlet-name>  
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>  
</servlet>  

But when I try to access the resource, I get this exception:

SEVERE: A message body writer for Java type, class com.example.MyDto, and MIME media type, application/json, was not found
SEVERE: Mapped exception to response: 500 (Internal Server Error)
javax.ws.rs.WebApplicationException
...

The class that I'm trying to serve isn't complicated, all it's got are some public final fields and a constructor that sets all of them. The fields are all strings, primitives, classes similar to this one, or Lists thereof (I've tried using plain Lists instead of generic List<T>s, to no avail). Does anyone know what gives? Thanks!

Java EE 6

Jersey 1.1.5

GlassFish 3.0.1


Source: (StackOverflow)

JAX-RS (Jersey) custom exception with XML or JSON

I have a REST service built using Jersey.

I want to be able to set the MIME of my custom exception writers depending on the MIME that was sent to the server. application/json is returned when json is received, and application/xml when xml is received.

Now I hard code application/json, but that's making the XML clients left in the dark.

public class MyCustomException extends WebApplicationException {
     public MyCustomException(Status status, String message, String reason, int errorCode) {
         super(Response.status(status).
           entity(new ErrorResponseConverter(message, reason, errorCode)).
           type("application/json").build());
     }
}

What context can I tap into to get the current requests Content-Type?

Thanks!


Update based on answer

For anyone else interested in the complete solution:

public class MyCustomException extends RuntimeException {

    private String reason;
    private Status status;
    private int errorCode;

    public MyCustomException(String message, String reason, Status status, int errorCode) {
        super(message);
        this.reason = reason;
        this.status = status;
        this.errorCode = errorCode;
    }

    //Getters and setters
}

Together with an ExceptionMapper

@Provider
public class MyCustomExceptionMapper implements ExceptionMapper<MyCustomException> {

    @Context
    private HttpHeaders headers;

    public Response toResponse(MyCustomException e) {
        return Response.status(e.getStatus()).
                entity(new ErrorResponseConverter(e.getMessage(), e.getReason(), e.getErrorCode())).
                type(headers.getMediaType()).
                build();
    }
}

Where ErrorResponseConverter is a custom JAXB POJO


Source: (StackOverflow)

Using the Jersey client to do a POST operation

In a Java method, I'd like to use a Jersey client object to do a POST operation on a RESTful web service (also written using Jersey) but am not sure how to use the client to send the values that will be used as FormParam's on the server. I'm able to send query params just fine.

Thanks in advance.


Source: (StackOverflow)

What is the difference between @PathParam and @QueryParam

I am newbie in RESTful jersey. I would like to ask what is the different between @PathParam and @QueryParam in jersey?


Source: (StackOverflow)

How can I grab all query parameters in Jersey JaxRS?

I am building a generic web service and need to grab all the query parameters into one string for later parsing. How can I do this?


Source: (StackOverflow)

Dependency injection with Jersey 2.0

Starting from scratch without any previous Jersey 1.x knowledge, I'm having a hard time understanding how to setup dependency injection in my Jersey 2.0 project.

I also understand that HK2 is available in Jersey 2.0, but I cannot seem to find docs that help with Jersey 2.0 integration.

@ManagedBean
@Path("myresource")
public class MyResource {

    @Inject
    MyService myService;

    /**
     * Method handling HTTP GET requests. The returned object will be sent
     * to the client as "text/plain" media type.
     *
     * @return String that will be returned as a text/plain response.
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/getit")
    public String getIt() {
        return "Got it {" + myService + "}";
    }
}

@Resource
@ManagedBean
public class MyService {
    void serviceCall() {
        System.out.print("Service calls");
    }
}

pom.xml

<properties>
    <jersey.version>2.0-rc1</jersey.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey</groupId>
            <artifactId>jersey-bom</artifactId>
            <version>${jersey.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-common</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey</groupId>
        <artifactId>jax-rs-ri</artifactId>
    </dependency>
</dependencies>

I can get the container to start and serve up my resource, but as soon as I add @Inject to MyService, the framework throws an exception:

SEVERE: Servlet.service() for servlet [com.noip.MyApplication] in context with path [/jaxrs] threw exception [A MultiException has 3 exceptions.  They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=MyService,parent=MyResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,1039471128)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.noip.MyResource errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on com.noip.MyResource
] with root cause
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=MyService,parent=MyResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,1039471128)
    at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)


My starter project is available at GitHub: https://github.com/donaldjarmstrong/jaxrs


Source: (StackOverflow)

Example of using StreamingOutput as Response entity in Jersey

Can someone post an example of how in Jersey to set StreamingOutput as an entity in a Response object?

I haven't been able to find an example of this.


Source: (StackOverflow)

jersey security and session management

Is there a way to get session management or security programatically in Jersey, e.g. web-application session management? Or are transactions, sessions, and security all handled by the container in which the Jersey application is deployed?


Source: (StackOverflow)

User authentication on a Jersey REST service

I am developing a REST application, which is using the Jersey framework. I would like to know how I can control user authentication. I have searched many places, and the closest article I have found is this: http://weblogs.java.net/blog/2008/03/07/authentication-jersey.

However this article can only be used with a GlassFish server and an attached database. Is there anyway that I can implement an interface in Jersey and use it as a filter before reaching the requested REST resource?

I want to use basic authentication right now, but it should be flexible enough such that I can change that at a later time.


Source: (StackOverflow)

RESTEasy or Jersey? [closed]

I have a requirement for RESTFul webservices. It is up to my team to decide whether to go with Jersey or Restlet or RESTEasy or anything else. after omitting other frameworks, we are not able to choose between RESTEasy and Jersey.

Since both of them seem to be almost the same, what should we consider?

The client API should be simple and rich. We are already using JBoss 5.1 in production.

Please let me know the pros and cons of Jersey and RESTEasy. Except that it is from JBoss, I'm not able to find any valid point over Jersey.


Source: (StackOverflow)