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:ee.ria.xroad.proxy.serverproxy.MetadataServiceHandlerImpl.java

private static void marshal(Object object, Node out) throws Exception {
    Marshaller marshaller = JAXB_CTX.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    marshaller.marshal(object, out);//from w  w w .j a va  2s . c o  m
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.objects.util.GenerateXMLString.java

public static String getExecutionresultString(String urlServer, String projectAreaAlias, String encoding,
        String executionWorkItemUrl, ScenarioState stateOf, Date _startDate, Date _endDate, String details)
        throws JAXBException, DatatypeConfigurationException {

    Date startDate = (Date) _startDate.clone();
    Date endDate = (Date) _endDate.clone();

    com.ibm.rqm.xml.bind.Executionresult.Executionworkitem workTest = new com.ibm.rqm.xml.bind.Executionresult.Executionworkitem();
    workTest.setHref(executionWorkItemUrl);

    State state = new State();
    Executionresult result = new Executionresult();
    if (stateOf.equals(ScenarioState.FAILED)) {
        state.setContent("com.ibm.rqm.execution.common.state.failed");
    } else {/*from www  .ja  v a2 s  .c  o  m*/
        if (stateOf.equals(ScenarioState.PENDING)) {
            state.setContent("com.ibm.rqm.execution.common.state.blocked");
        } else {
            state.setContent("com.ibm.rqm.execution.common.state.passed");
        }
    }

    result.setState(state);
    result.setExecutionworkitem(workTest);

    // Datas de incio e fim do teste
    GregorianCalendar c = new GregorianCalendar();
    c.setTime(startDate);
    XMLGregorianCalendar startDateXml = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    result.setStarttime(startDateXml);

    c.setTime(endDate);
    XMLGregorianCalendar endDateXml = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    result.setEndtime(endDateXml);

    // Details
    Details d = new Details();
    d.getContent().add(details);
    result.setDetails(d);

    JAXBContext jaxb = JAXBContext.newInstance(Executionresult.class);
    Marshaller marshaller = jaxb.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
    StringWriter resourceString = new StringWriter();
    marshaller.marshal(result, resourceString);

    return resourceString.toString();
}

From source file:eu.eco2clouds.scheduler.bonfire.BFClientSchedulerImpl.java

private Compute changeStateCompute(String userId, Compute compute, String state) {
    this.userId = userId;
    Boolean exception = false;//www  .j  av a 2 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:br.ufpb.dicomflow.integrationAPI.tools.ReadService.java

private static void saveMessages(List<MessageIF> messages, File destDir) throws JAXBException, IOException {
    Iterator<MessageIF> it = messages.iterator();
    while (it.hasNext()) {
        MessageIF messageIF = (MessageIF) it.next();
        ServiceIF service = messageIF.getService();
        Logger.v(rb.getString("loaded-service") + service.getName() + " - " + service.getAction() + " - "
                + service.getMessageID());

        JAXBContext jaxbContext = JAXBContext.newInstance(messageIF.getService().getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        FileOutputStream fos = new FileOutputStream(destDir.getAbsolutePath() + File.pathSeparator
                + service.getName() + "_" + service.getAction() + "_" + service.getMessageID());
        jaxbMarshaller.marshal(messageIF.getService(), fos);

        if (messageIF.getAttach() != null && messageIF.getAttach().length > 0) {
            fos = new FileOutputStream(destDir.getAbsolutePath() + File.pathSeparator + service.getName() + "_"
                    + service.getAction() + "_" + service.getMessageID() + "_attach");
            fos.write(messageIF.getAttach());
            fos.close();/*from www  .j  a  va 2s  . c  o  m*/
        }

    }
}

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

/**
 * Get this header as an XML string./*from w w w .ja va 2s .  co  m*/
 * 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.manydesigns.portofino.persistence.Persistence.java

public synchronized void saveXmlModel() throws IOException, JAXBException {
    //TODO gestire conflitti con modifiche esterne?
    File tempFile = File.createTempFile(appModelFile.getName(), "");

    JAXBContext jc = JAXBContext.newInstance(Model.JAXB_MODEL_PACKAGES);
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.marshal(model, tempFile);/*w  w w.  j  av  a2 s  . co  m*/

    ElementsFileUtils.moveFileSafely(tempFile, appModelFile.getAbsolutePath());
    lastLiquibaseRunTime = new Date(0);
    logger.info("Saved xml model to file: {}", appModelFile);
}

From source file:com.bitplan.jaxb.JaxbFactory.java

/**
 * get a marshaller for the given <T> instance
 * /*from ww w. j a  v a  2s .  com*/
 * @param instance
 *          - the instance to get a marshaller for
 * @return a marshaller for <T>
 * @throws JAXBException
 */
public Marshaller getMarshaller(T instance) throws JAXBException {
    JAXBContext lcontext = getJAXBContext();
    Marshaller marshaller = lcontext.createMarshaller();
    if (this.marshalListener != null) {
        marshaller.setListener(marshalListener);
    }
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    return marshaller;
}

From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

private static void writeAsterixClusterConfigurationFile(AsterixInstance asterixInstance)
        throws IOException, EventException, JAXBException {
    String asterixInstanceName = asterixInstance.getName();
    Cluster cluster = asterixInstance.getCluster();

    JAXBContext ctx = JAXBContext.newInstance(Cluster.class);
    Marshaller marshaller = ctx.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(cluster, new FileOutputStream(AsterixEventService.getAsterixDir() + File.separator
            + asterixInstanceName + File.separator + "cluster.xml"));
}

From source file:org.opennms.features.vaadin.pmatrix.calculator.PmatrixDpdCalculatorRepository.java

/**
 * Causes the dataPointMap to be persisted to a file
 * @param file file definition to persist the data set to
 * @return true if dataPointMap persisted correctly, false if not
 *//*  www.j  a  v a 2  s  . co  m*/
public boolean persist() {
    File currentArchiveFile = null;
    File tmpCurrentArchiveFile = null;
    Resource tmpResource = null;

    if (!persistHistoricData) {
        LOG.debug("not persisting data as persistHistoricData=false");
        return false;
    }

    if (archiveFileName == null || archiveFileDirectoryLocation == null) {
        LOG.error("cannot save historical data to file as incorrect file location:"
                + " archiveFileDirectoryLocation=" + archiveFileDirectoryLocation + " archiveFileName="
                + archiveFileName);
        return false;
    }

    // set the date on which this file was persisted
    datePersisted = new Date();

    // used to get file name suffix
    SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormatString);

    // persist data to temporary file <archiveFileName.tmp>
    String tmpArchiveFileName = archiveFileName + ".tmp";
    String tmpArchiveFileLocation = archiveFileDirectoryLocation + File.separator + tmpArchiveFileName;
    LOG.debug("historical data will be written to temporary file :" + tmpArchiveFileLocation);

    try {
        tmpResource = resourceLoader.getResource(tmpArchiveFileLocation);
        tmpCurrentArchiveFile = new File(tmpResource.getURL().getFile());
    } catch (IOException e) {
        LOG.error("cannot save historical data to file at archiveFileLocation='" + tmpArchiveFileLocation
                + "' due to error:", e);
        return false;
    }

    LOG.debug(
            "persisting historical data to temporary file location:" + tmpCurrentArchiveFile.getAbsolutePath());

    // marshal the data
    PrintWriter writer = null;
    boolean marshalledCorrectly = false;
    try {
        // create  directory if doesn't exist
        File directory = new File(tmpCurrentArchiveFile.getParentFile().getAbsolutePath());
        directory.mkdirs();
        // create file if doesn't exist
        writer = new PrintWriter(tmpCurrentArchiveFile, "UTF-8");
        writer.close();

        // see http://stackoverflow.com/questions/1043109/why-cant-jaxb-find-my-jaxb-index-when-running-inside-apache-felix
        // need to provide bundles class loader
        ClassLoader cl = org.opennms.features.vaadin.pmatrix.model.DataPointDefinition.class.getClassLoader();
        JAXBContext jaxbContext = JAXBContext.newInstance(
                "org.opennms.features.vaadin.pmatrix.model:org.opennms.features.vaadin.pmatrix.calculator", cl);

        //JAXBContext jaxbContext = JAXBContext.newInstance("org.opennms.features.vaadin.pmatrix.model:org.opennms.features.vaadin.pmatrix.calculator");

        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

        // TODO CHANGE output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        // marshal this Data Repository
        jaxbMarshaller.marshal(this, tmpCurrentArchiveFile);

        marshalledCorrectly = true;
    } catch (JAXBException e) {
        LOG.error("problem marshalling file: ", e);
    } catch (Exception e) {
        LOG.error("problem marshalling file: ", e);
    } finally {
        if (writer != null)
            writer.close();
    }
    if (marshalledCorrectly == false)
        return false;

    // marshaling succeeded so rename tmp file
    String archiveFileLocation = archiveFileDirectoryLocation + File.separator + archiveFileName;
    LOG.info("historical data will be written to:" + archiveFileLocation);

    Resource resource = resourceLoader.getResource(archiveFileLocation);

    if (resource.exists()) {
        String oldArchiveFileName = archiveFileName + "." + dateFormatter.format(datePersisted);
        String oldArchiveFileLocation = archiveFileDirectoryLocation + File.separator + oldArchiveFileName;
        LOG.info("previous historical file at archiveFileLocation='" + archiveFileLocation
                + "' exists so being renamed to " + oldArchiveFileLocation);
        Resource oldresource = resourceLoader.getResource(oldArchiveFileLocation);
        try {
            currentArchiveFile = new File(resource.getURL().getFile());
            File oldArchiveFile = new File(oldresource.getURL().getFile());
            // rename current archive file to old archive file name
            if (!currentArchiveFile.renameTo(oldArchiveFile)) {
                throw new IOException("cannot rename current archive file:"
                        + currentArchiveFile.getAbsolutePath() + " to " + oldArchiveFile.getAbsolutePath());
            }
            // rename temporary archive file to current archive file name
            if (!tmpCurrentArchiveFile.renameTo(currentArchiveFile)) {
                throw new IOException("cannot rename temporary current archive file:"
                        + tmpCurrentArchiveFile.getAbsolutePath() + " to "
                        + currentArchiveFile.getAbsolutePath());
            }
        } catch (IOException e) {
            LOG.error("Problem archiving old persistance file", e);
        }
        // remove excess files
        try {
            Resource directoryResource = resourceLoader.getResource(archiveFileDirectoryLocation);
            File archiveFolder = new File(directoryResource.getURL().getFile());
            File[] listOfFiles = archiveFolder.listFiles();

            String filename;
            //this will sort earliest to latest date
            TreeMap<Date, File> sortedFiles = new TreeMap<Date, File>();

            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    filename = listOfFiles[i].getName();
                    if ((!filename.equals(archiveFileName)) && (!filename.equals(tmpArchiveFileName))
                            && (filename.startsWith(archiveFileName))) {
                        String beforeTimeString = archiveFileName + ".";
                        String timeSuffix = filename.substring(beforeTimeString.length());
                        if (!"".equals(timeSuffix)) {
                            Date fileCreatedate = null;
                            try {
                                fileCreatedate = dateFormatter.parse(timeSuffix);
                            } catch (ParseException e) {
                                LOG.debug("cant parse file name suffix to time for filename:" + filename, e);
                            }
                            if (fileCreatedate != null) {
                                sortedFiles.put(fileCreatedate, listOfFiles[i]);
                            }
                        }
                    }
                }
            }

            while (sortedFiles.size() > archiveFileMaxNumber) {
                File removeFile = sortedFiles.remove(sortedFiles.firstKey());
                LOG.debug("deleting archive file:'" + removeFile.getName()
                        + "' so that number of archive files <=" + archiveFileMaxNumber);
                removeFile.delete();
            }
            for (File archivedFile : sortedFiles.values()) {
                LOG.debug("not deleting archive file:'" + archivedFile.getName()
                        + "' so that number of archive files <=" + archiveFileMaxNumber);
            }

            return true;
        } catch (IOException e) {
            LOG.error("Problem removing old persistance files", e);
        }
    } else {
        // if resource doesn't exist just rename the new tmp file to the archive file name
        try {
            currentArchiveFile = new File(resource.getURL().getFile());
            // rename temporary archive file to current archive file name
            if (!tmpCurrentArchiveFile.renameTo(currentArchiveFile)) {
                throw new IOException("cannot rename temporary current archive file:"
                        + tmpCurrentArchiveFile.getAbsolutePath() + " to "
                        + currentArchiveFile.getAbsolutePath());
            }
            return true;
        } catch (IOException e) {
            LOG.error("cannot rename temporary current archive ", e);
        }
    }

    return false;

}

From source file:com.castlemock.web.basis.model.RepositoryImpl.java

/**
 * The method provides the functionality to export an entity and convert it to a String
 * @param id The id of the entityy that will be converted and exported
 * @return The entity with the provided id as a String
 *//*from  w  ww  .  j  ava2 s. com*/
@Override
public String exportOne(final I id) {
    try {
        final T type = collection.get(id);
        final JAXBContext context = JAXBContext.newInstance(entityClass);
        final Marshaller marshaller = context.createMarshaller();
        final StringWriter writer = new StringWriter();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(type, writer);
        return writer.toString();
    } catch (JAXBException e) {
        throw new IllegalStateException("Unable to export type", e);
    }
}