Example usage for javax.xml.stream XMLEventFactory createStartDocument

List of usage examples for javax.xml.stream XMLEventFactory createStartDocument

Introduction

In this page you can find the example usage for javax.xml.stream XMLEventFactory createStartDocument.

Prototype

public abstract StartDocument createStartDocument();

Source Link

Document

Creates a new instance of a StartDocument event

Usage

From source file:de.tudarmstadt.ukp.dkpro.core.io.tiger.TigerXmlWriter.java

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    OutputStream docOS = null;/*from  w  w w .j  a  va2 s  .c  o  m*/
    try {
        docOS = getOutputStream(aJCas, filenameSuffix);

        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        XMLEventWriter xmlEventWriter = new IndentingXMLEventWriter(
                xmlOutputFactory.createXMLEventWriter(docOS));

        JAXBContext context = JAXBContext.newInstance(TigerSentence.class);
        Marshaller marshaller = context.createMarshaller();
        // We use the marshaller only for individual sentences. That way, we do not have to 
        // build the whole TIGER object graph before seralizing, which should safe us some
        // memory.
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        XMLEventFactory xmlef = XMLEventFactory.newInstance();
        xmlEventWriter.add(xmlef.createStartDocument());
        xmlEventWriter.add(xmlef.createStartElement("", "", "corpus"));
        xmlEventWriter.add(xmlef.createStartElement("", "", "body"));

        int sentenceNumber = 1;
        for (Sentence s : select(aJCas, Sentence.class)) {
            TigerSentence ts = convertSentence(s, sentenceNumber);
            marshaller.marshal(new JAXBElement<TigerSentence>(new QName("s"), TigerSentence.class, ts),
                    xmlEventWriter);
            sentenceNumber++;
        }

        xmlEventWriter.add(xmlef.createEndElement("", "", "body"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "corpus"));
        xmlEventWriter.add(xmlef.createEndDocument());
    } catch (Exception e) {
        throw new AnalysisEngineProcessException(e);
    } finally {
        closeQuietly(docOS);
    }
}

From source file:com.gtwm.pb.model.manageData.DataManagement.java

/**
 * Based on http://www.vogella.de/articles/RSSFeed/article.html
 *///www .j ava  2s. c  om
private String generateRSS(AppUserInfo user, BaseReportInfo report, List<DataRowInfo> reportDataRows)
        throws XMLStreamException, ObjectNotFoundException {
    // Create a XMLOutputFactory
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    // Create XMLEventWriter
    StringWriter stringWriter = new StringWriter();
    XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(stringWriter);
    // Create a EventFactory
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent end = eventFactory.createDTD("\n");
    // Create and write Start Tag
    StartDocument startDocument = eventFactory.createStartDocument();
    eventWriter.add(startDocument);
    // Create open tag
    eventWriter.add(end);
    StartElement rssStart = eventFactory.createStartElement("", "", "rss");
    eventWriter.add(rssStart);
    eventWriter.add(eventFactory.createAttribute("version", "2.0"));
    eventWriter.add(end);
    eventWriter.add(eventFactory.createStartElement("", "", "channel"));
    eventWriter.add(end);
    // Write the different nodes
    this.createNode(eventWriter, "title", report.getModule().getModuleName() + " - " + report.getReportName());
    // TODO: Don't hard code host part of URL
    String reportLink = "https://appserver.gtportalbase.com/agileBase/AppController.servlet?return=gui/display_application&set_table="
            + report.getParentTable().getInternalTableName() + "&set_report=" + report.getInternalReportName();
    this.createNode(eventWriter, "link", reportLink);
    this.createNode(eventWriter, "description", "A live data feed from www.agilebase.co.uk");
    DateFormat dateFormatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
    Date lastDataChangeDate = new Date(getLastCompanyDataChangeTime(user.getCompany()));
    this.createNode(eventWriter, "pubdate", dateFormatter.format(lastDataChangeDate));
    for (DataRowInfo reportDataRow : reportDataRows) {
        eventWriter.add(eventFactory.createStartElement("", "", "item"));
        eventWriter.add(end);
        this.createNode(eventWriter, "title", buildEventTitle(report, reportDataRow, false));
        this.createNode(eventWriter, "description", reportDataRow.toString());
        String rowLink = reportLink + "&set_row_id=" + reportDataRow.getRowId();
        this.createNode(eventWriter, "link", rowLink);
        this.createNode(eventWriter, "guid", rowLink);
        eventWriter.add(end);
        eventWriter.add(eventFactory.createEndElement("", "", "item"));
        eventWriter.add(end);
    }
    eventWriter.add(eventFactory.createEndElement("", "", "channel"));
    eventWriter.add(end);
    eventWriter.add(eventFactory.createEndElement("", "", "rss"));
    eventWriter.add(end);
    return stringWriter.toString();
}

