Example usage for javax.xml.bind Marshaller marshal

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

Introduction

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

Prototype

public void marshal(Object jaxbElement, javax.xml.stream.XMLEventWriter writer) throws JAXBException;

Source Link

Document

Marshal the content tree rooted at jaxbElement into a javax.xml.stream.XMLEventWriter .

Usage

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.manydesigns.portofino.dispatcher.DispatcherLogic.java

public static File saveConfiguration(File directory, Object configuration) throws Exception {
    String configurationPackage = configuration.getClass().getPackage().getName();
    JAXBContext jaxbContext = JAXBContext.newInstance(configurationPackage);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    File configurationFile = new File(directory, "configuration.xml");
    marshaller.marshal(configuration, configurationFile);
    configurationCache.invalidate(configurationFile);
    return configurationFile;
}

From source file:org.apache.directory.fortress.core.rest.RestUtils.java

/**
 * Marshall the request into an XML String.
 *
 * @param request/*  w  w w .j  av a2  s  .  com*/
 * @return String containing xml request
 * @throws RestException
 */
public static String marshal(FortRequest request) throws RestException {
    String szRetValue;
    try {
        // Create a JAXB context passing in the class of the object we want to marshal/unmarshal
        final JAXBContext context = cachedJaxbContext.getJaxbContext(FortRequest.class);
        // =============================================================================================================
        // Marshalling OBJECT to XML
        // =============================================================================================================
        // Create the marshaller, that will transform the object into XML
        final Marshaller marshaller = context.createMarshaller();
        // Create a stringWriter to hold the XML
        final StringWriter stringWriter = new StringWriter();
        // Marshal the javaObject and write the XML to the stringWriter
        marshaller.marshal(request, stringWriter);
        szRetValue = stringWriter.toString();
    } catch (JAXBException je) {
        String error = "marshal caught JAXBException=" + je;
        throw new RestException(GlobalErrIds.REST_MARSHALL_ERR, error, je);
    }
    return szRetValue;
}

From source file:org.pentaho.platform.dataaccess.datasource.DataSourcePublishACLTest.java

private static String marshalACL(RepositoryFileAclDto acl) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(RepositoryFileAclDto.class);
    Marshaller marshaller = context.createMarshaller();
    StringWriter sw = new StringWriter();
    marshaller.marshal(acl, sw);//from w  ww .j  av a  2  s  .com

    return sw.toString();
}

From source file:Main.java

