Example usage for javax.xml.bind Marshaller JAXB_FORMATTED_OUTPUT

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

Introduction

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

Prototype

String JAXB_FORMATTED_OUTPUT

To view the source code for javax.xml.bind Marshaller JAXB_FORMATTED_OUTPUT.

Click Source Link

Document

The name of the property used to specify whether or not the marshalled XML data is formatted with linefeeds and indentation.

Usage

From source file:de.uniwue.info6.database.jaxb.ScenarioExporter.java

/**
 *
 *
 * @param scenario// w ww .  j av a 2 s. c om
 */
public File generateScenarioXml(Scenario scenario) {
    scenario = populateScenario(scenario);
    File base = new File(scriptSystemPath + File.separator + Cfg.RESOURCE_PATH);
    File saveDir = new File(base, String.valueOf(scenario.getId()));

    try {
        if (!saveDir.exists() && saveDir.getParentFile().exists()) {
            saveDir.mkdir();
        }
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy_MM_dd-HH_mm_ss");
        String baseName = "scenario_" + scenario.getId() + "_export_" + fmt.format(new Date());

        String conflict = "VERSION_CONFLICT";
        File scenarioXml = new File(saveDir, baseName + ".xml");
        File scenarioXmlConflict = new File(saveDir, baseName + "_" + conflict + ".xml");
        File scenarioXsd = new File(saveDir, baseName + ".xsd");
        File scenarioXsdConflict = new File(saveDir, baseName + "_" + conflict + ".xsd");
        File scenarioMain = new File(scriptSystemPath, "reference_schema.xsd");
        File scenarioMainConflict = new File(saveDir, baseName + "_" + "REFERENCE_SCHEMA.xsd");

        JAXBContext jaxbContext = JAXBContext.newInstance(Scenario.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(scenario, scenarioXml);

        SchemaOutputResolver sor = new CustomOutputResolver(saveDir, baseName + ".xsd");
        jaxbContext.generateSchema(sor);

        if (!scenarioMain.exists()) {
            LOGGER.error("REFERENCE SCHEMA IS MISSING: " + scenarioMain);
        }

        if (!scenarioXsd.exists()) {
            LOGGER.error("GENERATED XSD IS MISSING: " + scenarioXsd);
        }

        if (!scenarioXml.exists()) {
            LOGGER.error("GENERATED XML IS MISSING: " + scenarioXml);
        }

        if (scenarioMain.exists() && scenarioXsd.exists() && scenarioXml.exists()) {
            String referenceMD5 = calculateMD5FromFile(scenarioMain);
            String newMD5 = calculateMD5FromFile(scenarioXsd);

            File export = null;
            boolean falseMD5 = !referenceMD5.equals(newMD5);
            File conflictReadme = new File(saveDir, conflict + "_README.txt");

            if (falseMD5) {
                FileUtils.moveFile(scenarioXml, scenarioXmlConflict);
                FileUtils.moveFile(scenarioXsd, scenarioXsdConflict);
                FileUtils.copyFile(scenarioMain, scenarioMainConflict);
                scenarioXml = scenarioXmlConflict;
                scenarioXsd = scenarioXsdConflict;
                export = new File(saveDir, "scenario_" + scenario.getId() + "_export_" + conflict + ".zip");
                String readme = Cfg.inst().getProp(DEF_LANGUAGE, "MISC.XSD_XML_CONFLICT") + "\n"
                        + scenarioMainConflict.getName();

                if (conflictReadme.exists()) {
                    conflictReadme.delete();
                }
                if (!conflictReadme.exists()) {
                    conflictReadme.createNewFile();
                }

                PrintWriter out = new PrintWriter(conflictReadme);
                out.println(readme);
                out.flush();
                out.close();
            } else {
                export = new File(saveDir, "scenario_" + scenario.getId() + "_export.zip");
            }

            ArrayList<File> exportFiles = new ArrayList<File>();
            if (scenarioXml.exists()) {
                exportFiles.add(scenarioXml);
            }
            if (scenarioXsd.exists()) {
                exportFiles.add(scenarioXsd);
            }
            if (falseMD5 && conflictReadme.exists() && scenarioMainConflict.exists()) {
                exportFiles.add(conflictReadme);
                exportFiles.add(scenarioMainConflict);
            }
            if (export.exists()) {
                export.delete();
            }
            return zip(exportFiles, export);
        }

    } catch (Exception e) {
        LOGGER.error("EXPORT XSD/XML FAILED!", e);
    }
    return null;
}

From source file:com.floreantpos.model.PosPrinters.java

public void save() {
    try {//from   w w w.  j  a v  a2 s .c o m
        getDefaultKitchenPrinter();

        populatePrinterMaps();

        File file = new File("config", "printers.xml"); //$NON-NLS-1$ //$NON-NLS-2$

        JAXBContext jaxbContext = JAXBContext.newInstance(PosPrinters.class);
        Marshaller m = jaxbContext.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

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

        FileUtils.write(file, writer.toString());

    } catch (Exception e) {
        PosLog.error(getClass(), e);
    }
}

From source file:de.thorstenberger.examServer.dao.xml.AbstractJAXBDao.java

/**
 * Serializes the object into xml. Will wrap any exception into a {@link RuntimeException}.
 *
 * @param obj//from w w w.j  a va 2s.com
 *            the object to save.
 * @throws RuntimeException
 *             wrapping {@link JAXBException} of {@link IOException}
 */
synchronized protected void save(final Object obj) {
    log.debug(String.format("Trying to save xml package to file '%s'", workingPath + "/" + xmlFileName));
    final String txId = startTransaction();
    Marshaller marshaller = null;
    try {

        marshaller = JAXBUtils.getJAXBMarshaller(jc);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
        final BufferedOutputStream bos = new BufferedOutputStream(
                getFRM().writeResource(txId, this.xmlFileName));
        marshaller.marshal(obj, bos);

        bos.close();
        commitTransaction(txId);
    } catch (final JAXBException e) {
        rollback(txId, e);
        throw new RuntimeException(e);
    } catch (final IOException e) {
        rollback(txId, e);
        throw new RuntimeException(e);
    } catch (final ResourceManagerException e) {
        rollback(txId, e);
        throw new RuntimeException(e);
    } catch (RuntimeException e) {
        rollback(txId, e);
        throw e;
    } finally {
        if (marshaller != null)
            JAXBUtils.releaseJAXBMarshaller(jc, marshaller);
    }
}

From source file:de.thorstenberger.taskmodel.complex.complextaskdef.impl.ComplexTaskDefDAOImpl.java

public void save(ComplexTaskDefRoot ctdr, OutputStream os) throws TaskApiException {
    BufferedOutputStream bos = new BufferedOutputStream(os);

    Marshaller marshaller = null;
    try {//  w w  w . j  a va 2 s.c om
        JAXBContext jc = createJAXBContext();
        marshaller = JAXBUtils.getJAXBMarshaller(jc);
        Validator validator = jc.createValidator();
        ComplexTaskDef ctd = ((ComplexTaskDefRootImpl) ctdr).getJAXBContent();
        validator.validate(ctd);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
        marshaller.marshal(ctd, bos);

    } catch (JAXBException e) {
        throw new TaskModelPersistenceException(e);
    } finally {
        try {
            bos.close();
        } catch (IOException e) {
            throw new TaskModelPersistenceException(e);
        }
        if (marshaller != null)
            JAXBUtils.releaseJAXBMarshaller(jc, marshaller);
    }

}

From source file:eu.crisis_economics.abm.dashboard.cluster.script.BashScheduler.java

/** {@inheritDoc} 
 * @throws SchedulerException /*from w w w . j  a  v  a 2s  .  c  om*/
 */
@Override
public String runParameterSweep(final Model paramSweepConfig, final String timeLimit, final File workDir)
        throws SchedulerException {

    File file = null;
    try {
        //         file = File.createTempFile("paramsweep-", ".xml");
        file = new File(workDir, "paramsweep-config.xml");
        Marshaller marshaller = JAXBContext.newInstance(Model.class).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(paramSweepConfig, file);
        //      } catch (IOException e) {
        //         throw new SchedulerException("Could not create temporary parameter-sweep configuration xml.", e);
    } catch (JAXBException e) {
        throw new SchedulerException(
                "Could not write temporary parameter-sweep configuration xml: " + file.toString(), e);
    }
    CommandLine cmd = new CommandLine(cmdFile);
    Map<String, Object> substitutions = new HashMap<String, Object>();
    substitutions.put(CMD_SUBSTITUTION_NAME_FILE, file);
    cmd.setSubstitutionMap(substitutions);

    if (timeLimit != null && !timeLimit.isEmpty()) {
        cmd.addArgument("-t", false);
        cmd.addArgument(timeLimit, false);
    }

    // add server port argument
    cmd.addArgument("-p", false);
    cmd.addArgument(String.valueOf(serverPort), false);

    cmd.addArgument("${" + CMD_SUBSTITUTION_NAME_FILE + "}", false);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(workDir);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(byteArrayOutputStream);

    executor.setStreamHandler(streamHandler);

    try {
        executor.execute(cmd);
    } catch (ExecuteException e) {
        throw new SchedulerException(
                paramSweepCmd + " exited with " + e.getExitValue() + ". Output:\n" + byteArrayOutputStream, e);
    } catch (IOException e) {
        throw new SchedulerException(
                "Execution of " + paramSweepCmd + " failed. Output:\n" + byteArrayOutputStream, e);
    }

    // the standard output of the script is the job id
    final String jobId = byteArrayOutputStream.toString();

    return jobId;
}

From source file:com.olp.jpa.domain.docu.ut.DepartmentServiceTest.java

public void test_marshalling() throws JAXBException {

    List<DepartmentBean> list = __service.findAll();

    DepartmentBean bean = __service.findByDeptCode("OPRTN");

    JAXBContext ctx = JAXBContext.newInstance(DepartmentBean.class);
    StringWriter writer = new StringWriter();
    Marshaller m = ctx.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.marshal(bean, writer);//from   w  w w .  j a v a  2s . com

    final String xml = writer.toString();
    System.out.println(xml);

}

From source file:org.kemri.wellcome.dhisreport.api.model.HttpDhis2Server.java

@Override
public ImportSummary postReport(DataValueSet report) throws DHIS2ReportingException {
    log.debug("Posting datavalueset report");
    ImportSummary summary = null;// w  w w. j av  a  2s  .c  o m

    StringWriter xmlReport = new StringWriter();
    try {
        JAXBContext jaxbDataValueSetContext = JAXBContext.newInstance(DataValueSet.class);
        Marshaller dataValueSetMarshaller = jaxbDataValueSetContext.createMarshaller();
        // output pretty printed
        dataValueSetMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        dataValueSetMarshaller.marshal(report, xmlReport);
    } catch (JAXBException ex) {
        log.error(ex.getMessage());
        throw new Dxf2Exception("Problem marshalling dataValueSet", ex);
    }

    String host = getUrl().getHost();
    int port = getUrl().getPort();

    HttpHost targetHost = new HttpHost(host, port, getUrl().getProtocol());
    DefaultHttpClient httpclient = new DefaultHttpClient();
    BasicHttpContext localcontext = new BasicHttpContext();

    try {
        String postUrl = getUrl().toString() + DATAVALUESET_PATH;
        log.error("Post URL: " + postUrl);
        HttpPost httpPost = new HttpPost(postUrl);
        Credentials creds = new UsernamePasswordCredentials(username, password);
        Header bs = new BasicScheme().authenticate(creds, httpPost, localcontext);
        httpPost.addHeader("Authorization", bs.getValue());
        httpPost.addHeader("Content-Type", "application/xml; charset=utf-8");
        httpPost.addHeader("Accept", "application/xml");

        httpPost.setEntity(new StringEntity(xmlReport.toString()));
        HttpResponse response = httpclient.execute(targetHost, httpPost, localcontext);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            JAXBContext jaxbImportSummaryContext = JAXBContext.newInstance(ImportSummary.class);
            Unmarshaller importSummaryUnMarshaller = jaxbImportSummaryContext.createUnmarshaller();
            summary = (ImportSummary) importSummaryUnMarshaller.unmarshal(entity.getContent());
        }
    } catch (Exception ex) {
        log.error(ex.getMessage());
        throw new Dhis2Exception(this, "Problem accessing Dhis2 server", ex);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return summary;
}

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
 *//*from   w w w .  j av a 2 s.  c  o  m*/
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:labr_client.xml.ObjToXML.java

public static void jaxbObjectToXML(KmehrMessage kmehrMessage) {
    try {// w  w  w . jav  a  2 s  .com
        JAXBContext context = JAXBContext.newInstance(KmehrMessage.class);
        Marshaller m = context.createMarshaller();
        //for pretty-print XML in JAXB
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        //----------HEADER--------------------------
        kmehrMessage.header.id.setS("ID-KMEHR");
        kmehrMessage.header.id.setSV("1.15");
        kmehrMessage.header.id.setValue("0000000");
        kmehrMessage.header.setDate("20160519");
        kmehrMessage.header.setTime("09:40:31");
        kmehrMessage.header.standard.cd.setS("CD-STANDARD");
        kmehrMessage.header.standard.cd.setSV("1.15");
        kmehrMessage.header.standard.cd.setValue("20150901");
        //----------HEADER-ZENDER-------------------------
        kmehrMessage.header.sender.hcparty.id.setS("ID-HCPARTY");
        kmehrMessage.header.sender.hcparty.id.setSV("1.15");
        kmehrMessage.header.sender.hcparty.id.setValue("000000");
        kmehrMessage.header.sender.hcparty.cd.setS("CD-HCPARTY");
        kmehrMessage.header.sender.hcparty.cd.setSV("1.15");
        kmehrMessage.header.sender.hcparty.cd.setValue("persphysician");
        kmehrMessage.header.sender.hcparty.setFamilyname("Pieters");
        kmehrMessage.header.sender.hcparty.setFirstname("Piet");
        //----------HEADER-ONTVANGER(S)--------------------
        Hcparty receiver = new Hcparty();
        receiver.id.setS("ID-HCPARTY");
        receiver.id.setSV("1.15");
        receiver.id.setValue("000000");
        receiver.cd.setS("CD-HCPARTY");
        receiver.cd.setSV("1.15");
        receiver.cd.setValue("persphysician");
        receiver.setFamilyname("Pieters");
        receiver.setFirstname("Piet");
        kmehrMessage.header.receiver.getHcparty().add(receiver);
        //----------FOLDER-------------------------
        kmehrMessage.folder.id.setS("ID-HCPARTY");
        kmehrMessage.folder.id.setSV("1.15");
        kmehrMessage.folder.patient.setFamilyname("De Mey");
        kmehrMessage.folder.patient.setFirstname("Matthias");
        kmehrMessage.folder.patient.birthdate.setDate("1990/06/07");

        kmehrMessage.setXmlns("http://www.ehealth.fgov.be/standards/kmehr/schema/v1");

        m.marshal(kmehrMessage, new File("C:\\Users\\labbl\\Documents\\testKMEHR.xml"));
    } catch (JAXBException e) {
        e.printStackTrace();
    }
}

From source file:mx.bigdata.sat.cfdi.TFDv1.java

public void guardar(OutputStream out) throws Exception {
    Marshaller m = CONTEXT.createMarshaller();
    m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapperImpl(CFDv3.PREFIXES));
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
            "http://www.sat.gob.mx/cfd/3  " + "http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv3.xsd");
    m.marshal(document.getComprobante(), out);
}