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:Main.java

public static String bean2Xml(Object bean) {
    String xmlString = null;/*from w w  w. j  a v a  2s.  c om*/
    JAXBContext context;
    StringWriter writer;
    if (null == bean)
        return xmlString;
    try {
        context = JAXBContext.newInstance(bean.getClass());
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);//
        //m.setProperty(Marshaller.JAXB_ENCODING, "gb2312");//
        //m.setProperty(Marshaller.JAXB_ENCODING, "GBK");//
        m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");//
        m.setProperty(Marshaller.JAXB_FRAGMENT, false);//
        writer = new StringWriter();
        m.marshal(bean, writer);
        xmlString = writer.toString();
        return xmlString;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return xmlString;
}

From source file:Main.java

public static String bean2Xml(Object bean, String codetype) {
    String xmlString = null;/*from  w  ww. j a va2 s  . co  m*/
    JAXBContext context;
    StringWriter writer;
    if (null == bean)
        return xmlString;
    try {
        context = JAXBContext.newInstance(bean.getClass());
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);//
        // m.setProperty(Marshaller.JAXB_ENCODING, "gb2312");//
        // m.setProperty(Marshaller.JAXB_ENCODING, "GBK");//
        m.setProperty(Marshaller.JAXB_ENCODING, codetype);//
        m.setProperty(Marshaller.JAXB_FRAGMENT, false);//
        writer = new StringWriter();
        m.marshal(bean, writer);
        xmlString = writer.toString();
        return xmlString;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return xmlString;
}

From source file:Main.java

/**
 * Marshal a JAXB element to a XML DOM document
 *
 * @param jaxbElement//from   w  ww.  j ava2s .  co  m
 *            The root of content tree to be marshalled
 * @return XML DOM document
 * @throws Exception
 *             in error case
 */
public static Document doMarshallingJAXBObject(Object jaxbElement) throws Exception {
    if (jaxbElement == null) {
        throw new RuntimeException("No JAXB element to marshal (null)!");
    }
    Document doc = null;
    try {
        JAXBContext jaxbCtx = JAXBContext.newInstance(jaxbElement.getClass().getPackage().getName());
        Marshaller marshaller = jaxbCtx.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); // NOI18N
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.newDocument();
        marshaller.marshal(jaxbElement, doc);
        doc.getDocumentElement().normalize();
    } catch (Exception e) {
        //            Logger.XMLEval.logState("Marshalling failed: " + e.getMessage(), LogLevel.Error);
        throw e;
    }

    return doc;
}

From source file:Main.java

/**
 * Generic method to Validate XML file while marshalling against their schema.
 * //from w w w  . j a v  a 2s.  c  o  m
 * @param context
 * @param schemaFile
 * @param object
 * @return
 * @throws SAXException
 * @throws JAXBException
 */
public static String validateAndMarshallXML(JAXBContext context, String schemaFile, Object object)
        throws SAXException, JAXBException {
    String xmlFormOfBean = null;

    if (context != null && (schemaFile != null && schemaFile.trim().length() > 0)) {
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // thread- safe 
        marshaller.setSchema(sf.newSchema(new File(schemaFile))); // validate jaxb context against schema 
        ByteArrayOutputStream sos = new ByteArrayOutputStream(); // for XML output into string

        marshaller.marshal(object, sos);
        xmlFormOfBean = sos.toString();

    }
    return xmlFormOfBean;
}

From source file:org.eclipse.winery.topologymodeler.addons.topologycompleter.helper.JAXBHelper.java

/**
 * Marshalls a JAXB object of the TOSCA model to an XML string.
 *
 * @param clazz//  www .j  a  v  a 2  s .  co m
 *           the class of the object
 * @param obj
 *           the object to be marshalled
 *
 * @return
 */
public static String getXMLAsString(@SuppressWarnings("rawtypes") Class clazz, Object obj) {
    try {
        @SuppressWarnings("rawtypes")
        JAXBElement rootElement = Util.getJAXBElement(clazz, obj);
        JAXBContext context = JAXBContext.newInstance(TDefinitions.class);
        Marshaller m;

        m = context.createMarshaller();

        StringWriter w = new StringWriter();
        m.marshal(rootElement, w);
        String res = w.toString();

        return res;
    } catch (JAXBException e) {
        logger.error(e.getLocalizedMessage());
    }
    return null;
}

From source file:com.labs64.utils.swid.support.JAXBUtils.java

