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.openthinks.webscheduler.service.WebSecurityService.java

/**
 * save changes to disk file//from   www.j  av  a2s.com
 */
public void saveToDisk() {
    Checker.require(this.securityConfig).notNull();
    Checker.require(this.webSecurity).notNull();
    File file = this.securityConfig.getConfigFile();
    try {
        FileOutputStream fos = new FileOutputStream(file);
        JAXBContext jaxbContext = JAXBContext.newInstance(WebSecurity.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(this.webSecurity, fos);
        fos.close();
        this.webSecurity.moveToSaved();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:de.tudarmstadt.ukp.integration.alignment.xml.AlignmentXmlWriter.java

public AlignmentXmlWriter(OutputStream out) throws IOException {

    try {/*from w  w  w .  java  2 s .co  m*/
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        xmlEventWriter = xmlOutputFactory.createXMLEventWriter(out);

        JAXBContext context = JAXBContext.newInstance(XmlMeta.class, Alignments.class); //Source.class

        marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); // no document level events
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        xmlef = XMLEventFactory.newInstance();
        xmlEventWriter.add(xmlef.createStartDocument());
        xmlEventWriter.add(xmlef.createStartElement("", "", RESOURCE_ALIGNMENT));

    } catch (XMLStreamException e) {
        throw new IOException(e);
    } catch (JAXBException e) {
        throw new IOException(e);
    }

}

From source file:org.openmrs.module.dhisreport.api.dxf2.DataValueSetTest.java

@Test
public void marshallDataValueSet() throws Exception {
    DataValueSet dvset = new DataValueSet();
    dvset.setDataSet("ANC");
    dvset.setOrgUnit("OU1");
    dvset.setPeriod("2012-09");
    List<DataValue> dataValues = dvset.getDataValues();
    dataValues.add(new DataValue("DE1", "45"));
    dataValues.add(new DataValue("DE2", "45"));
    dataValues.add(new DataValue("DE3", "r543efdgty2", "53"));

    Writer xmlWriter = new StringWriter();
    JAXBContext jaxbContext = JAXBContext.newInstance(DataValueSet.class);

    Marshaller jaxbmarshaller = jaxbContext.createMarshaller();
    jaxbmarshaller.marshal(dvset, xmlWriter);
    String xml = xmlWriter.toString();

    //System.out.println( xml );
    assertEquals("3", xpathTest("count(//d:dataValue)", xml));
    assertEquals("53", xpathTest("//d:dataValue[3]/@value", xml));
    assertEquals("r543efdgty2", xpathTest("//d:dataValue[3]/@categoryOptionCombo", xml));

}

From source file:com.redhat.akashche.wixgen.dir.DirectoryGeneratorTest.java

@Test
public void test() throws Exception {
    // emulate externally provided conf file
    String json = GSON.toJson(ImmutableMap.builder().put("appName", "Test Wix Application")
            .put("versionMajor", "0").put("versionMinor", "1").put("versionPatch", "0")
            .put("vendor", "Test Vendor")
            .put("licenseFilePath", "src/test/resources/com/redhat/akashche/wixgen/dir/LICENSE.rtf")
            .put("iconPath", "src/test/resources/com/redhat/akashche/wixgen/dir/test_icon.ico")
            .put("topBannerBmpPath", "src/test/resources/com/redhat/akashche/wixgen/dir/top_banner.bmp")
            .put("greetingsBannerBmpPath",
                    "src/test/resources/com/redhat/akashche/wixgen/dir/greetings_banner.bmp")
            .put("registryKeys", ImmutableList.builder().add(ImmutableMap.builder().put("root", "HKCU")
                    .put("key", "Software\\Test Wix Application")
                    .put("values", ImmutableList.builder()
                            .add(ImmutableMap.builder().put("type", "string").put("name", "Application Name")
                                    .put("value", "Test Application").build())
                            .add(ImmutableMap.builder().put("type", "integer").put("name", "Version Minor")
                                    .put("value", "1").build())
                            .add(ImmutableMap.builder().put("type", "string").put("name", "Test Path")
                                    .put("value", "[INSTALLDIR]src\\test\\resources\\com").build())
                            .build())/*from   ww w. j av  a  2s.  c  o m*/
                    .build()).build())
            .put("environmentVariables", ImmutableList.builder()
                    .add(ImmutableMap.builder().put("name", "TEST_WIX_VAR").put("action", "create")
                            .put("value", "Test Wix Var Contents").build())
                    .add(ImmutableMap.builder().put("name", "PATH").put("action", "set")
                            .put("value", "[INSTALLDIR]src\\test\\resources\\com\\redhat").build())
                    .build())
            .build());
    WixConfig conf = GSON.fromJson(json, WixConfig.class);
    Wix wix = new DirectoryGenerator().createFromDir(new File("src"), conf);
    JAXBContext jaxb = JAXBContext.newInstance(Wix.class.getPackage().getName());
    Marshaller marshaller = jaxb.createMarshaller();
    marshaller.setProperty(JAXB_FORMATTED_OUTPUT, true);
    Writer writer = null;
    try {
        OutputStream os = new FileOutputStream("target/test.wxs");
        writer = new OutputStreamWriter(os, Charset.forName("UTF-8"));
        marshaller.marshal(wix, writer);
    } finally {
        closeQuietly(writer);
    }

    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
    try {
        OutputStream os = new FileOutputStream("target/components.xml");
        writer = new OutputStreamWriter(os, Charset.forName("UTF-8"));
        Directory dir = findWixDirectory(wix);
        marshaller.marshal(dir, writer);
    } finally {
        closeQuietly(writer);
    }

    try {
        OutputStream os = new FileOutputStream("target/feature.xml");
        writer = new OutputStreamWriter(os, Charset.forName("UTF-8"));
        Feature dir = findWixFeature(wix);
        marshaller.marshal(dir, writer);
    } finally {
        closeQuietly(writer);
    }
}

From source file:com.rapid.server.ActionCache.java

public ActionCache(ServletContext servletContext) throws JAXBException {

    // retain servletContext
    _servletContext = servletContext;/*from   w  w  w  .  j  a va2s.c o m*/

    // create the JAXB context and marshalers for this
    JAXBContext jaxb = JAXBContext.newInstance(Cache.class);
    _marshaller = jaxb.createMarshaller();
    _marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    _unmarshaller = jaxb.createUnmarshaller();

    // initialise the map of all application caches
    _applicationCaches = new HashMap<String, Cache>();

}

From source file:dk.dma.epd.common.prototype.communication.webservice.ShoreHttp.java

public void setXmlMarshalContent(String contextPath, Object obj)
        throws JAXBException, UnsupportedEncodingException {
    JAXBContext jc = JAXBContext.newInstance(contextPath);
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.setProperty(Marshaller.JAXB_ENCODING, ENCODING);
    StringWriter sw = new StringWriter();
    m.marshal(obj, sw);// w ww. java 2s.co  m
    String req = sw.toString();
    LOG.debug("XML request: " + req);
    setRequestBody(sw.toString().getBytes(ENCODING), ENCODING);
}

From source file:org.javelin.sws.ext.bind.SweJaxbContextFactoryTest.java

@Test
public void defaultPackage() throws Exception {
    JAXBContext ctx = SweJaxbContextFactory.createContext("", null);
    // but we may marshal objects of built-in classes - XSD simple types
    ctx.createMarshaller().marshal(
            new JAXBElement<String>(new QName("urn:test", "str"), String.class, "content"), System.out);
}

From source file:org.jvoicexml.callmanager.mmi.http.HttpETLProtocolAdapter.java

@Override
public void sendMMIEvent(Object channel, Mmi mmi) throws IOException {
    try {//from  www .  ja  va 2  s . com
        final URI source = server.getURI();
        final LifeCycleEvent event = mmi.getLifeCycleEvent();
        event.setSource(source.toString());
        final String target = event.getTarget();
        if (target == null) {
            LOGGER.error("unable to send MMI event '" + mmi + "'. No target.");
            return;
        }
        final JAXBContext ctx = JAXBContext.newInstance(Mmi.class);
        final Marshaller marshaller = ctx.createMarshaller();
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        marshaller.marshal(mmi, out);
        final URI uri = new URI(target);
        final HttpClient client = new DefaultHttpClient();
        final HttpPost post = new HttpPost(uri);
        final HttpEntity entity = new StringEntity(out.toString(), ContentType.APPLICATION_XML);
        post.setEntity(entity);
        client.execute(post);
        LOGGER.info("sending " + mmi + " to '" + uri + "'");
    } catch (JAXBException e) {
        throw new IOException(e.getMessage(), e);
    } catch (URISyntaxException e) {
        throw new IOException(e.getMessage(), e);
    }
}

From source file:eu.impress.impressplatform.IntegrationLayer.ResourcesMgmt.BedAvailabilityServiceBean.java

@Override
public String getBedAvailablityHAVE(String hospitalname) {

    String hospitalstatushave;/*from  ww  w.j a v a  2  s  . com*/
    BedStats bedStats = bedService.getHospitalAvailableBeds(hospitalname);
    HospitalStatus hospitalStatus = beansTransformation.BedStatstoHAVE(bedStats);

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(HospitalStatus.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        //jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        StringWriter sw = new StringWriter();
        //marshal the envelope 
        jaxbMarshaller.marshal(hospitalStatus, sw);
        hospitalstatushave = sw.toString();

    } catch (JAXBException e) {
        e.printStackTrace();
        return "Error Marshalling XML Object" + HttpStatus.INTERNAL_SERVER_ERROR;
    }

    return hospitalstatushave;

}

From source file:edu.isi.misd.scanner.network.worker.webapp.ResultsReleaseDelegate.java

private void writeRejectedServiceResponse(String id, String url, String siteName, String nodeName,
        String comments, File outputFile) throws Exception {
    // 1. Populate the rejected ServiceResponse
    ServiceResponse response = new ServiceResponse();
    ServiceResponseMetadata responseMetadata = new ServiceResponseMetadata();
    responseMetadata.setRequestID(id);/*from  ww  w .  j ava  2  s  .  co  m*/
    responseMetadata.setRequestURL(url);
    responseMetadata.setRequestState(ServiceRequestStateType.REJECTED);
    responseMetadata.setRequestStateDetail("Reason: " + (comments.isEmpty() ? "not specified." : comments));
    responseMetadata.setRequestSiteName(siteName);
    responseMetadata.setRequestNodeName(nodeName);
    response.setServiceResponseMetadata(responseMetadata);

    // 2. Write out the result response using JAXB
    JAXBContext jaxbContext = JAXBContext.newInstance(ServiceResponse.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
    jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    if (outputFile.exists()) {
        try {
            FileUtils.forceDelete(outputFile);
        } catch (Exception e) {
            log.warn("Could not delete output file: " + outputFile.getCanonicalPath());
            throw e;
        }
    }
    jaxbMarshaller.marshal(response, outputFile);
}