Package de.huepattl.playground.rest

Source Code of de.huepattl.playground.rest.XmlExamplesResource

package de.huepattl.playground.rest;

import java.io.File;
import java.io.StringWriter;
import java.util.Date;
import javax.ejb.Stateless;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.util.JAXBSource;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

/**
* <p>
* For more JAXB/XML based examples (such as using schmea validation,
* shcmea-generated classes etc.) please consult the dedicated JAXB playground.
*
* @author blazko
* @since 2014-07-18
*/
@Path("employee")
@Stateless
@Produces(MediaType.APPLICATION_XML)
public class XmlExamplesResource {

    private static final String EMPLOYEE_NAME = "Spot";

    @GET
    @Path("getJaxb")
    public EmployeeEntity getJaxb(@QueryParam("id") final long id) {
        EmployeeEntity newEmployee = new EmployeeEntity(id,
                EMPLOYEE_NAME, new Date());

        return newEmployee;
    }

    @GET
    @Path("getJaxbAndTransform")
    public String getJaxbAndTransform(@QueryParam("id") final long id) throws JAXBException, TransformerConfigurationException, TransformerException {

        // 1. Create bean
        EmployeeEntity employee = new EmployeeEntity(id,
                EMPLOYEE_NAME, new Date());

        // 2. Define trafo source using JAXB source from Employee bean.
        JAXBContext jaxbContext = JAXBContext.newInstance(EmployeeEntity.class);
        JAXBSource employeeSource = new JAXBSource(jaxbContext, employee);

        // 3. Define XSLT stylesheet.
        StreamSource xslt = new StreamSource(
                new File(getClass().getResource("/employee.xslt").getFile()));

        // 4. Define trafo destination.
        StringWriter stringWriter = new StringWriter();
        StreamResult streamResult = new StreamResult(stringWriter);

        // 5. Setup trafo and transform employee XML to different format.
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer(xslt);
        transformer.transform(employeeSource, streamResult);

        return stringWriter.toString();
    }

}
TOP

Related Classes of de.huepattl.playground.rest.XmlExamplesResource

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.