Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-RS: returning concrete class instance from method with declared abstract return type

I have some REST service using JAX-RS and Jackson. My customer wants to have abstract class as service's return type and I have no clue how to make JAX-RS client return instances of concrete sub-classes. Is this possible for both XML and JSON representation? If so, will appreciate samples and/or links.

like image 250
Aleksandr Kravets Avatar asked Dec 23 '13 17:12

Aleksandr Kravets


2 Answers

You can try to add JsonTypeInfo and JsonSubTypes annotations

@JsonTypeInfo(use = Id.CLASS,
              include = JsonTypeInfo.As.PROPERTY,
              property = "type")
@JsonSubTypes({
    @Type(value = MySubClass.class)
    })
public abstract class MyAbsClass {
....
}
public class MySubClass extends MyAbsClass {
....
}

It should add the type info to json output.

like image 157
Garry Avatar answered Oct 30 '22 23:10

Garry


There are several ways to achieve this. The simplest way is to use @JsonTypeInfo, as Garry mentioned. All you have to do is annotate your abstract base class with a @JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY) and you should be good to go.

Another way is to make sure all mappers on both the server-side and the client-side have (likely NON_FINAL) default typing enabled so type information is (de)serialized on unannotated classes. Both ways can be enhanced by providing your own TypeResolverBuilder if you're unsatisfied with out-of-the-box serialization capabilities. More detailed explanations of these approaches can be found in this article or on Jackson's Polymorphic Type Handling wiki page.

Although the @JsonTypeInfo way is simple, getting a CXF server/client actually working can be a chore. So here's a full example:

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.fasterxml.jackson.jaxrs.xml.JacksonJaxbXMLProvider;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.MediaType.APPLICATION_XML;

public class FullCxfJaxrsJacksonExample {
    public static void main(String[] args) {
        String serverAddress = "http://localhost:9000/";
        Server server = null;

        try {
            // make server that supports JSON and XML
            JAXRSServerFactoryBean serverFactory = new JAXRSServerFactoryBean();
            serverFactory.setResourceClasses(ShapeServiceRandom.class);
            serverFactory.setAddress(serverAddress);
            serverFactory.setProviders(Arrays.asList(new JacksonJaxbJsonProvider(), new JacksonJaxbXMLProvider()));
            server = serverFactory.create();

            // make and use a client
            JAXRSClientFactoryBean clientFactory = new JAXRSClientFactoryBean();
            clientFactory.setAddress(serverAddress);
            clientFactory.setServiceClass(ShapeService.class);
            clientFactory.setProvider(new JacksonJaxbJsonProvider());
            clientFactory.setHeaders(Collections.singletonMap("Accept", "application/json"));
            // for an XML client instead of a JSON client, use the following provider/headers instead:
            //clientFactory.setProvider(new JacksonJaxbXMLProvider());
            //clientFactory.setHeaders(Collections.singletonMap("Accept", "application/xml"));

            ShapeService shapeServiceClient = clientFactory.create(ShapeService.class);
            for (int i = 0; i < 10; i++) {
                System.out.format("created shape: %s\n", shapeServiceClient.create());
            }

        } finally {
            if (server != null) {
                server.destroy();
            }
        }
        System.exit(0);
    }

    // Put JsonTypeInfo on the abstract base class so class info gets marshalled.
    // You'll want CLASS instead of MINIMAL_CLASS if your base class and subclasses are in different packages.
    @JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY)
    public abstract static class Shape {
    }

    public static class Circle extends Shape {
        public double radius;

        @Override
        public String toString() {
            return "Circle{radius=" + radius + '}';
        }
    }

    public static class Polygon extends Shape {
        public int numSides;

        @Override
        public String toString() {
            return "Polygon{numSides=" + numSides + '}';
        }
    }

    // service definition with abstract return type
    @Path("/shape")
    public interface ShapeService {
        @GET
        @Path("/create")
        @Produces({APPLICATION_JSON, APPLICATION_XML})
        Shape create();
    }

    // service implementation that returns different concrete subclasses
    public static class ShapeServiceRandom implements ShapeService {
        Random random = new Random();

        public Shape create() {
            int num = random.nextInt(8);
            if (num > 3) {
                Polygon polygon = new Polygon();
                polygon.numSides = num;
                return polygon;
            } else {
                Circle circle = new Circle();
                circle.radius = num + 0.5;
                return circle;
            }
        }
    }
}

This example was successfully tested using JDK 1.8.0_45 and the following dependencies:

    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>2.5.4</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-xml-provider</artifactId>
        <version>2.5.4</version>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-transports-http-jetty</artifactId>
        <version>3.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-rs-client</artifactId>
        <version>3.1.1</version>
    </dependency>
like image 41
heenenee Avatar answered Oct 30 '22 23:10

heenenee