Example usage for javax.xml.bind JAXBContext createMarshaller

List of usage examples for javax.xml.bind JAXBContext createMarshaller

Introduction

In this page you can find the example usage for javax.xml.bind JAXBContext createMarshaller.

Prototype

public abstract Marshaller createMarshaller() throws JAXBException;

Source Link

Document

Create a Marshaller object that can be used to convert a java content tree into XML data.

Usage

From source file:com.comcast.cats.service.util.HttpClientUtil.java

public static synchronized byte[] getPayload(Object domain, boolean prettyPrint) {
    byte[] payload = null;

    String xml = null;/*from   ww w . java2s .  co m*/

    StringWriter writer = new StringWriter();

    try {
        JAXBContext context = JAXBContext.newInstance(domain.getClass());

        Marshaller marshaller = context.createMarshaller();

        if (prettyPrint) {
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        }

        marshaller.marshal(domain, writer);
        xml = writer.toString();
    } catch (JAXBException e) {
        logger.error("[ JAXBException   ] " + e.getMessage());
    }

    logger.trace("[ PAYLOAD  ] " + xml);

    if (null != xml) {
        payload = xml.getBytes();
    }

    return payload;
}

From source file:gov.nih.nci.coppa.services.client.ClientUtils.java

private static void printXml(Object obj) throws JAXBException {
    JAXBContext jaxbContext = MAP.get(obj.getClass().getPackage().getName());
    if (jaxbContext == null) {
        jaxbContext = JAXBContext.newInstance(obj.getClass().getPackage().getName());
        MAP.put(obj.getClass().getPackage().getName(), jaxbContext);
    }//from  w w  w . j a v  a  2s . com
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.marshal(obj, System.out);
}