From source file:org.callimachusproject.behaviours.ZipArchiveSupport.java

public XMLEventReader createAtomFeedFromArchive(final String id, final String entryPattern) throws IOException {
    final FileObject file = this;
    final XMLEventFactory ef = XMLEventFactory.newInstance();
    final byte[] buf = new byte[1024];
    final ZipArchiveInputStream zip = new ZipArchiveInputStream(file.openInputStream());
    return new XMLEventReaderBase() {
        private boolean started;
        private boolean ended;

        public void close() throws XMLStreamException {
            try {
                zip.close();//from   w ww  .j a v a  2 s. co m
            } catch (IOException e) {
                throw new XMLStreamException(e);
            }
        }

        protected boolean more() throws XMLStreamException {
            try {
                ZipArchiveEntry entry;
                if (!started) {
                    Namespace atom = ef.createNamespace(FEED.getPrefix(), FEED.getNamespaceURI());
                    add(ef.createStartDocument());
                    add(ef.createStartElement(FEED, null, Arrays.asList(atom).iterator()));
                    add(ef.createStartElement(TITLE, null, null));
                    add(ef.createCharacters(file.getName()));
                    add(ef.createEndElement(TITLE, null));
                    add(ef.createStartElement(ID, null, null));
                    add(ef.createCharacters(id));
                    add(ef.createEndElement(ID, null));
                    Attribute href = ef.createAttribute("href", file.toUri().toASCIIString());
                    List<Attribute> attrs = Arrays.asList(href, ef.createAttribute("type", "application/zip"));
                    add(ef.createStartElement(LINK, attrs.iterator(), null));
                    add(ef.createEndElement(LINK, null));
                    add(ef.createStartElement(UPDATED, null, null));
                    add(ef.createCharacters(format(new Date(file.getLastModified()))));
                    add(ef.createEndElement(UPDATED, null));
                    started = true;
                    return true;
                } else if (started && !ended && (entry = zip.getNextZipEntry()) != null) {
                    String name = entry.getName();
                    String link = entryPattern.replace("{entry}", PercentCodec.encode(name));
                    MimetypesFileTypeMap mimetypes = new javax.activation.MimetypesFileTypeMap();
                    String type = mimetypes.getContentType(name);
                    if (type == null || type.length() == 0) {
                        type = "application/octet-stream";
                    }
                    add(ef.createStartElement(ENTRY, null, null));
                    add(ef.createStartElement(TITLE, null, null));
                    add(ef.createCharacters(name));
                    add(ef.createEndElement(TITLE, null));
                    Attribute href = ef.createAttribute("href", link);
                    List<Attribute> attrs = Arrays.asList(href, ef.createAttribute("type", type));
                    add(ef.createStartElement(LINK, attrs.iterator(), null));
                    add(ef.createEndElement(LINK, null));
                    long size = entry.getSize();
                    if (size > 0) {
                        zip.skip(size);
                    } else {
                        while (zip.read(buf, 0, buf.length) >= 0)
                            ;
                    }
                    add(ef.createEndElement(ENTRY, null));
                    return true;
                } else if (!ended) {
                    add(ef.createEndElement(FEED, null));
                    add(ef.createEndDocument());
                    ended = true;
                    return true;
                } else {
                    return false;
                }
            } catch (IOException e) {
                throw new XMLStreamException(e);
            }
        }
    };
}

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

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    OutputStream docOS = null;//from   w w  w  .j  a v  a2 s  .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  a  2s . 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.omnaest.utils.xml.XMLNestedMapConverter.java

/**
 * @param nestedMap/* w w  w . ja v a  2  s. c om*/
 *          {@link Map}
 * @param outputStream
 *          {@link OutputStream}
 * @param includeDocumentHeader
 *          if true a xml document header is written out additionally
 */
