Search code examples
javaxmlrestxstream

how can I output a XML file to a REST web service in Java so another application can consume this XML?


I need to output an XML file from one application to another, but I'd like not to have to write this XML somewhere and then reading this file on the other application.

Both are Java applications and (so far!) I'm using XStream.

How can I do it?


Solution

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

    JAXB (JSR-222) is the default binding layer for The Java API for RESTful Web Services (JAX-RS). This means you can just create a service that returns POJOs and all the to/from XML conversion will be handled for you.

    Below is an example JAX-RS service that looks up an instance of Customer using JPA and returns it to XML. The JAX-RS implementation will leverage JAXB to do the actual conversion automatically.

    package org.example;
    
    import java.util.List;
    import javax.ejb.*;
    import javax.persistence.*;
    import javax.ws.rs.*;
    import javax.ws.rs.core.MediaType;
    
    @Stateless
    @LocalBean
    @Path("/customers")
    public class CustomerService {
    
        @PersistenceContext(unitName="CustomerService", 
                            type=PersistenceContextType.TRANSACTION)
        EntityManager entityManager;
    
        @GET
        @Produces(MediaType.APPLICATION_XML)
        @Path("{id}")
        public Customer read(@PathParam("id") long id) {
            return entityManager.find(Customer.class, id);
        }
    
    }
    

    Full Example