/**
 * Write XML entity to the given destination.
 * /*from   w  w w.  ja  v a 2  s . c o  m*/
 * @param entity
 *            XML entity
 * @param destination
 *            destination to write to. Supported destinations: {@link java.io.OutputStream}, {@link java.io.File},
 *            {@link java.io.Writer}
 * @param comment
 *            optional comment which will be added at the begining of the generated XML
 * @throws IllegalArgumentException
 * @throws SwidException
 * @param <T>
 *            JAXB entity
 */
public static <T> void writeObject(final T entity, final Object destination, final String comment) {
    try {
        JAXBContext jaxbContext;
        if (entity instanceof JAXBElement) {
            jaxbContext = JAXBContext.newInstance(((JAXBElement) entity).getValue().getClass());
        } else {
            jaxbContext = JAXBContext.newInstance(entity.getClass());
        }

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        if (StringUtils.isNotBlank(comment)) {
            marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", comment);
        }

        if (destination instanceof java.io.OutputStream) {
            marshaller.marshal(entity, (OutputStream) destination);
        } else if (destination instanceof java.io.File) {
            marshaller.marshal(entity, (java.io.File) destination);
        } else if (destination instanceof java.io.Writer) {
            marshaller.marshal(entity, (java.io.Writer) destination);
        } else {
            throw new IllegalArgumentException("Unsupported destination.");
        }
    } catch (final JAXBException e) {
        throw new SwidException("Cannot write object.", e);
    }
}

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 source file:eu.modaclouds.sla.mediator.Utils.java

public static <E> void print(E e, OutputStream os, Class<?>... classesToBeBound) throws JAXBException {
    JAXBContext jaxbContext;/*w ww  . j  av a 2s. c o  m*/
    Marshaller jaxbMarshaller;
    jaxbContext = JAXBContext.newInstance(classesToBeBound);
    jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    /*
     * http://stackoverflow.com/a/22756191
     */
    jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
    jaxbMarshaller.marshal(e, os);
}

From source file:cz.lbenda.dataman.rc.DbConfigFactory.java

public static String storeStructureCache(DbConfig dbConfig) {
    cz.lbenda.dataman.schema.dbstructure.ObjectFactory of = new cz.lbenda.dataman.schema.dbstructure.ObjectFactory();
    try {/*from w  w w  .j av  a2  s.  co m*/
        JAXBContext jc = JAXBContext.newInstance(cz.lbenda.dataman.schema.dbstructure.ObjectFactory.class);
        Marshaller m = jc.createMarshaller();
        StringWriter sw = new StringWriter();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        DatabaseStructureType dst = DbStructureFactory.createXMLDatabaseStructure(dbConfig.getCatalogs());
        JAXBElement<DatabaseStructureType> element = of.createDatabaseType(dst);
        m.marshal(element, sw);
        return sw.toString();
    } catch (JAXBException e) {
        LOG.error("Problem with write configuration: " + e.toString(), e);
        throw new RuntimeException("Problem with write configuration: " + e.toString(), e);
    }
}

From source file:org.pmedv.jake.JakeUtil.java

/**
 * Updates the {@link RecentFileList} with a new file
 * //from   ww w .  jav  a  2 s .c  o m
 * @param filename the name to append to the list
 */
public static void updateRecentFiles(String filename) {

    RecentFileList fileList = null;

    try {

        String inputDir = System.getProperty("user.home") + "/." + AppContext.getName() + "/";
        String inputFileName = "recentFiles.xml";
        File inputFile = new File(inputDir + inputFileName);

        if (inputFile.exists()) {
            Unmarshaller u = JAXBContext.newInstance(RecentFileList.class).createUnmarshaller();
            fileList = (RecentFileList) u.unmarshal(inputFile);
        }

        if (fileList == null)
            fileList = new RecentFileList();

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

    if (fileList.getRecentFiles().size() >= 5) {
        fileList.getRecentFiles().remove(0);
    }

    if (!fileList.getRecentFiles().contains(filename))
        fileList.getRecentFiles().add(filename);

    Marshaller m;

    try {
        String outputDir = System.getProperty("user.home") + "/." + AppContext.getName() + "/";
        String outputFileName = "recentFiles.xml";
        m = JAXBContext.newInstance(RecentFileList.class).createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        File output = new File(outputDir + outputFileName);
        m.marshal(fileList, output);
    } catch (JAXBException e) {
        e.printStackTrace();
    }
}