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:eu.eco2clouds.scheduler.bonfire.BFClientSchedulerImpl.java

private Compute changeStateCompute(String userId, Compute compute, String state) {
    this.userId = userId;
    Boolean exception = false;//from w w  w .ja v  a2  s . c  o m
    String computeURL = url + compute.getHref();

    Compute computeMessage = new Compute();
    computeMessage.setHref(compute.getHref());
    computeMessage.setState(state);
    computeMessage.setLinks(compute.getLinks());

    String payload = "";

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Compute.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        marshaller.marshal(computeMessage, out);
        payload = out.toString();

    } catch (JAXBException e) {
        logger.warn("Error trying to parse returned status of hosts: " + computeURL + " Exception: "
                + e.getMessage());
        exception = true;
    }

    String response = putMethod(computeURL, payload, exception);
    logger.debug(response);

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Compute.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        compute = (Compute) jaxbUnmarshaller.unmarshal(new StringReader(response));
    } catch (JAXBException e) {
        logger.warn("Error trying to parse returned status of hosts: " + computeURL + " Exception: "
                + e.getMessage());
        exception = true;
    }

    if (exception)
        return new Compute();
    return compute;
}

From source file:com.healthcit.cacure.web.controller.ModuleImportExportController.java

@RequestMapping(method = RequestMethod.GET)
public void exportModule(@RequestParam(value = "moduleId", required = true) long id,
        @RequestParam(value = "format", required = true) String format, HttpServletResponse response) {

    try {//ww  w .j a  v  a2  s.co m
        response.setContentType("text/xml");

        OutputStream oStream = response.getOutputStream();
        Cure cureXml = dataExporter.constructModuleXML(id);
        JAXBContext jc = JAXBContext.newInstance("com.healthcit.cacure.export.model");
        if (ExportFormat.XML.name().equals(format)) {
            String fileNameHeader = String.format("attachment; filename=form-%d.xml;", id);

            response.setHeader("Content-Disposition", fileNameHeader);
            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.marshal(cureXml, oStream);
        } else if (ExportFormat.EXCEL.name().equals(format)) {
            String fileNameHeader = String.format("attachment; filename=form-%d.xlxml;", id);

            response.setHeader("Content-Disposition", fileNameHeader);
            response.setContentType("application/xml");
            StreamSource xslSource = new StreamSource(this.getClass().getClassLoader()
                    .getResourceAsStream(AppConfig.getString(Constants.EXPORT_EXCEL_XSLT_FILE)));
            JAXBSource xmlSource = new JAXBSource(jc, cureXml);
            Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource);
            transformer.transform(xmlSource, new StreamResult(oStream));
        }
        oStream.flush();
    } catch (IOException e) {
        log.error("Unable to obtain output stream from the response");
        log.error(e.getMessage(), e);
    } catch (JAXBException e) {
        log.error("Unable to marshal the object");
        log.error(e.getMessage(), e);
    } catch (TransformerException e) {
        log.error("XSLT transformation failed");
        log.error(e.getMessage(), e);
    }
}

From source file:net.ageto.gyrex.impex.persistence.cassandra.storage.CassandraRepositoryImpl.java

/**
 * Persist process configuration./* ww w . ja  v a2  s.  co  m*/
 * 
 * @param process
 */
