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.netflix.subtitles.ttml.TtmlParagraphResolver.java

private static <T> T deepCopy(T object, Class<T> clazz, String packages) {
    try {/*from w  w  w .j  a  v  a2s  . c  o  m*/
        JAXBContext jaxbContext = JAXBContext.newInstance(packages);

        //  create marshaller which disable validation step
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setEventHandler(event -> true);

        //  create unmarshaller which disable validation step
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setEventHandler(event -> true);

        JAXBElement<T> contentObject = new JAXBElement<>(new QName(clazz.getName()), clazz, object);
        return unmarshaller.unmarshal(new JAXBSource(marshaller, contentObject), clazz).getValue();
    } catch (JAXBException e) {
        throw new ParseException("Time overlaps in <p> cannot be resolved.", e);
    }
}

From source file:com.mymita.vaadlets.JAXBUtils.java

private static final void marshal(final Writer aWriter, final Vaadlets vaadlets,
        final Resource theSchemaResource) {
    try {//from www  .j a  v  a  2  s.  co  m
        final JAXBContext jc = JAXBContext.newInstance(CONTEXTPATH);
        final Marshaller marshaller = jc.createMarshaller();
        if (theSchemaResource != null) {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new ClasspathResourceResolver());
            final Schema schema = schemaFactory.newSchema(new StreamSource(theSchemaResource.getInputStream()));
            marshaller.setSchema(schema);
        }
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",
                new com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper() {

                    @Override
                    public String getPreferredPrefix(final String namespaceUri, final String suggestion,
                            final boolean requirePrefix) {
                        final String subpackage = namespaceUri.replaceFirst("http://www.mymita.com/vaadlets/",
                                "");
                        if (subpackage.equals("1.0.0")) {
                            return "";
                        }
                        return Iterables.getFirst(newArrayList(Splitter.on("/").split(subpackage).iterator()),
                                "");
                    }
                });
        marshaller.marshal(
                new JAXBElement<Vaadlets>(new QName("http://www.mymita.com/vaadlets/1.0.0", "vaadlets", ""),
                        Vaadlets.class, vaadlets),
                aWriter);
    } catch (final JAXBException | SAXException | FactoryConfigurationError | IOException e) {
        throw new RuntimeException("Can't marschal", e);
    }
}

From source file:at.ac.tuwien.dsg.comot.m.common.Utils.java

public static String asJsonString(Object obj, Class<?>... clazz) throws JAXBException {

    List<Object> list = new ArrayList<Object>(Arrays.asList(clazz));
    list.add(obj.getClass());/*from  w w w  .j  ava  2 s . co  m*/

    StringWriter w = new StringWriter();

    Map<String, Object> props = new HashMap<String, Object>();
    // props.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
    props.put(JAXBContextProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);

    JAXBContext context = JAXBContextFactory.createContext(list.toArray(new Class[list.size()]), props);

    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(obj, w);

    return w.toString();
}

From source file:com.faceye.feature.util.JaxbMapper.java

/**
 * Marshallerencoding(?null).// w ww .ja v  a  2 s  .com
 * ???pooling
 */
public static Marshaller createMarshaller(Class clazz, String encoding) {
    try {
        JAXBContext jaxbContext = getJaxbContext(clazz);

        Marshaller marshaller = jaxbContext.createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        if (StringUtils.isNotBlank(encoding)) {
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
        }
        //         marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "");
        //         marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "");

        //         marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {
        //                @Override
        //                public String[] getPreDeclaredNamespaceUris() {
        //                    return new String[] { WellKnownNamespace.XML_SCHEMA_INSTANCE };
        //                }
        //
        //                @Override
        //                public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
        //                    if (namespaceUri.equals(WellKnownNamespace.XML_SCHEMA_INSTANCE))
        //                        return "xsi";
        //                    if (namespaceUri.equals(WellKnownNamespace.XML_SCHEMA))
        //                        return "xs";
        //                    if (namespaceUri.equals(WellKnownNamespace.XML_MIME_URI))
        //                        return "xmime";
        //                    return suggestion;
        //
        //                }
        //            });

        return marshaller;
    } catch (JAXBException e) {
        logger.error(">>FaceYe form xml 2 class exception:", e);
        throw Exceptions.unchecked(e);
    }
}

From source file:eu.seaclouds.platform.planner.core.application.agreements.AgreementGenerator.java

private static String serializeToXml(MonitoringInfo monitoringInfo) {
    StringWriter sw = new StringWriter();
    JAXBContext jaxbContext;
    String marshalledMonitoringRules = null;
    try {/*  w  w w .j  av a  2s.c o  m*/
        jaxbContext = JAXBContext.newInstance(MonitoringRules.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        jaxbMarshaller.marshal(monitoringInfo.getApplicationMonitoringRules(), sw);
        marshalledMonitoringRules = sw.toString();
    } catch (JAXBException e) {
        log.error("Monitoring rules {} can not be marshalled by addSeaCloudsPolicy in " + "DamGenerator",
                monitoringInfo.getApplicationMonitoringRules());
    }

    return marshalledMonitoringRules;
}

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  a v  a 2s  .c  o 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:cz.lbenda.dataman.rc.DbConfigFactory.java

public static String storeToString(Callback<DbConfig, String> cacheDbStructureWriteFactory) {
    cz.lbenda.dataman.schema.dataman.ObjectFactory of = new cz.lbenda.dataman.schema.dataman.ObjectFactory();
    DatamanType config = of.createDatamanType();
    config.setSessions(of.createSessionsType());

    for (DbConfig sc : getConfigurations()) {
        config.getSessions().getSession()
                .add(sc.storeToSessionType(null, cacheDbStructureWriteFactory.call(sc)));
    }//w w  w .j ava 2  s  .c  o m

    try {
        JAXBContext jc = JAXBContext.newInstance(cz.lbenda.dataman.schema.dataman.ObjectFactory.class);
        Marshaller m = jc.createMarshaller();
        StringWriter sw = new StringWriter();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.marshal(of.createDataman(config), 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:com.bluexml.side.build.tools.reader.MavenProjectReader.java

/**
 * @return//from   ww w .  j av a 2s .  c  om
 * @throws JAXBException
 * @throws PropertyException
 */

private static Unmarshaller getUnmarshaller(String packageName) throws JAXBException, PropertyException {
    JAXBContext jaxbContext = JAXBContext.newInstance(packageName);

    Marshaller alfrescoMarshaller = jaxbContext.createMarshaller();
    alfrescoMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    alfrescoMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    Unmarshaller alfrescoUnmarshaller = jaxbContext.createUnmarshaller();

    return alfrescoUnmarshaller;
}

From source file:Main.java

/**
 * Generic method to Validate XML file while marshalling against their schema.
 * /*www  .j a  v  a2 s.  co 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:Main.java

/**
 * Generic method to Validate XML file while marshalling against their schema.
 * /* ww w .  j  a va 2s.com*/
 * @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);
    QName qname = new QName("www.genpact.com", "CobCmData");
    marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "www.genpact.com cob_cm.xsd ");
    //         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

    //         JAXBElement<CobCmData> rootElement = new JAXBElement<CobCmData>(qname,CobCmData.class,(CobCmData)object);
    //         marshaller.marshal(rootElement, sos);  
    //         xmlFormOfBean = sos.toString();

    //      }
    return xmlFormOfBean;
}