Example usage for javax.xml.bind Marshaller JAXB_FRAGMENT

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

Introduction

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

Prototype

String JAXB_FRAGMENT

To view the source code for javax.xml.bind Marshaller JAXB_FRAGMENT.

Click Source Link

Document

The name of the property used to specify whether or not the marshaller will generate document level events (ie calling startDocument or endDocument).

Usage

From source file:org.dkpro.core.io.xces.XcesBasicXmlWriter.java

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    OutputStream docOS = null;/* w  ww  . jav a 2s.  c om*/
    try {
        docOS = getOutputStream(aJCas, filenameSuffix);
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        XMLEventWriter xmlEventWriter = new IndentingXMLEventWriter(
                xmlOutputFactory.createXMLEventWriter(docOS));
        JAXBContext context = JAXBContext.newInstance(XcesBodyBasic.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        XMLEventFactory xmlef = XMLEventFactory.newInstance();
        xmlEventWriter.add(xmlef.createStartDocument());
        // Begin cesDoc
        xmlEventWriter.add(xmlef.createStartElement("", "", "cesDoc"));
        // Begin and End cesHeader
        xmlEventWriter.add(xmlef.createStartElement("", "", "cesHeader"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "cesHeader"));

        // Begin text and body
        xmlEventWriter.add(xmlef.createStartElement("", "", "text"));
        // xmlEventWriter.add(xmlef.createStartElement("", "", "body"));

        // Begin body of all the paragraphs            
        Collection<Paragraph> parasInCas = JCasUtil.select(aJCas, Paragraph.class);
        XcesBodyBasic xb = convertToXcesBasicPara(parasInCas);
        marshaller.marshal(new JAXBElement<XcesBodyBasic>(new QName("body"), XcesBodyBasic.class, xb),
                xmlEventWriter);
        // End body of all the paragraphs
        // xmlEventWriter.add(xmlef.createEndElement("", "", "body"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "text"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "cesDoc"));
        xmlEventWriter.add(xmlef.createEndDocument());
    } catch (Exception e) {
        throw new AnalysisEngineProcessException(e);
    } finally {
        closeQuietly(docOS);
    }

}

From source file:org.dkpro.core.io.xces.XcesXmlWriter.java

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    OutputStream docOS = null;//from w w  w .  j av a2  s  .c  o  m
    try {
        docOS = getOutputStream(aJCas, filenameSuffix);
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        XMLEventWriter xmlEventWriter = new IndentingXMLEventWriter(
                xmlOutputFactory.createXMLEventWriter(docOS));
        JAXBContext context = JAXBContext.newInstance(XcesBody.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        XMLEventFactory xmlef = XMLEventFactory.newInstance();
        xmlEventWriter.add(xmlef.createStartDocument());
        // Begin cesDoc
        xmlEventWriter.add(xmlef.createStartElement("", "", "cesDoc"));
        // Begin and End cesHeader
        xmlEventWriter.add(xmlef.createStartElement("", "", "cesHeader"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "cesHeader"));

        // Begin text and body
        xmlEventWriter.add(xmlef.createStartElement("", "", "text"));
        // xmlEventWriter.add(xmlef.createStartElement("", "", "body"));

        // Begin body of all the paragraphs            
        Collection<Paragraph> parasInCas = JCasUtil.select(aJCas, Paragraph.class);
        XcesBody xb = convertToXcesPara(parasInCas);
        marshaller.marshal(new JAXBElement<XcesBody>(new QName("body"), XcesBody.class, xb), xmlEventWriter);
        // End body of all the paragraphs
        // xmlEventWriter.add(xmlef.createEndElement("", "", "body"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "text"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "cesDoc"));
        xmlEventWriter.add(xmlef.createEndDocument());
    } catch (Exception e) {
        throw new AnalysisEngineProcessException(e);
    } finally {
        closeQuietly(docOS);
    }

}

From source file:org.docx4j.XmlUtils.java

