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:edu.duke.cabig.c3pr.domain.scheduler.runtime.job.CCTSNotificationMessageJob.java

private String serialize(Notification notification) {
    try {/*from ww w . j  av  a 2  s.c  o m*/
        JAXBContext context = JAXBContext.newInstance(Notification.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        JAXBElement<Notification> jaxbElement = new JAXBElement<Notification>(
                new QName(CCTS_NOTIFICATIONS_NS, "notification"), Notification.class, notification);
        CharArrayWriter writer = new CharArrayWriter();
        m.marshal(jaxbElement, writer);
        return String.valueOf(writer.toCharArray());
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.ikon.util.impexp.RepositoryExporter.java

/**
 * Performs a recursive repository content export with metadata
 *//*from   w w  w . j a v  a  2  s.  com*/
private static ImpExpStats exportDocumentsHelper(String token, String fldPath, File fs, String metadata,
        boolean history, Writer out, InfoDecorator deco)
        throws FileNotFoundException, PathNotFoundException, AccessDeniedException, RepositoryException,
        IOException, DatabaseException, ParseException, NoSuchGroupException, MessagingException {
    log.debug("exportDocumentsHelper({}, {}, {}, {}, {}, {}, {})",
            new Object[] { token, fldPath, fs, metadata, history, out, deco });
    ImpExpStats stats = new ImpExpStats();
    DocumentModule dm = ModuleManager.getDocumentModule();
    FolderModule fm = ModuleManager.getFolderModule();
    MailModule mm = ModuleManager.getMailModule();
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    Gson gson = new Gson();
    String path = null;
    File fsPath = null;

    if (firstTime) {
        path = fs.getPath();
        fsPath = new File(path);
        firstTime = false;
    } else {
        // Repository path needs to be "corrected" under Windoze
        path = fs.getPath() + File.separator + PathUtils.getName(fldPath).replace(':', '_');
        fsPath = new File(path);
        fsPath.mkdirs();
        FileLogger.info(BASE_NAME, "Created folder ''{0}''", fsPath.getPath());

        if (out != null) {
            out.write(deco.print(fldPath, 0, null));
            out.flush();
        }
    }

    for (Iterator<Mail> it = mm.getChildren(token, fldPath).iterator(); it.hasNext();) {
        Mail mailChild = it.next();
        path = fsPath.getPath() + File.separator + PathUtils.getName(mailChild.getPath()).replace(':', '_');
        ImpExpStats mailStats = exportMail(token, mailChild.getPath(), path + ".eml", metadata, out, deco);

        // Stats
        stats.setSize(stats.getSize() + mailStats.getSize());
        stats.setMails(stats.getMails() + mailStats.getMails());
    }

    for (Iterator<Document> it = dm.getChildren(token, fldPath).iterator(); it.hasNext();) {
        Document docChild = it.next();
        path = fsPath.getPath() + File.separator + PathUtils.getName(docChild.getPath()).replace(':', '_');
        ImpExpStats docStats = exportDocument(token, docChild.getPath(), path, metadata, history, out, deco);

        // Stats
        stats.setSize(stats.getSize() + docStats.getSize());
        stats.setDocuments(stats.getDocuments() + docStats.getDocuments());
    }

    for (Iterator<Folder> it = fm.getChildren(token, fldPath).iterator(); it.hasNext();) {
        Folder fldChild = it.next();
        ImpExpStats tmp = exportDocumentsHelper(token, fldChild.getPath(), fsPath, metadata, history, out,
                deco);
        path = fsPath.getPath() + File.separator + PathUtils.getName(fldChild.getPath()).replace(':', '_');

        // Metadata
        if (metadata.equals("JSON")) {
            FolderMetadata fmd = ma.getMetadata(fldChild);
            String json = gson.toJson(fmd);
            FileOutputStream fos = new FileOutputStream(path + Config.EXPORT_METADATA_EXT);
            IOUtils.write(json, fos);
            fos.close();
        } else if (metadata.equals("XML")) {
            FileOutputStream fos = new FileOutputStream(path + ".xml");

            FolderMetadata fmd = ma.getMetadata(fldChild);
            JAXBContext jaxbContext;
            try {
                jaxbContext = JAXBContext.newInstance(FolderMetadata.class);
                Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

                // output pretty printed
                jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                jaxbMarshaller.marshal(fmd, fos);
            } catch (JAXBException e) {
                log.error(e.getMessage(), e);
                FileLogger.error(BASE_NAME, "XMLException ''{0}''", e.getMessage());
            }
        }

        // Stats
        stats.setSize(stats.getSize() + tmp.getSize());
        stats.setDocuments(stats.getDocuments() + tmp.getDocuments());
        stats.setFolders(stats.getFolders() + tmp.getFolders() + 1);
        stats.setOk(stats.isOk() && tmp.isOk());
    }

    log.debug("exportDocumentsHelper: {}", stats);
    return stats;
}

From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static String marshal(Object obj, String rootElementName) {
    StringWriter sw = new StringWriter();
    try {/*from  w w  w  . j  a  va  2  s.  c o  m*/
        JAXBContext jaxbCtx = JAXBContext.newInstance(obj.getClass().getPackage().getName());
        Marshaller marshaller = jaxbCtx.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(new JAXBElement(new QName(rootElementName), obj.getClass(), obj), sw);
        sw.close();

    } catch (PropertyException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return sw.toString();
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java

private static String getMetaDataXMLAsString(final JAXBContext jaxbContext, final Object jaxbObject)
        throws JAXBException {

    // Create an unmarshaller
    final Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    // Marshal the JAXB object meta-data into XML and return the result
    final StringWriter stringWriter = new StringWriter();
    marshaller.marshal(jaxbObject, stringWriter);

    return stringWriter.toString();
}

From source file:com.evolveum.midpoint.prism.util.JaxbTestUtil.java

private Marshaller createMarshaller(Map<String, Object> jaxbProperties) throws JAXBException {
    Marshaller marshaller = context.createMarshaller();
    // set default properties
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    DynamicNamespacePrefixMapper namespacePrefixMapper = getSchemaRegistry().getNamespacePrefixMapper().clone();
    namespacePrefixMapper.setAlwaysExplicit(true);
    marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", namespacePrefixMapper);
    // set custom properties
    if (jaxbProperties != null) {
        for (Entry<String, Object> property : jaxbProperties.entrySet()) {
            marshaller.setProperty(property.getKey(), property.getValue());
        }//w  ww. j a  v a2s . c om
    }

    return marshaller;
}

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

@Override
public void notifyScoreUpdate(ScoreRecord record) throws LpRestException {
    String contentType = "application/xml";
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/cw/bridge/scores", DefaultRestResource.REST_URI);
    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, contentType);

    try {// w  ww  .  j  av a  2  s.c  om
        JAXBContext jc = JAXBContext.newInstance(ScoreRecord.class);
        Writer marshalledRecord = new StringWriter();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(record, marshalledRecord);

        postMethod.setRequestEntity(new StringRequestEntity(marshalledRecord.toString(), contentType, "UTF-8"));

        httpClient.executeMethod(postMethod);
    } catch (JAXBException e1) {
        e1.printStackTrace();
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.netxforge.oss2.core.xml.JaxbUtils.java

public static Marshaller getMarshallerFor(final Object obj, final JAXBContext jaxbContext) {
    final Class<?> clazz = (Class<?>) (obj instanceof Class<?> ? obj : obj.getClass());

    Map<Class<?>, Marshaller> marshallers = m_marshallers.get();
    if (jaxbContext == null) {
        if (marshallers == null) {
            marshallers = new WeakHashMap<Class<?>, Marshaller>();
            m_marshallers.set(marshallers);
        }/*from  w  ww.  j a  va2 s.  c  o m*/
        if (marshallers.containsKey(clazz)) {
            LogUtils.tracef(clazz, "found unmarshaller for %s", clazz);
            return marshallers.get(clazz);
        }
    }
    LogUtils.tracef(clazz, "creating unmarshaller for %s", clazz);

    try {
        final JAXBContext context;
        if (jaxbContext == null) {
            context = getContextFor(clazz);
        } else {
            context = jaxbContext;
        }
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        final Schema schema = getValidatorFor(clazz);
        marshaller.setSchema(schema);
        if (jaxbContext == null)
            marshallers.put(clazz, marshaller);

        return marshaller;
    } catch (JAXBException e) {
        throw EXCEPTION_TRANSLATOR.translate("creating XML marshaller", e);
    }
}

From source file:edu.lternet.pasta.common.EmlUtility.java

/**
 * Creates and returns an EML 2.1.0 {@code <access} element string that
 * corresponds to the provided JAXB object.
 *
 * @param accessType//from w  w  w. ja  va  2 s .co  m
 *            the JAXB object to be represented as a string.
 * @return an EML 2.1.0 {@code <access} element string that corresponds to
 *         the provided JAXB object.
 */
public static String toString(AccessType accessType) {

    try {

        ObjectFactory factory = new ObjectFactory();
        JAXBElement<AccessType> jaxb = factory.createAccess(accessType);

        StringWriter writer = new StringWriter();

        String packageName = AccessType.class.getPackage().getName();
        JAXBContext jc = JAXBContext.newInstance(packageName);
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(jaxb, writer);

        return writer.toString();
    } catch (JAXBException e) {
        throw new IllegalStateException(e);
    }

}

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

@Override
public void guardar(OutputStream out) throws Exception {
    Marshaller m = context.createMarshaller();
    m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapperImpl(localPrefixes));
    m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, getSchemaLocation());
    byte[] xmlHeaderBytes = XML_HEADER.getBytes("UTF8");
    out.write(xmlHeaderBytes);//from  ww  w  . ja  v a 2 s .co  m
    m.marshal(document, out);
}