JAX WS RS using Jersey - returning Collection, Map etc
Asked Answered
C

5

14

I'm using Jersey 2.3

My WS endpoint class :

@Path("/employees")
public class EmployeeWSEndpoint {

    @Context
    Request request;

    @GET
    @Path("/allEmployees")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Employee> getAllEmployees() {

        System.out.println("In EmployeeWSEndpoint.getAllEmployees()");

        EmployeeService employeeService = new EmployeeServiceImpl();
        return employeeService.getAllEmployees();
    }

    @GET
    @Path("/allDept")
    @Produces(MediaType.APPLICATION_JSON)
    public List<String> getAllDept() {

        System.out.println("In EmployeeWSEndpoint.getAllDept()");

        List<String> deptNames = new ArrayList<>();
        deptNames.add("CoE");
        deptNames.add("iLabs");

        return deptNames;
    }

    @GET
    @Path("/allDeptPOJO")
    @Produces(MediaType.APPLICATION_JSON)
    public TempPOJO getAllDeptPOJO() {

        System.out.println("In EmployeeWSEndpoint.getAllDeptPOJO");

        TempPOJO tempPOJO = new TempPOJO();

        return tempPOJO;
    }
}

Employee POJO :

public class Employee {

    private int id;
    private String firstName;
    private String middleName;
    private String lastName;
    private Date dob;
    private int deptId;

    public Employee() {

    }

    public Employee(String firstName, String middleName, String lastName,
            Date dob, int deptId) {
        this.firstName = firstName;
        this.middleName = middleName;
        this.lastName = lastName;
        this.dob = dob;
        this.deptId = deptId;
    }

    public Employee(int id, String firstName, String middleName,
            String lastName, Date dob, int deptId) {
        this.id = id;
        this.firstName = firstName;
        this.middleName = middleName;
        this.lastName = lastName;
        this.dob = dob;
        this.deptId = deptId;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getMiddleName() {
        return middleName;
    }

    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    public int getDeptId() {
        return deptId;
    }

    public void setDeptId(int deptId) {
        this.deptId = deptId;
    }

    @Override
    public String toString() {
        return firstName + " " + middleName + " " + " " + lastName;
    }
}

A temporary POJO :

public class TempPOJO {

    private List<String> deptNames;

    public List<String> getDeptNames() {

        deptNames = new ArrayList<>();
        deptNames.add("CoE");
        deptNames.add("iLabs");

        return deptNames;
    }

    public void setDeptNames(List<String> deptNames) {
        this.deptNames = deptNames;
    }

}

Listing the output(s) for different methods :

allEmployees

[{"deptId":1,"dob":"1978-06-19","firstName":"Garfield","id":0,"lastName":"Arbuckle","middleName":"John"},{"deptId":1,"dob":"1946-07-07","firstName":"John","id":0,"lastName":"Rambo","middleName":"R"}]

/allDept

In EmployeeWSEndpoint.getAllDept()
Oct 01, 2013 3:31:08 PM org.glassfish.jersey.server.ServerRuntime$Responder mapException
WARNING: WebApplicationException cause:
javax.xml.bind.MarshalException
 - with linked exception:
[Exception [EclipseLink-25003] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: An error occurred marshalling the object
Internal Exception: Exception [EclipseLink-25007] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor for class java.lang.String was not found in the project.  For JAXB, if the JAXBContext was bootstrapped using TypeMappingInfo[] you must call a marshal method that accepts TypeMappingInfo as an input parameter.]
    at org.eclipse.persistence.jaxb.JAXBMarshaller.marshal(JAXBMarshaller.java:403)
    at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.writeTo(MOXyJsonProvider.java:808)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:243)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:230)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:149)
    at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:103)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:149)
    at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:88)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:149)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1139)
    at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:562)
    at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:357)
    at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:347)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:258)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:318)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:235)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:983)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:359)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: Exception [EclipseLink-25003] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: An error occurred marshalling the object