/** Marshal to a String */
public static String marshaltoString(Object o, boolean suppressDeclaration, boolean prettyprint,
        JAXBContext jc) {//from  w w  w. j a  v a  2s.c o m

    /* http://weblogs.java.net/blog/kohsuke/archive/2005/10/101_ways_to_mar.html
     * 
     * If you are writing to a file, a socket, or memory, then you should use
     * the version that takes OutputStream. Unless you change the target 
     * encoding to something else (default is UTF-8), there's a special 
     * marshaller codepath for OutputStream, which makes it run really fast.
     * You also don't have to use BufferedOutputStream, since the JAXB RI 
     * does the adequate buffering.
     * 
     * You can also write to Writer, but in this case you'll be responsible 
     * for encoding characters, so in general you need to be careful. If 
     * you want to marshal XML into an encoding other than UTF-8, it's best
     *  to use the JAXB_ENCODING property and then write to OutputStream, 
     *  as it escapes characters to things like &#x1824; correctly. 
     */

    if (o == null) {
        return null;
    }

    try {
        Marshaller m = jc.createMarshaller();
        NamespacePrefixMapperUtils.setProperty(m, NamespacePrefixMapperUtils.getPrefixMapper());
        String ignorables = setMcIgnorable(
                ((McIgnorableNamespaceDeclarator) NamespacePrefixMapperUtils.getPrefixMapper()), o);

        if (prettyprint) {
            m.setProperty("jaxb.formatted.output", true);
        }

        /* Fix for:
         *       <t tstamp='1198193417585' snum='1' op='update'>
         * ~~~~~~~>   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
         *             <ns1:sdt xmlns:ns1="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
         *                <ns1:sdtPr><ns1:id ns1:val="1814108031"/><ns1:tag ns1:val="1"/></ns1:sdtPr><ns1:sdtContent><ns1:p><ns1:r><ns1:t>Lookin</ns1:t></ns1:r><ns1:r><ns1:t> pretty</ns1:t></ns1:r></ns1:p></ns1:sdtContent></ns1:sdt></t>
         */

        /* http://weblogs.java.net/blog/kohsuke/archive/2005/10/101_ways_to_mar.html
         * 
         * JAXB_FRAGMENT prevents the marshaller from producing an XML declaration, 
         * so the above works just fine. The downside of this approach is that if 
         * the ancestor elements declare the namespaces, JAXB won't be able to take 
         * advantage of them.
         */

        if (suppressDeclaration) {
            m.setProperty(Marshaller.JAXB_FRAGMENT, true);
        }

        if (Docx4jProperties.getProperty("docx4j.jaxb.marshal.canonicalize", false)) {

            org.w3c.dom.Document doc = marshaltoW3CDomDocument(o, jc); // TODO rest of 
            byte[] bytes = trimNamespaces(doc, ignorables);

            return new String(bytes, "UTF-8");

        } else {
            StringWriter sWriter = new StringWriter();
            m.marshal(o, sWriter);
            return sWriter.toString();
        }

        /*          Alternative implementation
                 
                 java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();         
                 marshaller.marshal(o, out);         
                  byte[] bytes = out.toByteArray();
                  return new String(bytes);
         */

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.docx4j.XmlUtils.java

/** Marshal to a String, for object
 *  missing an @XmlRootElement annotation.  */
public static String marshaltoString(Object o, boolean suppressDeclaration, boolean prettyprint, JAXBContext jc,
        String uri, String local, Class declaredType) {
    // TODO - refactor this.
    try {/*  w  ww . j a v a  2  s.c om*/

        Marshaller m = jc.createMarshaller();
        NamespacePrefixMapperUtils.setProperty(m, NamespacePrefixMapperUtils.getPrefixMapper());
        String ignorables = setMcIgnorable(
                ((McIgnorableNamespaceDeclarator) NamespacePrefixMapperUtils.getPrefixMapper()), o);

        if (prettyprint) {
            m.setProperty("jaxb.formatted.output", true);
        }

        if (suppressDeclaration) {
            m.setProperty(Marshaller.JAXB_FRAGMENT, true);
        }

        if (Docx4jProperties.getProperty("docx4j.jaxb.marshal.canonicalize", false)) {

            org.w3c.dom.Document doc = marshaltoW3CDomDocument(o, jc, uri, local, declaredType);
            byte[] bytes = trimNamespaces(doc, ignorables);

            return new String(bytes, "UTF-8");

        } else {

            StringWriter sWriter = new StringWriter();

            m.marshal(new JAXBElement(new QName(uri, local), declaredType, o), sWriter);

            return sWriter.toString();
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.docx4j.XmlUtils.java

public static java.io.InputStream marshaltoInputStream(Object o, boolean suppressDeclaration, JAXBContext jc) {

    /* http://weblogs.java.net/blog/kohsuke/archive/2005/10/101_ways_to_mar.html
     * /*  w  w  w .j a  v  a  2 s  .c  om*/
     * If you are writing to a file, a socket, or memory, then you should use
     * the version that takes OutputStream. Unless you change the target 
     * encoding to something else (default is UTF-8), there's a special 
     * marshaller codepath for OutputStream, which makes it run really fast.
     * You also don't have to use BufferedOutputStream, since the JAXB RI 
     * does the adequate buffering.
     * 
     */

    try {
        Marshaller m = jc.createMarshaller();
        NamespacePrefixMapperUtils.setProperty(m, NamespacePrefixMapperUtils.getPrefixMapper());
        String ignorables = setMcIgnorable(
                ((McIgnorableNamespaceDeclarator) NamespacePrefixMapperUtils.getPrefixMapper()), o);

        if (suppressDeclaration) {
            m.setProperty(Marshaller.JAXB_FRAGMENT, true);
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        m.marshal(o, os);

        if (Docx4jProperties.getProperty("docx4j.jaxb.marshal.canonicalize", false)) {

            org.w3c.dom.Document doc = marshaltoW3CDomDocument(o, jc);
            byte[] bytes = trimNamespaces(doc, ignorables);
            return new java.io.ByteArrayInputStream(bytes);

        } else {
            // Now copy from the outputstream to inputstream
            // See http://ostermiller.org/convert_java_outputstream_inputstream.html

            return new java.io.ByteArrayInputStream(os.toByteArray());
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.winery.common.Util.java

/**
 * Method similar to {@link//from  w  ww  .j a  v  a 2  s  . c o  m
 * org.eclipse.winery.repository.Utils.getXMLAsString(Class, Object)}.
 * 
 * Differences:
 * <ul>
 * <li>XML processing instruction is not included in the header</li>
 * <li>JAXBcontext is created at each call</li>
 * </ul>
 */
public static <T extends Object> String getXMLAsString(Class<T> clazz, T obj) throws Exception {
    // copied from Utils java, but we create an own JAXBcontext here
    // JAXBSupport cannot be used as this relies on a MockElement, which we do not want to factor out to winery.common

    JAXBContext context;
    try {
        // For winery classes, eventually the package+jaxb.index method could be better. See http://stackoverflow.com/a/3628525/873282
        // @formatter:off
        context = JAXBContext.newInstance(TEntityType.class);
        // @formatter:on
    } catch (JAXBException e) {
        throw new IllegalStateException(e);
    }

    JAXBElement<T> rootElement = Util.getJAXBElement(clazz, obj);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.setProperty(Marshaller.JAXB_FRAGMENT, true);
    // m.setProperty("com.sun.xml.bind.namespacePrefixMapper", JAXBSupport.prefixMapper);

    StringWriter w = new StringWriter();
    try {
        m.marshal(rootElement, w);
    } catch (JAXBException e) {
        throw new IllegalStateException(e);
    }
    String res = w.toString();
    return res;
}

From source file:org.eclipse.winery.repository.JAXBSupport.java

/**
 * Creates a marshaller./*from www.  j a v a  2  s. c  om*/
 *
 * IMPORTANT: always create a new instance and do not reuse the marhaller, otherwise the input-stream will throw a
 * NullPointerException! see https://stackoverflow.com/questions/11114665/org-xml-sax-saxparseexception-premature-end-of-file-for-valid-xml
 *
 * @throws IllegalStateException if marshaller could not be instantiated
 */
public static Marshaller createMarshaller(boolean includeProcessingInstruction) {
    Marshaller m;
    try {
        m = JAXBSupport.context.createMarshaller();
        // pretty printed output is required as the XML is sent 1:1 to the browser for editing
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        try {
            m.setProperty("com.sun.xml.bind.namespacePrefixMapper", JAXBSupport.prefixMapper);
        } catch (PropertyException e) {
            // Namespace-Prefixing is not supported by the used Provider. Nothing we can do about that
        }
        if (!includeProcessingInstruction) {
            // side effect of JAXB_FRAGMENT property (when true): processing instruction is not included
            m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        }
    } catch (JAXBException e) {
        JAXBSupport.LOGGER.error("Could not instantiate marshaller", e);
        throw new IllegalStateException(e);
    }

    return m;
}

From source file:org.netbeans.jbatch.modeler.specification.model.job.util.JobUtil.java

public void saveModelerFile(ModelerFile modelerFile) {

    Definitions definitions = (Definitions) modelerFile.getDefinitionElement();

    try {//from  ww  w. j  a  v a 2  s. c  o m
        updateBatchDiagram(modelerFile);
        List<String> closeDefinitionIdList = closeDiagram(modelerFile, definitions.getGarbageDefinitions());
        List<String> definitionIdList = new ArrayList<String>(closeDefinitionIdList);
        //            definitionIdList.addAll(definitions.getGarbageDefinitions());
        definitionIdList.add(definitions.getId());
        File savedFile = modelerFile.getFile();

        BufferedReader br = new BufferedReader(new FileReader(savedFile));
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println("savedFile : " + line);
        }

        File cloneSavedFile = File.createTempFile("TMP", "job");
        FileUtils.copyFile(savedFile, cloneSavedFile);
        //            br = new BufferedReader(new FileReader(cloneSavedFile));
        //            line = null;
        //            while ((line = br.readLine()) != null) {
        //                System.out.println("line2 : " + line);
        //            }

        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        XMLStreamWriter xsw = xof.createXMLStreamWriter(new FileWriter(savedFile));
        xsw.setDefaultNamespace("http://jbatchsuite.java.net");

        xsw.writeStartDocument();
        xsw.writeStartElement("jbatchnb", "root", "http://jbatchsuite.java.net");
        xsw.writeNamespace("jbatch", "http://xmlns.jcp.org/xml/ns/javaee");
        xsw.writeNamespace("jbatchnb", "http://jbatchsuite.java.net");
        xsw.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xsw.writeNamespace("java", "http://jcp.org/en/jsr/detail?id=270");
        xsw.writeNamespace("nbm", "http://nbmodeler.java.net");

        //            br = new BufferedReader(new FileReader(savedFile));
        //            line = null;
        //            while ((line = br.readLine()) != null) {
        //                System.out.println("line3 : " + line);
        //            }
        if (cloneSavedFile.length() != 0) {
            try {
                XMLInputFactory xif = XMLInputFactory.newFactory();
                StreamSource xml = new StreamSource(cloneSavedFile);
                XMLStreamReader xsr = xif.createXMLStreamReader(xml);
                xsr.nextTag();
                while (xsr.getEventType() == XMLStreamConstants.START_ELEMENT) {
                    //                        Def   Y    N
                    //                        Tag   N(D) Y(D)
                    //                        ________________
                    //                              T    T
                    //                        ----------------
                    //
                    //                        Def   Y    N
                    //                        Tag   Y(S) N(S)
                    //                        ________________
                    //                              S    S
                    //                        ----------------
                    //
                    //                        Def   Y    N
                    //                        Tag   Y(D) N(S)
                    //                        ________________
                    //                              T    S
                    //                        ----------------
                    //
                    //                       (D) => Different
                    //                       (S) => Same
                    //                        Y => Id Exist
                    //                        N => Id is null
                    //                        T => Transform
                    //                        S => Skip

                    if (xsr.getLocalName().equals("definitions")) {
                        //                            if (definitions.getId() == null) {
                        //                                if (xsr.getAttributeValue(null, "id") != null) {
                        //                                    transformXMLStream(xsr, xsw);
                        //                                } else {
                        //                                    skipXMLStream(xsr);
                        //                                }
                        //                            } else {
                        if (xsr.getAttributeValue(null, "id") == null) {
                            if (definitions.getId() == null) {
                                skipXMLStream(xsr);
                            } else {
                                transformXMLStream(xsr, xsw);
                            }
                        } else {
                            if (!definitionIdList.contains(xsr.getAttributeValue(null, "id"))) {
                                transformXMLStream(xsr, xsw);
                            } else {
                                skipXMLStream(xsr);
                            }
                        }
                        //                            }
                    }
                    xsr.nextTag();
                }
            } catch (XMLStreamException ex) {
                Exceptions.printStackTrace(ex);
            }
        }

        JAXBElement<Definitions> je = new JAXBElement<Definitions>(
                new QName("http://jbatchsuite.java.net", "definitions", "jbatchnb"), Definitions.class,
                definitions);
        if (jobContext == null) {
            jobContext = JAXBContext.newInstance(new Class<?>[] { ShapeDesign.class, Definitions.class });
        }
        if (jobMarshaller == null) {
            jobMarshaller = jobContext.createMarshaller();
        }

        // output pretty printed
        jobMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jobMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        //          jobMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.omg.org/spec/Batch/20100524/MODEL http://www.omg.org/spec/Batch/2.0/20100501/Batch20.xsd");
        jobMarshaller.setEventHandler(new ValidateJAXB());
        jobMarshaller.marshal(je, System.out);
        jobMarshaller.marshal(je, xsw);

        //            xsw.writeEndElement();
        xsw.writeEndDocument();
        xsw.close();

        //            StringWriter sw = new StringWriter();
        //            jobMarshaller.marshal(file.getDefinitionElement(), sw);
        //            FileUtils.writeStringToFile(savedFile, sw.toString().replaceFirst("xmlns:ns[A-Za-z\\d]{0,3}=\"http://www.omg.org/spec/Batch/20100524/MODEL\"",
        //                    "xmlns=\"http://www.omg.org/spec/Batch/20100524/MODEL\""));
    } catch (JAXBException ex) {
        Exceptions.printStackTrace(ex);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } catch (XMLStreamException ex) {
        Exceptions.printStackTrace(ex);
    }

}

From source file:org.openengsb.connector.promreport.internal.ProcessFileStore.java

private Marshaller createMarshaller() throws JAXBException {
    Marshaller m = jaxbContext.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.setProperty(Marshaller.JAXB_FRAGMENT, true);
    m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    m.setSchema(schema);/*from   w ww .j  a v a  2s  .  c  om*/
    return m;
}

From source file:org.openhealthtools.openatna.jaxb21.JaxbIOFactory.java

public void write(AtnaMessage message, OutputStream out, boolean includeDeclaration) throws AtnaException {
    if (jc == null) {
        throw new AtnaException("Could not create Jaxb Context");
    }/*from w  w  w  .ja  va2s . c  om*/
    if (message.getEventDateTime() == null) {
        message.setEventDateTime(new Date());
    }
    try {
        AuditMessage jmessage = createMessage(message);
        Marshaller marshaller = jc.createMarshaller();
        if (!includeDeclaration) {
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        }
        marshaller.marshal(jmessage, out);
        if (log.isDebugEnabled()) {
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            marshaller.marshal(jmessage, bout);
            log.debug("Written Audit Message:\n" + new String(bout.toByteArray()));
        }

    } catch (JAXBException e) {
        throw new AtnaException(e);
    }
}