From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static String marshal(Object obj, String rootElementName) {
    StringWriter sw = new StringWriter();
    try {/*from w ww.jav a  2 s  .com*/
        JAXBContext jaxbCtx = JAXBContext.newInstance(obj.getClass().getPackage().getName());
        Marshaller marshaller = jaxbCtx.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(new JAXBElement(new QName(rootElementName), obj.getClass(), obj), sw);
        sw.close();

    } catch (PropertyException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return sw.toString();
}

From source file:com.labs64.utils.swid.support.JAXBUtils.java

/**
 * Write XML entity to the given destination.
 * //from   ww  w . j a v  a 2  s  .c  om
 * @param entity
 *            XML entity
 * @param destination
 *            destination to write to. Supported destinations: {@link java.io.OutputStream}, {@link java.io.File},
 *            {@link java.io.Writer}
 * @param comment
 *            optional comment which will be added at the begining of the generated XML
 * @throws IllegalArgumentException
 * @throws SwidException
 * @param <T>
 *            JAXB entity
 */
public static <T> void writeObject(final T entity, final Object destination, final String comment) {
    try {
        JAXBContext jaxbContext;
        if (entity instanceof JAXBElement) {
            jaxbContext = JAXBContext.newInstance(((JAXBElement) entity).getValue().getClass());
        } else {
            jaxbContext = JAXBContext.newInstance(entity.getClass());
        }

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        if (StringUtils.isNotBlank(comment)) {
            marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", comment);
        }

        if (destination instanceof java.io.OutputStream) {
            marshaller.marshal(entity, (OutputStream) destination);
        } else if (destination instanceof java.io.File) {
            marshaller.marshal(entity, (java.io.File) destination);
        } else if (destination instanceof java.io.Writer) {
            marshaller.marshal(entity, (java.io.Writer) destination);
        } else {
            throw new IllegalArgumentException("Unsupported destination.");
        }
    } catch (final JAXBException e) {
        throw new SwidException("Cannot write object.", e);
    }
}

From source file:dk.statsbiblioteket.doms.licensemodule.integrationtest.LicenseModuleRestWSTester.java

@SuppressWarnings("all")
private static void testGetUserLicenseQuery() throws Exception {
    GetUserQueryInputDTO input = new GetUserQueryInputDTO();
    input.setPresentationType("images");
    input.setAttributes(createUserObjAttributeDTO());

    JAXBContext context = JAXBContext.newInstance(GetUserQueryInputDTO.class);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(input, outputStream);/* ww  w .  j  a v a 2  s .  c  om*/

    // serialize to XML
    String inputXML = outputStream.toString();
    System.out.println(inputXML);
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client
            .resource(UriBuilder.fromUri("http://localhost:8080/licensemodule/services/").build());

    // Call with XML
    String output = service.path("getUserLicenseQuery").type(MediaType.TEXT_XML).accept(MediaType.TEXT_XML)
            .entity(inputXML).post(String.class);

    System.out.println("query:" + output);
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java

private static String getMetaDataXMLAsString(final JAXBContext jaxbContext, final Object jaxbObject)
        throws JAXBException {

    // Create an unmarshaller
    final Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    // Marshal the JAXB object meta-data into XML and return the result
    final StringWriter stringWriter = new StringWriter();
    marshaller.marshal(jaxbObject, stringWriter);

    return stringWriter.toString();
}

From source file:de.thorstenberger.taskmodel.util.JAXBUtils.java

/**
 * Get JAXBMarshaller//from   w  ww .  ja  v  a  2s .  c o m
 *
 * @param context JAXBContext
 * @return Marshaller
 * @throws JAXBException
 */
public static Marshaller getJAXBMarshaller(JAXBContext context) throws JAXBException {
    Marshaller m = null;
    if (!ENABLE_MARSHALL_POOLING) {
        if (log.isDebugEnabled()) {
            log.debug("Marshaller created [no pooling]");
        }
        m = context.createMarshaller();
    } else {
        m = mpool.get(context);
        if (m == null) {
            if (log.isDebugEnabled()) {
                log.debug("Marshaller created [not in pool]");
            }
            m = context.createMarshaller();
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Marshaller obtained [from  pool]");
            }
        }
    }
    return m;
}

From source file:dk.statsbiblioteket.doms.licensemodule.integrationtest.LicenseModuleRestWSTester.java

@SuppressWarnings("all")
private static void testGetUsersGroups() throws Exception {

    GetUserGroupsInputDTO input = new GetUserGroupsInputDTO();
    input.setAttributes(createUserObjAttributeDTO());
    input.setLocale("da");
    JAXBContext context = JAXBContext.newInstance(GetUserGroupsInputDTO.class);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(input, outputStream);/*  w w w  .j  a va 2s  .  co m*/

    // serialize to XML
    String inputXML = outputStream.toString();
    System.out.println("input xml:\n" + inputXML);

    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client
            .resource(UriBuilder.fromUri("http://localhost:8080/licensemodule/services/").build());
    // Call with XML
    //GetUsersLicensesOutputDTO output = service.path("getUserLicenses").type(MediaType.TEXT_XML).accept(MediaType.TEXT_XML).entity(inputXML).post(GetUsersLicensesOutputDTO.class);

    // Call with @XmlRootElement
    GetUserGroupsOutputDTO output = service.path("getUserGroups").type(MediaType.TEXT_XML)
            .accept(MediaType.TEXT_XML).entity(input).post(GetUserGroupsOutputDTO.class);

    context = JAXBContext.newInstance(GetUserGroupsOutputDTO.class);
    outputStream = new ByteArrayOutputStream();
    m = context.createMarshaller();

    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(output, outputStream);

    // serialize to XML
    String outputXML = outputStream.toString();
    System.out.println(outputXML);

    System.out.println("output, groups:" + output.getGroups());
}

From source file:org.eclipse.winery.topologymodeler.addons.topologycompleter.helper.JAXBHelper.java

/**
 * Marshalls a JAXB object of the TOSCA model to an XML string.
 *
 * @param clazz/*from w w w.j  a va 2 s.c om*/
 *           the class of the object
 * @param obj
 *           the object to be marshalled
 *
 * @return
 */
public static String getXMLAsString(@SuppressWarnings("rawtypes") Class clazz, Object obj) {
    try {
        @SuppressWarnings("rawtypes")
        JAXBElement rootElement = Util.getJAXBElement(clazz, obj);
        JAXBContext context = JAXBContext.newInstance(TDefinitions.class);
        Marshaller m;

        m = context.createMarshaller();

        StringWriter w = new StringWriter();
        m.marshal(rootElement, w);
        String res = w.toString();

        return res;
    } catch (JAXBException e) {
        logger.error(e.getLocalizedMessage());
    }
    return null;
}

From source file:dk.statsbiblioteket.doms.licensemodule.integrationtest.LicenseModuleRestWSTester.java

@SuppressWarnings("all")
private static void testGetUsersLicenses() throws Exception {
    // GetUserLicensesOutputDTO getUserLicenses

    GetUsersLicensesInputDTO input = new GetUsersLicensesInputDTO();
    input.setAttributes(createUserObjAttributeDTO());
    input.setLocale("da");

    JAXBContext context = JAXBContext.newInstance(GetUsersLicensesInputDTO.class);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(input, outputStream);//from  www  . j  a  va 2s  .c  o  m

    // serialize to XML
    String inputXML = outputStream.toString();
    System.out.println("input xml:\n" + inputXML);

    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client
            .resource(UriBuilder.fromUri("http://localhost:8080/licensemodule/services/").build());
    // Call with XML
    //GetUsersLicensesOutputDTO output = service.path("getUserLicenses").type(MediaType.TEXT_XML).accept(MediaType.TEXT_XML).entity(inputXML).post(GetUsersLicensesOutputDTO.class);

    // Call with @XmlRootElement
    GetUsersLicensesOutputDTO output = service.path("getUserLicenses").type(MediaType.TEXT_XML)
            .accept(MediaType.TEXT_XML).entity(input).post(GetUsersLicensesOutputDTO.class);
    context = JAXBContext.newInstance(GetUsersLicensesOutputDTO.class);
    outputStream = new ByteArrayOutputStream();
    m = context.createMarshaller();

    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(output, outputStream);

    // serialize to XML
    String outputXML = outputStream.toString();
    System.out.println(outputXML);

    System.out.println("output, licensenames:" + output.getLicenses());
}