public static String convertBean2Xml(Object obj) throws IOException {
    String result = null;/*from   ww w  .  ja  v  a2  s  .c  o  m*/
    try {
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(baos,
                (String) marshaller.getProperty(Marshaller.JAXB_ENCODING));
        xmlStreamWriter.writeStartDocument((String) marshaller.getProperty(Marshaller.JAXB_ENCODING), "1.0");
        marshaller.marshal(obj, xmlStreamWriter);
        xmlStreamWriter.writeEndDocument();
        xmlStreamWriter.close();
        result = baos.toString("UTF-8");

    } catch (JAXBException e) {
        e.printStackTrace();
        return null;
    } catch (XMLStreamException e) {
        e.printStackTrace();
        return null;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
    return result;
}

From source file:carisma.ui.eclipse.CarismaGUI.java

public final static void saveXml(final AnalysisResult analysisResult) {
    IContainer container = analysisResult.getAnalysis().getIFile().getParent();
    IFile file = null;// w  w w  .j  a v  a 2  s.  co m
    if (container instanceof IFolder) {
        IFolder folder = (IFolder) container;
        file = folder.getFile(
                "xml-output-" + analysisResult.getName() + "-" + analysisResult.getTimestamp() + ".xml");

    } else if (container instanceof IProject) {
        IProject project = (IProject) container;
        file = project.getFile(
                "xml-output-" + analysisResult.getName() + "-" + analysisResult.getTimestamp() + ".xml");
    } else {
        Logger.log(LogLevel.ERROR, "Analyzed file is not part of a project.");
        return;
    }
    if (!(file.exists())) {

        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {

            JAXBContext context = JAXBContext.newInstance(carisma.core.analysis.result.AnalysisResult.class);
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            m.marshal(analysisResult, out);

            String store = new String(out.toByteArray(), StandardCharsets.UTF_8);

            InputStream is = new ByteArrayInputStream(store.getBytes(StandardCharsets.UTF_8));
            // file.create(Utils.createInputStreamFromString(store), true,
            // null);
            file.create(is, true, null);

            // JSONObject fromXml = XML.toJSONObject(store);
            // String jsonPrint = fromXml.toString(1);
            // System.out.println(jsonPrint);

            // carisma.core.analysis.result.exp.dbexport.exportXml(jsonPrint);

            out.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
}

From source file:Main.java

public static String parseBeanToXmlStringByJAXB(Object bean, Class clase) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(clase);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
    JAXBElement<Object> rootElement = new JAXBElement<Object>(new QName(clase.getSimpleName()), clase, bean);

    OutputStream output = new OutputStream() {

        private StringBuilder string = new StringBuilder();

        public void write(int b) throws IOException {
            this.string.append((char) b);
        }//ww  w.j  ava  2  s.c  om

        //Netbeans IDE automatically overrides this toString()
        public String toString() {
            return this.string.toString();
        }
    };

    marshaller.marshal(rootElement, output);

    return output.toString();

}

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

/**
 * Performs a recursive repository content export with metadata
 *//*from  www  . j  a  v  a 2  s.  c o  m*/
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:it.cnr.icar.eric.server.cms.CMSManagerImpl.java

/**
 * Gets the <code>ExtrinsicObjectType</code> as a stream of XML markup.
 *
 * @param eo an <code>ExtrinsicObjectType</code> value
 * @return a <code>StreamSource</code> value
 * @exception RegistryException if an error occurs
 *///w ww  .  ja  v a  2  s .com
protected static StreamSource getAsStreamSource(ExtrinsicObjectType eo) throws RegistryException {
    log.trace("getAsStreamSource(ExtrinsicObjectType ) entered");

    StreamSource src = null;

    try {
        StringWriter sw = new StringWriter();

        Marshaller marshaller = bu.getJAXBContext().createMarshaller();

        marshaller.marshal(eo, sw);

        StringReader reader = new StringReader(sw.toString());
        src = new StreamSource(reader);
    }
    // these Exceptions should already be caught by Binding
    catch (JAXBException e) {
        throw new RegistryException(e);
    }

    return src;
}

From source file:com.sun.tools.xjc.addon.xew.XmlElementWrapperPluginTest.java

/**
 * Standard test for XSD examples./* ww w .  j a  v a 2  s . c  om*/
 * 
 * @param testName
 *            the prototype of XSD file name / package name
 * @param extraXewOptions
 *            to be passed to plugin
 * @param generateEpisode
 *            generate episode file and check the list of classes included into it
 * @param classesToCheck
 *            expected classes/files in target directory; these files content is checked if it is present in
 *            resources directory; {@code ObjectFactory.java} is automatically included
 */
static void assertXsd(String testName, String[] extraXewOptions, boolean generateEpisode,
        String... classesToCheck) throws Exception {
    String resourceXsd = testName + ".xsd";
    String packageName = testName.replace('-', '_');

    // Force plugin to reinitialize the logger:
    System.clearProperty(XmlElementWrapperPlugin.COMMONS_LOGGING_LOG_LEVEL_PROPERTY_KEY);

    URL xsdUrl = XmlElementWrapperPluginTest.class.getResource(resourceXsd);

    File targetDir = new File(GENERATED_SOURCES_PREFIX);

    targetDir.mkdirs();

    PrintStream loggingPrintStream = new PrintStream(
            new LoggingOutputStream(logger, LoggingOutputStream.LogLevel.INFO, "[XJC] "));

    String[] opts = ArrayUtils.addAll(extraXewOptions, "-no-header", "-extension", "-Xxew", "-d",
            targetDir.getPath(), xsdUrl.getFile());

    String episodeFile = new File(targetDir, "episode.xml").getPath();

    // Episode plugin should be triggered after Xew, see https://github.com/dmak/jaxb-xew-plugin/issues/6
    if (generateEpisode) {
        opts = ArrayUtils.addAll(opts, "-episode", episodeFile);
    }

    assertTrue("XJC compilation failed. Checked console for more info.",
            Driver.run(opts, loggingPrintStream, loggingPrintStream) == 0);

    if (generateEpisode) {
        // FIXME: Episode file actually contains only value objects
        Set<String> classReferences = getClassReferencesFromEpisodeFile(episodeFile);

        if (Arrays.asList(classesToCheck).contains("package-info")) {
            classReferences.add(packageName + ".package-info");
        }

        assertEquals("Wrong number of classes in episode file", classesToCheck.length, classReferences.size());

        for (String className : classesToCheck) {
            assertTrue(className + " class is missing in episode file;",
                    classReferences.contains(packageName + "." + className));
        }
    }

    targetDir = new File(targetDir, packageName);

    Collection<String> generatedJavaSources = new HashSet<String>();

    // *.properties files are ignored:
    for (File targetFile : FileUtils.listFiles(targetDir, new String[] { "java" }, true)) {
        // This is effectively the path of targetFile relative to targetDir:
        generatedJavaSources
                .add(targetFile.getPath().substring(targetDir.getPath().length() + 1).replace('\\', '/'));
    }

    // This class is added and checked by default:
    classesToCheck = ArrayUtils.add(classesToCheck, "ObjectFactory");

    assertEquals("Wrong number of generated classes " + generatedJavaSources + ";", classesToCheck.length,
            generatedJavaSources.size());

    for (String className : classesToCheck) {
        className = className.replace('.', '/') + ".java";

        assertTrue(className + " is missing in target directory", generatedJavaSources.contains(className));
    }

    // Check the contents for those files which exist in resources:
    for (String className : classesToCheck) {
        className = className.replace('.', '/') + ".java";

        File sourceFile = new File(PREGENERATED_SOURCES_PREFIX + packageName, className);

        if (sourceFile.exists()) {
            // To avoid CR/LF conflicts:
            assertEquals("For " + className, FileUtils.readFileToString(sourceFile).replace("\r", ""),
                    FileUtils.readFileToString(new File(targetDir, className)).replace("\r", ""));
        }
    }

    JAXBContext jaxbContext = compileAndLoad(packageName, targetDir, generatedJavaSources);

    URL xmlTestFile = XmlElementWrapperPluginTest.class.getResource(testName + ".xml");

    if (xmlTestFile != null) {
        StringWriter writer = new StringWriter();

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schemaFactory.newSchema(xsdUrl));

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        Object bean = unmarshaller.unmarshal(xmlTestFile);
        marshaller.marshal(bean, writer);

        XMLUnit.setIgnoreComments(true);
        XMLUnit.setIgnoreWhitespace(true);
        Diff xmlDiff = new Diff(IOUtils.toString(xmlTestFile), writer.toString());

        assertXMLEqual("Generated XML is wrong: " + writer.toString(), xmlDiff, true);
    }
}