Example usage for javax.xml.bind JAXBContext createMarshaller

List of usage examples for javax.xml.bind JAXBContext createMarshaller

Introduction

In this page you can find the example usage for javax.xml.bind JAXBContext createMarshaller.

Prototype

public abstract Marshaller createMarshaller() throws JAXBException;

Source Link

Document

Create a Marshaller object that can be used to convert a java content tree into XML data.

Usage

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

/**
 * Export mail from openkm repository to filesystem.
 *///from   w w  w .j  ava  2 s. c  o m
public static ImpExpStats exportMail(String token, String mailPath, String destPath, String metadata,
        Writer out, InfoDecorator deco) throws PathNotFoundException, RepositoryException, DatabaseException,
        IOException, AccessDeniedException, ParseException, NoSuchGroupException, MessagingException {
    MailModule mm = ModuleManager.getMailModule();
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    Mail mailChild = mm.getProperties(token, mailPath);
    Gson gson = new Gson();
    ImpExpStats stats = new ImpExpStats();
    MimeMessage msg = MailUtils.create(token, mailChild);
    FileOutputStream fos = new FileOutputStream(destPath);
    msg.writeTo(fos);
    IOUtils.closeQuietly(fos);
    FileLogger.info(BASE_NAME, "Created document ''{0}''", mailChild.getPath());

    // Metadata
    if (metadata.equals("JSON")) {
        MailMetadata mmd = ma.getMetadata(mailChild);
        String json = gson.toJson(mmd);
        fos = new FileOutputStream(destPath + Config.EXPORT_METADATA_EXT);
        IOUtils.write(json, fos);
        IOUtils.closeQuietly(fos);
    } else if (metadata.equals("XML")) {
        fos = new FileOutputStream(destPath + ".xml");

        MailMetadata mmd = ma.getMetadata(mailChild);
        JAXBContext jaxbContext;
        try {
            jaxbContext = JAXBContext.newInstance(MailMetadata.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

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

    if (out != null) {
        out.write(deco.print(mailChild.getPath(), mailChild.getSize(), null));
        out.flush();
    }

    // Stats
    stats.setSize(stats.getSize() + mailChild.getSize());
    stats.setMails(stats.getMails() + 1);

    return stats;
}

From source file:org.tellervo.desktop.wsi.WebJaxbAccessor.java

/**
 * Marshall this object to a JDOM Document
 * /*from  w w w .j ava 2s.  co  m*/
 * @param context
 * @param object
 * @param prefixMapper an implementation of namespacePrefixMapper
 * @return
 * @throws JAXBException
 */
protected static Document marshallToDocument(JAXBContext context, Object object,
        NamespacePrefixMapper prefixMapper) throws JAXBException {
    JDOMResult result = new JDOMResult();
    Marshaller m = context.createMarshaller();

    // set a namespace prefix mapper
    if (prefixMapper != null)
        m.setProperty("com.sun.xml.bind.namespacePrefixMapper", prefixMapper);

    m.marshal(object, result);

    return result.getDocument();
}

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;//from  w ww  .  ja va  2  s  .  c  om
    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: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);
        }/*w  w  w .ja va2s  . c om*/
        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.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:com.hpe.application.automation.tools.octane.executor.UFTTestDetectionService.java

/**
 * Serialize detectionResult to file in XML format
 *
 * @param fileToWriteTo/*  w w w .j  av  a  2 s .  c  o  m*/
 * @param taskListenerLog
 * @param detectionResult
 */
public static void publishDetectionResults(File fileToWriteTo, TaskListener taskListenerLog,
        UFTTestDetectionResult detectionResult) {

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(UFTTestDetectionResult.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(detectionResult, fileToWriteTo);

    } catch (JAXBException e) {
        if (taskListenerLog != null) {
            taskListenerLog.error("Failed to persist detection results: " + e.getMessage());
        }
        logger.error("Failed to persist detection results: " + e.getMessage());
    }
}

From source file:org.apache.lens.regression.util.Util.java

public static Marshaller getMarshaller(Class clazz) {
    JAXBContext jaxbContext = null;
    try {// w w w.j  av  a2  s. c  o m
        jaxbContext = new LensJAXBContext(clazz);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        return jaxbMarshaller;
    } catch (JAXBException e) {
        log.error("Error : ", e);
    }

    return null;
}

From source file:com.jkoolcloud.tnt4j.streams.configure.state.AbstractFileStreamStateHandler.java

/**
 * Persists files streaming state in specified directory or system temp directory.
 *
 * @param fileAccessState//  w  ww .  ja v  a  2 s. c om
 *            streamed files access state
 * @param fileDir
 *            directory to save file
 * @param streamName
 *            stream name
 *
 * @return file containing persisted state
 *
 * @throws JAXBException
 *             if parsing fails
 */
static File writeState(FileAccessState fileAccessState, File fileDir, String streamName) throws JAXBException {
    if (fileAccessState == null) {
        return null;
    }

    JAXBContext jaxb = JAXBContext.newInstance(FileAccessState.class);
    final Marshaller marshaller = jaxb.createMarshaller();

    File fasFile = null;
    String fileName = getFileName(streamName);
    if (fileDir != null) {
        fasFile = new File(fileDir, fileName);
    }

    if (fileDir == null || !fasFile.canWrite()) {
        fasFile = new File(System.getProperty("java.io.tmpdir"), fileName);
    }
    marshaller.marshal(fileAccessState, fasFile);

    return fasFile;
}

From source file:labr_client.xml.ObjToXML.java

public static String marshallRequest(LabrRequest request) {
    String xml = "";
    String date = String.format("%1$tY%1$tm%1$td", new Date());
    String time = String.format("%1$tH%1$tM%1$tS", new Date());
    try {/*from  ww  w  . ja  v a2  s  .  co m*/
        JAXBContext context = JAXBContext.newInstance(LabrRequest.class);
        Marshaller m = context.createMarshaller();
        //for pretty-print XML in JAXB
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        File labrRequest = new File("data/tmp/" + date + time + ".xml");
        m.marshal(request, labrRequest);
        xml = FileUtils.readFileToString(labrRequest);

    } catch (JAXBException | IOException ex) {
        Logger.getLogger(ObjToXML.class.getName()).log(Level.SEVERE, null, ex);
    }
    return xml;
}

From source file:labr_client.xml.ObjToXML.java

public static String marshallRequest(KmehrMessage message) {
    String xml = "";
    String date = String.format("%1$tY%1$tm%1$td", new Date());
    String time = String.format("%1$tH%1$tM%1$tS", new Date());
    try {/* w  w w  . j  a  v  a 2s .c  o  m*/
        JAXBContext context = JAXBContext.newInstance(LabrRequest.class);
        Marshaller m = context.createMarshaller();
        //for pretty-print XML in JAXB
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        File kmehrMessage = new File("data/tmp/kmehr" + date + time + ".xml");
        m.marshal(message, kmehrMessage);
        xml = FileUtils.readFileToString(kmehrMessage);

    } catch (JAXBException | IOException ex) {
        Logger.getLogger(ObjToXML.class.getName()).log(Level.SEVERE, null, ex);
    }
    return xml;
}