public void insertOrUpdateProcess(IProcessConfig process) {

    JAXBContext context;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {
        context = JAXBContext.newInstance(ProcessConfig.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        // process / process step configuration xml formatted
        m.marshal(process, outputStream);

    } catch (JAXBException e) {
        throw new IllegalArgumentException(e.getMessage());
    }

    Mutator<String> mutator = HFactory.createMutator(getImpexKeyspace(), StringSerializer.get());
    // insert process configuration
    mutator.insert(process.getId(), columnFamilyProcesses,
            HFactory.createStringColumn(columnNameProcess, outputStream.toString()));
}

From source file:edu.usc.goffish.gopher.impl.client.DeploymentTool.java

public void setup(String gofsConfig, String managerHost, String coordinatorHost, boolean persist)
        throws IOException, ConfigurationException {

    int numberOfProcessors = 0;

    PropertiesConfiguration gofs = new PropertiesConfiguration(gofsConfig);
    gofs.load();/*w  w w  .j a  v  a2  s  . c  o  m*/
    String nameNodeRestAPI = gofs.getString(GoFSFormat.GOFS_NAMENODE_LOCATION_KEY);

    INameNode nameNode = new RemoteNameNode(URI.create(nameNodeRestAPI));
    numberOfProcessors = nameNode.getDataNodes().size();

    // generate flow graph.
    FloeGraphGenerator generator = new FloeGraphGenerator();
    OMElement xmlOm = generator.createFloe(numberOfProcessors);
    xmlOm.build();
    try {
        JAXBContext ctx = JAXBContext.newInstance(FloeGraph.class);
        Unmarshaller um = ctx.createUnmarshaller();
        FloeGraph floe = (FloeGraph) um.unmarshal(xmlOm.getXMLStreamReader());

        if (persist) {
            FileOutputStream fileOutputStream = new FileOutputStream(new File(FLOE_GRAPH_PATH));
            ctx.createMarshaller().marshal(floe, fileOutputStream);
        }
        DefaultClientConfig config = new DefaultClientConfig();
        config.getProperties().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true);
        config.getFeatures().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true);

        Client c = Client.create(config);
        WebResource r = c
                .resource("http://" + coordinatorHost + ":" + COORDINATOR_PORT + "/Coordinator/createFloe");
        c.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
        ClientResponse response;
        c.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
        response = r.post(ClientResponse.class, floe);
        StartFloeInfo startFloeInfo = response.getEntity(StartFloeInfo.class);

        createClientConfig(startFloeInfo, managerHost, coordinatorHost);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:de.avanux.smartapplianceenabler.semp.webservice.SempController.java

private String marshall(Device2EM device2EM) {
    StringWriter writer = new StringWriter();
    try {/*  w ww  . j  a  v a2  s . c  o  m*/
        JAXBContext context = JAXBContext.newInstance(Device2EM.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(device2EM, writer);
        return writer.toString();
    } catch (JAXBException e) {
        logger.error("Error marshalling", e);
    }
    return null;
}

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

private void invokeSimulationTaskNotification(String restOperationName, String modelSetId, String modelId,
        String artifactId, String simulationId, SimulationData data) throws LpRestException {
    // <host>/learnpad/or/bridge/{modelsetid}/{modelid}/{restOperationName}?artifactid=aid,simulationid=id
    String contentType = "application/xml";

    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/or/bridge/%s/%s/%s", DefaultRestResource.REST_URI, modelSetId,
            modelId, restOperationName);
    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader("Content-Type", contentType);

    NameValuePair[] queryString = new NameValuePair[2];
    queryString[0] = new NameValuePair("artifactid", artifactId);
    queryString[1] = new NameValuePair("simulationid", simulationId);
    postMethod.setQueryString(queryString);

    try {/*from   w ww. ja  v a2 s . c o  m*/
        Writer simDataWriter = new StringWriter();
        JAXBContext jc = JAXBContext.newInstance(SimulationData.class);
        jc.createMarshaller().marshal(data, simDataWriter);

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

        httpClient.executeMethod(postMethod);

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

From source file:eu.learnpad.cw.CWXwikiBridge.java

License:asdf

@Override
public void notifyRecommendations(String modelSetId, String simulationid, String userId, Recommendations rec)
        throws LpRestException {
    Writer recWriter = new StringWriter();
    JAXBContext jc;
    try {//from w ww. j a  va 2s .  com
        jc = JAXBContext.newInstance(Recommendations.class);
        jc.createMarshaller().marshal(rec, recWriter);
    } catch (JAXBException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }

    String msg = "modelSetId : " + modelSetId + "\n" + "simulationid : " + simulationid + "\n" + "userId : "
            + userId + "\n" + "recommendations : " + rec.toString();

    logger.info(msg);

    CWXwikiBridge.recsStore.put(userId, simulationid, rec);
}

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

@Override
public void simulationInstanceNotification(String modelSetId, String modelId, String action,
        String simulationId, SimulationData data) throws LpRestException {
    // <host>/learnpad/or/bridge/{modelsetid}/{modelid}/simulationinstancenotification?action={started|stopped},simulationid=id
    String contentType = "application/xml";

    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/or/bridge/%s/%s/simulationinstancenotification",
            DefaultRestResource.REST_URI, modelSetId, modelId);
    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader("Content-Type", contentType);

    NameValuePair[] queryString = new NameValuePair[2];
    queryString[0] = new NameValuePair("action", action);
    queryString[1] = new NameValuePair("simulationid", simulationId);
    postMethod.setQueryString(queryString);

    try {//from  w  ww.  j  a  va 2  s  .  c o  m
        Writer simDataWriter = new StringWriter();
        JAXBContext jc = JAXBContext.newInstance(SimulationData.class);
        jc.createMarshaller().marshal(data, simDataWriter);

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

        httpClient.executeMethod(postMethod);

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

From source file:com.uttesh.pdfngreport.handler.PdfReportHandler.java

/**
 * This method generate the XML data file required by the apache fo to
 * generate the PDF report. XML data file is generated by using the java
 * JAXB./*w  ww . j a v a  2s.  co m*/
 *
 * @param reportData
 * @return UUID which is used as the file name.
 *
 * {@link com.uttesh.pdfngreport.util.xml.ReportData#member ReportData}
 * @see JAXBException
 */
public int generateXmlData(ReportData reportData) {
    JAXBContext jc;
    int fileName = UUID.randomUUID().toString().substring(0, 3).hashCode();
    File file = null;
    try {
        jc = JAXBContext.newInstance(ReportData.class);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        if (reportData.getOsName().equalsIgnoreCase("w")) {
            file = new File(reportLocation + Constants.BACKWARD_SLASH + fileName + Constants.XML_EXTENSION);
        } else {
            file = new File(reportLocation + Constants.FORWARD_SLASH + fileName + Constants.XML_EXTENSION);
        }
        marshaller.marshal(reportData, file);
    } catch (JAXBException ex) {
        Logger.getLogger(PdfReportHandler.class.getName()).log(Level.SEVERE, null, ex);
        //new File(reportLocation + Constants.FORWARD_SLASH + fileName + Constants.XML_EXTENSION).delete();
    }
    return fileName;
}

From source file:com.sap.prd.mobile.ios.mios.VersionInfoManager.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 www  . j a v  a2 s . c  om*/

        final String connectionString = "scm:perforce:" + versionInfo.getProperty("port") + ":"
                + getDepotPath(versionInfo.getProperty("depotpath"));

        final Versions versions = new Versions();

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

        final SCM scm = new SCM();
        scm.setConnection(connectionString);
        scm.setRevision(versionInfo.getProperty("changelist"));

        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);
    }
}