Internal Exception: Exception [EclipseLink-25007] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor for class java.lang.String was not found in the project.  For JAXB, if the JAXBContext was bootstrapped using TypeMappingInfo[] you must call a marshal method that accepts TypeMappingInfo as an input parameter.
    at org.eclipse.persistence.exceptions.XMLMarshalException.marshalException(XMLMarshalException.java:97)
    at org.eclipse.persistence.internal.oxm.XMLMarshaller.marshal(XMLMarshaller.java:911)
    at org.eclipse.persistence.internal.oxm.XMLMarshaller.marshal(XMLMarshaller.java:848)
    at org.eclipse.persistence.jaxb.JAXBMarshaller.marshal(JAXBMarshaller.java:401)
    ... 41 more
Caused by: Exception [EclipseLink-25007] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor for class java.lang.String was not found in the project.  For JAXB, if the JAXBContext was bootstrapped using TypeMappingInfo[] you must call a marshal method that accepts TypeMappingInfo as an input parameter.
    at org.eclipse.persistence.exceptions.XMLMarshalException.descriptorNotFoundInProject(XMLMarshalException.java:139)
    at org.eclipse.persistence.internal.oxm.Context$ContextState.getSession(Context.java:143)
    at org.eclipse.persistence.oxm.XMLContext$XMLContextState.getSession(XMLContext.java:787)
    at org.eclipse.persistence.oxm.XMLContext$XMLContextState.getSession(XMLContext.java:1)
    at org.eclipse.persistence.internal.oxm.Context.getSession(Context.java:451)
    at org.eclipse.persistence.oxm.XMLContext.getSession(XMLContext.java:356)
    at org.eclipse.persistence.oxm.XMLContext.getSession(XMLContext.java:1)
    at org.eclipse.persistence.internal.oxm.XMLMarshaller.marshal(XMLMarshaller.java:568)
    at org.eclipse.persistence.internal.oxm.XMLMarshaller.marshal(XMLMarshaller.java:1096)
    at org.eclipse.persistence.internal.oxm.XMLMarshaller.marshal(XMLMarshaller.java:869)
    ... 43 more

/allDeptPOJO

{"deptNames":["CoE","iLabs"]}

I have some queries :

  1. I guess since Jersey 2.3, annotation 'XmlRootElement' isn't necessary for POJOs - I haven't done it, yet, the calls work. Please confirm
  2. In case of a List of a pojo(Employee) or a pojo having a List, the response is proper but for List, Map etc. it fails(basically, for Java types) - why is this so? If it works for Employee, why doesn't it work for Java types? Is there a need to write an XmlAdapter?

Note : I want the response in JSON in most of the cases.

Modifying the web.xml to use Jackson :

<?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"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>Jersey</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.ws.jaxrs.jersey</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.disableMoxyJson.server</param-name>
            <param-value>true</param-value>
        </init-param>

        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.ws.jaxrs.jersey;org.codehaus.jackson.jaxrs</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 got the following exception :

In EmployeeWSEndpoint.getAllDept()
Nov 07, 2013 10:04:12 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Jersey REST Service] in context with path [/Jersey] threw exception [org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<java.lang.String>.] with root cause
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<java.lang.String>.
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:227)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:149)
    at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:103)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:149)
    at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:88)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:149)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1139)
    at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:562)
    at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:357)
    at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:347)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:258)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:318)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:235)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:983)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:359)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Craigcraighead answered 1/10, 2013 at 10:37 Comment(1)
This may help #35039794Androclinium
I
17

Jackson is the best solution for me at the moment.

To use Jackson as your JSON provider you need to add jersey-media-json-jackson module to your pom.xml file:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.7</version>
</dependency>

Note: Auto-discovery feature does not work.

Building client with Jackson JSON feature enabled:

final Client client = ClientBuilder.newBuilder()
                    .register(JacksonFeature.class)
                    .build();

Creating JAX-RS server application with Jackson JSON feature enabled:

final Application application = new ResourceConfig()
                              .packages("my.rest.package")
                              .register(JacksonFeature.class);

Also check official Jersey json-jackson example.

Idealistic answered 27/3, 2014 at 11:0 Comment(1)
I also needed jackson-module-jaxb-annotations-2.5.0Sheelah
A
7

Use a different JSON provider

I don't know why jersey startet to adopt MOXy as their default JSON provider, but it's obviously a bad idea.