private <K> void toXML(Map<K, Object> nestedMap, OutputStream outputStream,
        final ElementConverter<K, QName> keyElementConverter, boolean includeDocumentHeader) {
    //
    if (nestedMap != null && keyElementConverter != null && outputStream != null) {
        //
        try {
            //
            final XMLOutputFactory xmlOutputFactory = this.xmlInstanceContextFactory.newXmlOutputFactory();
            final XMLEventFactory xmlEventFactory = this.xmlInstanceContextFactory.newXmlEventFactory();
            Assert.isNotNull(xmlOutputFactory, "xmlOutputFactory must not be null");
            Assert.isNotNull(xmlEventFactory, "xmlEventFactory must not be null");

            //
            final XMLEventWriter xmlEventWriter = xmlOutputFactory.createXMLEventWriter(outputStream,
                    this.encoding);
            final ExceptionHandler exceptionHandler = this.exceptionHandler;

            //
            try {
                //
                class Helper {
                    /* ********************************************** Variables ********************************************** */
                    private List<String> namespaceStack = new ArrayList<String>();

                    /* ********************************************** Methods ********************************************** */

                    @SuppressWarnings("unchecked")
                    public void write(Map<K, Object> map) {
                        if (map != null) {
                            for (K key : map.keySet()) {
                                //
                                final QName tagName = keyElementConverter.convert(key);
                                final Object value = map.get(key);

                                //
                                if (value instanceof String) {
                                    //
                                    this.writeStartTag(tagName);

                                    //
                                    final String text = (String) value;
                                    this.writeText(text);

                                    //
                                    this.writeEndTag(tagName);
                                } else if (value instanceof Map) {
                                    //
                                    this.writeStartTag(tagName);

                                    //
                                    final Map<K, Object> subMap = (Map<K, Object>) value;
                                    this.write(subMap);

                                    //
                                    this.writeEndTag(tagName);
                                } else if (value instanceof List) {
                                    //
                                    final List<Object> valueList = (List<Object>) value;
                                    this.write(tagName, valueList);
                                }
                            }
                        }
                    }

                    /**
                     * @param tagName
                     */
                    private void writeStartTag(QName tagName) {
                        //
                        try {
                            //
                            final String namespaceURI = tagName.getNamespaceURI();

                            //            
                            final Iterator<?> attributes = null;
                            final Iterator<?> namespaces = StringUtils.isNotBlank(namespaceURI) && !StringUtils
                                    .equals(namespaceURI, ListUtils.lastElement(this.namespaceStack))
                                            ? IteratorUtils.valueOf(
                                                    xmlEventFactory.createNamespace(namespaceURI))
                                            : null;
                            StartElement startElement = xmlEventFactory.createStartElement(tagName, attributes,
                                    namespaces);
                            xmlEventWriter.add(startElement);

                            //
                            this.namespaceStack.add(namespaceURI);
                        } catch (Exception e) {
                            exceptionHandler.handleException(e);
                        }
                    }

                    /**
                     * @param tagName
                     */
                    private void writeEndTag(QName tagName) {
                        //
                        try {
                            //            
                            final Iterator<?> namespaces = null;
                            EndElement endElement = xmlEventFactory.createEndElement(tagName, namespaces);
                            xmlEventWriter.add(endElement);

                            //
                            ListUtils.removeLast(this.namespaceStack);
                        } catch (Exception e) {
                            exceptionHandler.handleException(e);
                        }
                    }

                    /**
                     * @param text
                     */
                    private void writeText(String text) {
                        //
                        try {
                            //            
                            final Characters characters = xmlEventFactory.createCharacters(text);
                            xmlEventWriter.add(characters);
                        } catch (Exception e) {
                            exceptionHandler.handleException(e);
                        }
                    }

                    /**
                     * @param tagName
                     * @param valueList
                     */
                    @SuppressWarnings("unchecked")
                    private void write(QName tagName, List<Object> valueList) {
                        if (valueList != null) {
                            for (Object value : valueList) {
                                //
                                if (value != null) {
                                    //
                                    this.writeStartTag(tagName);

                                    //
                                    if (value instanceof Map) {
                                        //
                                        final Map<K, Object> map = (Map<K, Object>) value;
                                        this.write(map);
                                    } else if (value instanceof String) {
                                        //
                                        final String text = (String) value;
                                        this.writeText(text);
                                    }

                                    //
                                    this.writeEndTag(tagName);
                                }
                            }
                        }
                    }
                }

                //
                if (includeDocumentHeader) {
                    xmlEventWriter.add(xmlEventFactory.createStartDocument());
                }

                //
                new Helper().write(nestedMap);

                //
                xmlEventWriter.add(xmlEventFactory.createEndDocument());
            } finally {
                xmlEventWriter.close();
                outputStream.flush();
            }
        } catch (Exception e) {
            if (this.exceptionHandler != null) {
                this.exceptionHandler.handleException(e);
            }
        }
    }
}