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.sap.prd.mobile.ios.mios.VersionInfoXmlManager.java

private void createVersionInfoFile(final String groupId, final String artifactId, final String version,
        Properties versionInfo, List<Dependency> dependencies, OutputStream os)
        throws MojoExecutionException, JAXBException {
    try {/*from w  ww . j a  va2s  . c  om*/

        final Versions versions = new Versions();

        for (final Dependency dep : dependencies)
            versions.addDependency(dep);

        final SCM scm = new SCM();
        scm.setConnection(SCMUtil.getConnectionString(versionInfo, false));
        scm.setRevision(SCMUtil.getRevision(versionInfo));

        final Coordinates coordinates = new Coordinates();
        coordinates.setGroupId(groupId);
        coordinates.setArtifactId(artifactId);
        coordinates.setVersion(version);

        versions.setScm(scm);
        versions.setCoordinates(coordinates);

        final JAXBContext context = JAXBContext.newInstance(Versions.class);

        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
                "urn:xml.sap.com:XCodePlugin:VersionInfo" + " " + NEXUS_URL + "/content/repositories/"
                        + SCHEMA_REPOSITORY + "/" + SCHEMA_GROUP_ID.replace(".", "/") + "/" + SCHEMA_ARTIFACT_ID
                        + "/" + SCHEMA_VERSION + "/" + SCHEMA_ARTIFACT_ID + "-" + SCHEMA_VERSION + ".xsd");

        final ByteArrayOutputStream byteOs = new ByteArrayOutputStream();

        marshaller.marshal(versions, byteOs);

        final byte[] b = byteOs.toByteArray();

        DomUtils.validateDocument(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(b)));

        IOUtils.write(b, os);
    } catch (ParserConfigurationException e) {
        throw new MojoExecutionException("Cannot create versions.xml.", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Cannot create versions.xml.", e);
    } catch (SAXException e) {
        throw new MojoExecutionException("Cannot create versions.xml.", e);
    }
}

From source file:com.prowidesoftware.swift.model.mx.BusinessHeader.java

/**
 * Get this header as an XML string./*from   w w  w.  j a  va  2 s  .c  om*/
 * Since this class contains a dual model supporting two type of headers (swift and ISO), if both
 * headers are present in the object the BusinessApplicationHeaderV01 will be used.
 * 
 * @param prefix optional prefix for namespace (empty by default)
 * @param includeXMLDeclaration true to include the XML declaration (false by default)
 * @return header serialized into XML string or null if neither header version is present
 * @since 7.8
 */
public String xml(final String prefix, boolean includeXMLDeclaration) {
    Object header = null;
    if (this.businessApplicationHeader != null) {
        header = this.businessApplicationHeader;
    } else if (this.applicationHeader != null) {
        header = this.applicationHeader;
    } else {
        return null;
    }
    try {
        JAXBContext context = JAXBContext.newInstance(header.getClass());
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        final StringWriter sw = new StringWriter();
        marshaller.marshal(_element(header), new XmlEventWriter(sw, prefix, includeXMLDeclaration, "AppHdr"));
        return sw.getBuffer().toString();

    } catch (JAXBException e) {
        log.log(Level.SEVERE, "Error writing XML:" + e + "\n for header: " + header);
    }
    return null;
}

From source file:com.prowidesoftware.swift.model.mx.AbstractMX.java

public Element element() {
    final HashMap<String, String> properties = new HashMap<String, String>();
    // it didn't work as expected
    // properties.put(JAXBRIContext.DEFAULT_NAMESPACE_REMAP, namespace);
    try {/*w ww . j a v a 2  s  .  c o  m*/
        JAXBContext context = JAXBContext.newInstance(getClasses(), properties);

        DOMResult res = new DOMResult();
        context.createMarshaller().marshal(this, res);
        Document doc = (Document) res.getNode();

        return (Element) doc.getFirstChild();
    } catch (Exception e) {
        log.log(Level.WARNING, "Error creating XML Document for MX", e);
        return null;
    }
}

From source file:com.prowidesoftware.swift.model.mx.BusinessHeader.java

/**
 * Gets the header as an Element object.
 *  /* w  w w . j av a 2  s .  c o  m*/
 * @return Element this header parsed into Element or null if header is null
 * @since 7.8
 */
public Element element() {
    Object header = null;
    if (this.businessApplicationHeader != null) {
        header = this.businessApplicationHeader;
    } else if (this.applicationHeader != null) {
        header = this.applicationHeader;
    } else {
        return null;
    }
    try {
        JAXBContext context = JAXBContext.newInstance(header.getClass());
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        DOMResult res = new DOMResult();
        marshaller.marshal(_element(header), res);
        Document doc = (Document) res.getNode();
        return (Element) doc.getFirstChild();

    } catch (JAXBException e) {
        log.log(Level.SEVERE, "Error writing XML:" + e + "\n for header: " + header);
    }
    return null;
}