The problems you (and me - and others) are experiencing are the result of MOXy beeing unable to map collections of simple Java types (like String) - that's just ridiculous imho. Other providers (like jackson) do not have this problem, so switching will definitely help.

Here is what I did:

  1. Tell Jersey not to use MOXy. Add this to your web.xml:

    <init-param>
        <param-name>jersey.config.disableMoxyJson.server</param-name>
        <param-value>true</param-value>
    </init-param>
    
  2. Add Jackson to your pom. Something like this will do:

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-jaxrs</artifactId>
        <version>1.9.12</version>
    </dependency>
    
  3. Tell jersey to scan the jackson jackson packages. It will find (and use) the json providers provided by jackson:

    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.example.your.package;org.codehaus.jackson.jaxrs</param-value>
    </init-param>
    
Anfractuous answered 6/11, 2013 at 1:25 Comment(4)
Have appended the changes and (new) exception to my original query. For using Jackson, in addition to your inputs, do I need to implement the steps mentioned here : jersey.java.net/documentation/latest/media.html#json.jacksonCraigcraighead
FYI Moxy by now (I tested version 2.6) is capable of handling collections.Tracay
This was not working for me. is weird that Jersey would have this major bug for that long.Radius
@PéterTörök, moxy does not handle collections of natives or built-ins like strings, maps, et al.Silica
F
6

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

The exception you are hitting is due to a bug in MOXy's MOXyJsonProvider. MOXyJsonProvider is an implementation of the JAX-RS interfaces MessageBodyReader/MessageBodyWriter. I have changed the isWriteable method to return false for List<String> to return false so that another provider can handle it.

I have also opened the following enhancement request to have this support added to MOXy:

Fulford answered 11/10, 2013 at 19:57 Comment(4)
Ok but how do how do I proceed?Craigcraighead
@KaliyugAntagonist Yes. See my answere above.Anfractuous
@Jim Have appended the changes and (new) exception to my original query. For using Jackson, in addition to your inputs, do I need to implement the steps mentioned here : jersey.java.net/documentation/latest/media.html#json.jacksonCraigcraighead
While this is indeed the "why", it doesn't provide a solution. Also, 4 years later and this is still an open Moxy issue...wow. The answer is to use Jackson. I don't quite understand why Jersey suggests Moxy when there are issues like this.Socio
A
2

You can use RestEasy as JAX-RS implementation

GlassFish4 uses Jersey/MOXy as implementation of the JAX-RS. They have problem with mapping collections of simple Java types (like String) to JSON - https://bugs.eclipse.org/bugs/show_bug.cgi?id=417723

WildFly and JBoss use RestEasy/Jackson as implementation of the JAX-RS and there is no problem with mapping.

You can use RestEasy instead of Jersey in any java application server, e.g. WildFly (JBoss), GlassFish or Tomcat,

just replace:

    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>

with:

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-servlet-initializer</artifactId>
        <version>3.0.7.Final</version>
        <scope>compile</scope>
    </dependency>        
    <dependency>
       <groupId>org.jboss.resteasy</groupId>
       <artifactId>resteasy-jaxrs</artifactId>
       <version>3.0.7.Final</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson-provider</artifactId>
        <version>3.0.7.Final</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxb-provider</artifactId>
        <version>3.0.7.Final</version>
        <scope>compile</scope>
    </dependency>

It's working for me.

Best regards from Lublin in Poland :)

Antioch answered 1/4, 2014 at 14:55 Comment(1)
T
0

I had the same problem returning a List<String> object. I wrapped it in a RestStringList class and that works. If we have more of these to do though, I may switch to Jackson.

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class RestStringList implements Serializable {
    private static final long serialVersionUID = 1L;

    private List<String> stringList = null;

    public RestStringList() {
        this.stringList = new ArrayList<String>();
    }

    public void setStringList(List<String> stringList) {
        this.stringList = new ArrayList<String>(stringList);
    }

    public List<String> getStringList() {
        return stringList;
    }

    public String toString() {
        return "{ strings=" + stringList + " }";
    }
}
Taco answered 5/2, 2016 at 22:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.