EzDevInfo.com

jersey

This is an active mirror of Jersey 2.x workspace from <a href="http://jersey.java.net">http://jersey.java.net</a>. Any changes made here are automatically propagated to java.net and vice versa. Forks and pull requests are welcome! Jersey

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)

Advertisements

Why use JAX-RS / Jersey?

Sorry, this questions sounds silly, but after developing some of my RESTful services using Jersey, I asked myself the question -- If REST is just an architecture, and not a protocol like SOAP, why do we need a specification like JAX-RS?

I actually googled for questions like "What is the difference between servlets and RESTful services over HTTP" and to sum up the community answers, I got:

  1. RESTful service development (on Jersey) is an architecture, which inherently uses servlets.
  2. JAX-RS compliant tools like Jersey provide easy marshalling-unmarshalling of XML/JSON data, helping the developers.
  3. REST helps us use GET/POST/PUT/DELETE in a fashion that is far efficient than normal servlets.

According to these answers, I guess if I write a servlet which uses JAXB (for dealing with automatic serialization), and I efficiently use GET/POST/PUT/DELETE in my servlet code, I don't use a tool like Jersey, and hence JAX-RS.

I know I am terribly wrong passing this statement, please correct me.

PS: This doubt actually came in when I had to develop some RESTful services in PHP. After going on through some of the RESTful PHP codes, I realized they are just the same old PHP scripts, with some helper methods for handling XML/JSON.


Source: (StackOverflow)

Howto automate documentation of a REST API (Jersey Implementation) [closed]

I have written a pretty extensive REST API using Java Jersey (and JAXB). I have also written the documentation using a Wiki, but its been a totally manual process, which is very error-prone, especially when we need to make modifications, people tend to forget to update the wiki.

From looking around, most other REST API's are also manually creating their documentation. But I'm wondering if theres maybe a good solution to this.

The kind of things which need to be documented for each endpoint are:

  • Service Name
  • Category
  • URI
  • Parameter
  • Parameter Types
  • Response Types
  • Response Type Schema (XSD)
  • Sample requests and responses
  • Request type (Get/Put/Post/Delete)
  • Description
  • Error codes which may be returned

And then of course there are some general things which are global such as

  • Security
  • Overview of REST
  • Error handling
  • Etc

These general things are fine to describe once and don't need to be automated, but for the web service methods themselves it seems highly desirable to automate it.

I've thought of maybe using annotations, and writing a small program which generates XML, and then an XSLT which should generate the actual documentation in HTML. Does it make more sense to use custom XDoclet?

Any help would be much appreciated, Alan


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)

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)

Session management : How to generate Authentication token for REST service ? (Jersey)

I am trying to implement session management in my REST service. I came to know these guidelines while surfing :

  1. Not using server side sessions - it violates the RESTful principle.

  2. Using HTTP Basic authentication - Not possible right now, as I am asked not to use SSL/TLS (which is no doubt needed for Basic auth.)

  3. Using Http digest - I heard this increases network traffic. This sounds costly, especially when my client is a mobile device.

  4. Using cookies - I am told I should never rely on cookie for securing my important resources, they can be spoofed easily. Plus, I read about cross-site scripting attacks through cookies.

  5. I am left with an option of generating authentication token ,which the user has to send everytime - which I admit is not "entirely" RESTful.

Now I need to know, how should I generate these unique authentication tokens, which are secure enough at a business level ? Is there some library for Jersey ? Should I go for OAuth..I have just read a little about them, are they useful in my case ? Please keep in mind that my target clients are mobile devices - can they access an OAuth service ??


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)

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)

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)

How does one intercept a request during the Jersey lifecycle?

I've used Jersey for the better part of a year now and have just stumbled upon a problem to which I can't find the answer: how do you intercept (or hook into) the Jersey request lifecycle?

Ideally, I'd be able to perform some custom filtering/validation/rejection between the time the container accepts the request from the network and the time my handler methods are called. Bonus points if there's an easy way to filter the interceptors by sub-path (e.g. have one interceptor for anything under /, another for anything under /user/, etc.).

Thanks!

Edit: To be a bit clearer, the general idea here is to be able to write some code that will be run for many API calls without having to explicitly call that code from each handler method. This would reduce extra code and eliminate the need to pass request contexts around.


Source: (StackOverflow)

How can I customize serialization of a list of JAXB objects to JSON?

I'm using Jersey to create a REST web service for a server component.

The JAXB-annotated object I want to serialize in a list looks like this:

@XmlRootElement(name = "distribution")
@XmlType(name = "tDistribution", propOrder = {
    "id", "name"
})
public class XMLDistribution {
    private String id;
    private String name;
    // no-args constructor, getters, setters, etc
}

I have a REST resource to retrieve one distribution which looks like this:

@Path("/distribution/{id: [1-9][0-9]*}")
public class RESTDistribution {
    @GET
    @Produces("application/json")
    public XMLDistribution retrieve(@PathParam("id") String id) {
        return retrieveDistribution(Long.parseLong(id));
    }
    // business logic (retrieveDistribution(long))
}

I also have a REST resource to retrieve a list of all distributions, which looks like this:

@Path("/distributions")
public class RESTDistributions {
    @GET
    @Produces("application/json")
    public List<XMLDistribution> retrieveAll() {
        return retrieveDistributions();
    }
    // business logic (retrieveDistributions())
}

I use a ContextResolver to customize JAXB serialization, which is currently configured like this:

@Provider
@Produces("application/json")
public class JAXBJSONContextResolver implements ContextResolver<JAXBContext> {
    private JAXBContext context;
    public JAXBJSONContextResolver() throws Exception {
        JSONConfiguration.MappedBuilder b = JSONConfiguration.mapped();
        b.nonStrings("id");
        b.rootUnwrapping(true);
        b.arrays("distribution");
        context = new JSONJAXBContext(b.build(), XMLDistribution.class);
    }
    @Override
    public JAXBContext getContext(Class<?> objectType) {
        return context;
    }
}

Both REST resources work, as well as the context resolver. This is an example of output for the first one:

// path: /distribution/1
{"id":1,"name":"Example Distribution"}

Which is exactly what I want. This is an example of output for the list:

// path: /distributions
{"distribution":[{"id":1,"name":"Sample Distribution 1"},{"id":2,"name":"Sample Distribution 2"}]}

Which is not quite what I want.

I don't understand why there is an enclosing distribution tag there. I wanted to remove it with .rootUnwrapping(true) in the context resolver, but apparently that only removes another enclosing tag. This is the output with .rootUnwrapping(false):

// path: /distribution/1
{"distribution":{"id":1,"name":"Example Distribution"}} // not ok
// path: /distributions
{"xMLDistributions":{"distribution":[{"id":1,"name":"Sample Distribution 1"},{"id":2,"name":"Sample Distribution 2"}]}}

I also had to configure .arrays("distribution") to always get a JSON array, even with only one element.

Ideally, I'd like to have this as an output:

// path: /distribution/1
{"id":1,"name":"Example Distribution"} // currently works
// path: /distributions
[{"id":1,"name":"Sample Distribution 1"},{"id":2,"name":"Sample Distribution 2"}]

I tried to return a List<XMLDistribution>, a XMLDistributionList (wrapper around a list), a XMLDistribution[], but I couldn't find a way to get a simple JSON array of distributions in my required format.

I also tried the other notations returned by JSONConfiguration.natural(), JSONConfiguration.mappedJettison(), etc, and couldn't get anything resembling what I need.

Does anyone know if it is possible to configure JAXB to do this?


Source: (StackOverflow)

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)

Java REST implementation: Jersey vs CXF [closed]

What do you think is the advantages/disadvantages between this two libraries? Which of these two are best suited for production environment? By the way I will be using JSON instead of XML.

I also would like to know what library is most supported by the community e.g. tutorials, documentation.


Source: (StackOverflow)

Troubles with WADL / generated XSD using Jersey with a contract-first approach

I have been working on a REST web service using Jersey for a few days now, and managed to have all CRUD operations working, with several exchange formats: XML, JSON, Google Protobuf.

However I am facing some issues related to automatically generated WADL and XSD.


Context

To define the objects exchanged in these three formats, I have followed a "contract-first" approach:

  • from a XSD I wrote, I generated my model classes using JAXB;
  • from an equivalent proto file I wrote, I generated the Google Protobuf classes (and internally have a way to convert these to the JAXB-generated objects, in order to have one unique model).

However, as I would like my users to be able to generate their classes too, I would like to share these schema files (.xsd and .proto) and have them well integrated with the automatically generated WADL.

For that purpose, thanks to this wiki page:

  • I have exposed the two files under
    • /schema/schema.xsd
    • /schema/schema.proto
  • I have added an application-grammar file:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <grammars xmlns="http://wadl.dev.java.net/2009/02" 
              xmlns:xsd="http://www.w3.org/2001/XMLSchema"
              xmlns:xi="http://www.w3.org/1999/XML/xinclude">
        <include rel='nofollow' href="../schema/schema.xsd" />
    </grammars>
    
  • I have added a customized WADL generator:

     public class RichWadlGeneratorConfig extends WadlGeneratorConfig {
        @Override
        public List<WadlGeneratorDescription> configure() {
            return generator(WadlGeneratorApplicationDoc.class)
                .prop("applicationDocsStream", "application-doc.xml")
                .generator(WadlGeneratorGrammarsSupport.class)
                .prop("grammarsStream", "application-grammars.xml")
                .descriptions();
        }
     }
    

This way the below appears in the WADL, when I hit /rest/application.wadl:

<grammars>
     <include rel='nofollow' href="../schema/schema.xsd"/>
     <include rel='nofollow' href="application.wadl/xsd0.xsd">
          <doc title="Generated" xml:lang="en"/>
     </include>
</grammars>

Problem

/rest/application.wadl/xsd0.xsd is automatically generated from my classes, but is quite different from what I initially had in schema.xsd. In addition to that, calling a tool like wadl2java on this WADL fails miserably, presumably because

  • /schema/schema.xsd, and
  • /rest/application.wadl/xsd0.xsd

are now conflicting (two definitions for the same objects).


Questions

  1. Is there a way to disable the generation and diffusion of this automatically generated XSD? (As I don't need it since I'm following this "contract-first" approach)

  2. If not, is there a way to "override" its content with my manually written XSD when /rest/application.wadl/xsd0.xsd is hit? (I have googled around and found about WadlResource, to generate customized WADL, but found nothing about the XSD generation itself)


Thanks in advance for your help!

M.


Edit

1) I raised the issue to the Jersey team and got a reply: http://java.net/projects/jersey/lists/users/archive/2012-06/message/8

2) I raised a ticket (JERSEY-1230), according to Pavel's instructions. I am currently following up to either submit a fix myself or get a fix from the Jersey team.


Source: (StackOverflow)