Example usage for javax.xml.bind Marshaller setProperty

List of usage examples for javax.xml.bind Marshaller setProperty

Introduction

In this page you can find the example usage for javax.xml.bind Marshaller setProperty.

Prototype

public void setProperty(String name, Object value) throws PropertyException;

Source Link

Document

Set the particular property in the underlying implementation of Marshaller .

Usage

From source file:com.quangphuong.crawler.util.XMLUtil.java

public <T> String marshallWithoutFile(T entityClass) {
    try {/*from w  w  w  . java2s.c  om*/
        JAXBContext cxt = JAXBContext.newInstance(entityClass.getClass());

        Marshaller marshaller = cxt.createMarshaller();
        marshaller.setProperty(marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(marshaller.JAXB_ENCODING, "UTF-8");
        StringWriter sw = new StringWriter();
        marshaller.marshal(entityClass, sw);
        return sw.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:ee.ria.xroad.confproxy.commandline.ConfProxyUtilGenerateAnchor.java

/**
 * Generates an achor xml file based on the provided proxy configuration
 * properties and writes it to the provided output stream.
 * @param conf configuration proxy properties instance
 * @param instanceIdentifier instance identifier of the resulting anchor
 * @param out the output stream for writing the generated xml
 * @throws Exception if xml generation fails
 *//*  w w w. j a va2  s  .  c om*/
private void generateAnchorXml(final ConfProxyProperties conf, final String instanceIdentifier,
        final OutputStream out) throws Exception {
    JAXBContext jaxbCtx = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbCtx.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    ObjectFactory factory = new ObjectFactory();
    ConfigurationSourceType sourceType = factory.createConfigurationSourceType();
    sourceType.setDownloadURL(conf.getConfigurationProxyURL() + "/" + OutputBuilder.SIGNED_DIRECTORY_NAME);
    for (byte[] cert : conf.getVerificationCerts()) {
        sourceType.getVerificationCert().add(cert);
    }
    ConfigurationAnchorType anchorType = factory.createConfigurationAnchorType();
    anchorType.setInstanceIdentifier(instanceIdentifier);
    GregorianCalendar gcal = new GregorianCalendar();
    gcal.setTimeZone(TimeZone.getTimeZone("UTC"));
    XMLGregorianCalendar xgcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal);
    anchorType.setGeneratedAt(xgcal);
    anchorType.getSource().add(sourceType);
    JAXBElement<ConfigurationAnchorType> root = factory.createConfigurationAnchor(anchorType);

    marshaller.marshal(root, out);
}

From source file:com.cognifide.aet.rest.XUnitServlet.java

private Marshaller prepareJaxbMarshaller() throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Testsuites.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
    return jaxbMarshaller;
}

From source file:cn.newtouch.util.utils.encode.JaxbBinder.java

/**
 * Marshaller, encoding(?Null).// w w  w .ja v a2 s .c  o  m
 */
public Marshaller createMarshaller(String encoding) {
    try {
        Marshaller marshaller = jaxbContext.createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        if (StringUtils.isNotBlank(encoding)) {
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
        }
        return marshaller;
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.sap.prd.mobile.ios.mios.xcodeprojreader.jaxb.JAXBPlistParser.java

private void marshallPlist(Plist plist, Writer projectFile) throws JAXBException {
    JAXBContext ctx = JAXBContext.newInstance(com.sap.prd.mobile.ios.mios.xcodeprojreader.jaxb.JAXBPlist.class);
    Marshaller marshaller = ctx.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    try {//  w ww  .j  a  v  a  2  s .  c o  m
        marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", xmlHeaders);
    } catch (PropertyException ex) {
        marshaller.setProperty("com.sun.xml.bind.xmlHeaders", xmlHeaders);
    }
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
    marshaller.marshal(plist, projectFile);
}

From source file:dk.dbc.rawrepo.oai.ResumptionTokenTest.java

@Test
public void testXmlExpiration() throws Exception {
    ObjectNode jsonOriginal = (ObjectNode) new ObjectMapper().readTree("{\"foo\":\"bar\"}");

    long now = Instant.now().getEpochSecond();
    ResumptionTokenType token = ResumptionToken.toToken(jsonOriginal, 0);

    OAIPMH oaipmh = OBJECT_FACTORY.createOAIPMH();
    ListRecordsType getRecord = OBJECT_FACTORY.createListRecordsType();
    oaipmh.setListRecords(getRecord);/*from   w  ww  .  ja  v a2 s. c om*/
    getRecord.setResumptionToken(token);
    JAXBContext context = JAXBContext.newInstance(OAIPMH.class);
    StringWriter writer = new StringWriter();
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(oaipmh, writer);
    String xml = writer.getBuffer().toString();
    System.out.println("XML is:\n" + xml);
    int start = xml.indexOf("expirationDate=\"") + "expirationDate=\"".length();
    int end = xml.indexOf("\"", start);
    String timestamp = xml.substring(start, end);
    System.out.println("timestamp = " + timestamp);

    assertTrue("Timestamp should be in ISO_INSTANT ending with Z", timestamp.endsWith("Z"));
    TemporalAccessor parse = DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.systemDefault()).parse(timestamp);
    long epochSecond = Instant.from(parse).getEpochSecond();
    long diff = Math.abs(now - epochSecond);
    System.out.println("diff = " + diff);
    assertTrue("Difference between expirationdate and now should be 10 sec or less", diff <= 10);
}

From source file:com.moss.veracity.core.config.ConfigManager.java

private void write(Configuration config) throws Exception {
    Marshaller m = jaxbContext.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(config, new FileWriter(file));

    if (monitor != null) {
        monitor.reset();//ww w . j a  v a 2  s  . c  o m
    }
}

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())//  www .  ja v a 2  s. 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.healthcit.cacure.web.controller.FormExportController.java

@RequestMapping(method = RequestMethod.GET)
public void exportForm(@RequestParam(value = "id", required = true) Long formId,
        @RequestParam(value = "format", required = true) String format, HttpServletResponse response) {

    try {//from ww  w. jav a  2 s  . c  om
        OutputStream oStream = response.getOutputStream();
        Cure cureXml = dataExporter.constructFormXML(formId);
        JAXBContext jc = JAXBContext.newInstance("com.healthcit.cacure.export.model");

        if (ExportFormat.XML.name().endsWith(format)) {
            String fileNameHeader = String.format("attachment; filename=form-%d.xml;", formId);
            response.setHeader("Content-Disposition", fileNameHeader);
            response.setContentType("application/xml");

            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.marshal(cureXml, oStream);
            oStream.flush();
        } else if (ExportFormat.EXCEL.name().equals(format)) {
            String fileNameHeader = String.format("attachment; filename=form-%d.xlxml;", formId);
            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));
        }
    } 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:fr.fastconnect.factory.tibco.bw.codereview.ConvertRulesToSonarMojo.java

public void save(File f, Rules rules) {
    try {/*  w  ww. j a v a 2  s . c o  m*/
        JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
        Marshaller m = jaxbContext.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(rules, f);
    } catch (JAXBException e) {
        e.printStackTrace();
    }
}