From source file:eu.learnpad.core.impl.or.XwikiBridgeInterfaceRestResource.java

@Override
public void updateSimulationScore(String modelSetId, String simulationSessionId, String processArtifactId,
        Long timestamp, String userId, SimulationScoresMap scoreMap) throws LpRestException {
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/or/bridge/%s/simulationscore", DefaultRestResource.REST_URI,
            modelSetId);//from w w  w  . j  a  v  a2  s  . c o m
    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML);
    String contentType = "application/xml";

    NameValuePair[] queryString = new NameValuePair[4];
    queryString[0] = new NameValuePair("simulationsessionid", simulationSessionId);
    queryString[1] = new NameValuePair("processartifactid", processArtifactId);
    queryString[2] = new NameValuePair("timestamp", timestamp.toString());
    queryString[3] = new NameValuePair("userid", userId);
    postMethod.setQueryString(queryString);

    try {
        Writer scoreMapWriter = new StringWriter();
        JAXBContext jc = JAXBContext.newInstance(SimulationScoresMap.class);
        jc.createMarshaller().marshal(scoreMap, scoreMapWriter);

        RequestEntity requestEntity = new StringRequestEntity(scoreMapWriter.toString(), contentType, "UTF-8");
        postMethod.setRequestEntity(requestEntity);

        httpClient.executeMethod(postMethod);
    } catch (IOException | JAXBException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

From source file:de.unisaarland.swan.export.ExportUtil.java

/**
 * Writes the object Document into the file.
 *
 * @param o/*w ww . ja  va 2s  . c om*/
 * @param file
 */
private void marshalXMLToSingleFile(Object o, File file) {

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(o.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(o, file);
        return;
    } catch (JAXBException ex) {
        Logger.getLogger(ExportUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    throw new RuntimeException("ExportUtil: Something went wrong while marshalling the XML");
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileT.java

/**
 * The default constructor for XAdESProfileT.
 * //from   www.j a  va2s.  c o m
 */
public XAdESProfileT() {
    super();
    Init.init();

    try {
        JAXBContext context = JAXBContext.newInstance(eu.europa.ec.markt.jaxb.xades141.ObjectFactory.class);
        marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        unmarshaller = context.createUnmarshaller();
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    }

}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.smartdeployment.QUELLE.QuelleService.java

@POST
@Path("/submitCloudDescription")
@Consumes(MediaType.APPLICATION_XML)//  ww  w  . j  av  a  2s . c  o m
public boolean submitCloudProviderDescription(CloudProvider provider,
        @DefaultValue("true") @QueryParam("overwrite") boolean overwrite) {
    File saveAs = new File(SalsaConfiguration.getCloudProviderDescriptionDir() + File.separator
            + provider.getName() + cloudDescriptionFileExtension);
    if (saveAs.exists() && overwrite == false) {
        EngineLogger.logger.debug("Do not overwrite file : " + saveAs);
        return false;
    }
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(CloudProvider.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(provider, saveAs);
    } catch (JAXBException e) {
        EngineLogger.logger.debug("Fail to pass the cloud description !");
        e.printStackTrace();
    }
    EngineLogger.logger.debug("Saved/Updated cloud description in : " + saveAs);
    return true;
}

From source file:alter.vitro.vgw.service.query.wrappers.ResponseAggrMsg.java

public String toString() {
    String retStr = "";
    try {//from w  w w  .  java2  s .co m
        javax.xml.bind.JAXBContext jaxbContext = javax.xml.bind.JAXBContext
                .newInstance("alter.vitro.vgw.service.query.xmlmessages.response");
        ObjectFactory theFactory = new ObjectFactory();
        javax.xml.bind.Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        JAXBElement<QueryResponseType> myAggrResponseMsgEl = theFactory.createQueryResponse(response);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        marshaller.marshal(myAggrResponseMsgEl, baos);
        //            marshaller.marshal(myAggrResponseMsgEl, new java.io.FileOutputStream("ResponseTest.xml"));
        retStr = baos.toString(HTTP.UTF_8);

    } catch (javax.xml.bind.JAXBException je) {
        je.printStackTrace();
    } catch (UnsupportedEncodingException e2) {
        e2.printStackTrace();
    }
    return retStr;
}

From source file:ch.algotrader.service.ib.IBFixAllocationServiceImpl.java

private String marshal(final GroupMap groups) {

    try {//from w  ww  . ja  v  a  2s. c  o m
        JAXBContext context = JAXBContext.newInstance(GroupMap.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        StringWriter writer = new StringWriter();
        m.marshal(groups, writer);

        return writer.toString();
    } catch (JAXBException ex) {
        throw new ExternalServiceException(ex);
    }
}