Example usage for javax.xml.stream XMLEventFactory newInstance

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

Introduction

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

Prototype

public static XMLEventFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

From source file:org.apache.olingo.fit.utils.XMLUtilities.java

/**
 * {@inheritDoc }//  w w  w .  ja  v a2 s .  c o  m
 */
@Override
protected InputStream addLinks(final String entitySetName, final String entitykey, final InputStream is,
        final Set<String> links) throws Exception {

    // -----------------------------------------
    // 0. Build reader and writer
    // -----------------------------------------
    final XMLEventReader reader = getEventReader(is);
    final XMLEventFactory eventFactory = XMLEventFactory.newInstance();

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);
    // -----------------------------------------
    final Map.Entry<Integer, XMLElement> entry = extractElement(reader, writer,
            Collections.singletonList("entry"), 0, 1, 1);

    writer.add(entry.getValue().getStart());

    final Map<String, NavigationProperty> navigationProperties = metadata
            .getNavigationProperties(entitySetName);

    // add for links
    for (String link : links) {
        final Set<Attribute> attributes = new HashSet<Attribute>();
        attributes.add(eventFactory.createAttribute(new QName("title"), link));
        attributes.add(eventFactory.createAttribute(new QName("href"),
                Commons.getLinksURI(entitySetName, entitykey, link)));
        attributes.add(eventFactory.createAttribute(new QName("rel"),
                Constants.get(ConstantKey.ATOM_LINK_REL) + link));
        attributes.add(eventFactory.createAttribute(new QName("type"),
                navigationProperties.get(link).isEntitySet() ? Constants.get(ConstantKey.ATOM_LINK_FEED)
                        : Constants.get(ConstantKey.ATOM_LINK_ENTRY)));

        writer.add(eventFactory.createStartElement(new QName(Constants.get(ConstantKey.LINK)),
                attributes.iterator(), null));
        writer.add(eventFactory.createEndElement(new QName(Constants.get(ConstantKey.LINK)), null));
    }

    writer.add(entry.getValue().getContentReader());
    writer.add(entry.getValue().getEnd());
    writer.add(reader);
    IOUtils.closeQuietly(is);

    writer.flush();
    writer.close();
    reader.close();

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:org.apache.olingo.fit.utils.XMLUtilities.java

@Override
protected InputStream replaceLink(final InputStream toBeChanged, final String linkName,
        final InputStream replacement) throws Exception {
    final XMLEventReader reader = getEventReader(toBeChanged);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    final XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent newLine = eventFactory.createSpace("\n");

    try {//from  w  w w . j  a va2  s  . c  o  m
        final XMLElement linkElement = extractElement(reader, writer,
                Collections.<String>singletonList(Constants.get(ConstantKey.LINK)),
                Collections.<Map.Entry<String, String>>singletonList(
                        new SimpleEntry<String, String>("title", linkName)),
                false, 0, -1, -1).getValue();
        writer.add(linkElement.getStart());

        // ------------------------------------------
        // write inline ...
        // ------------------------------------------
        writer.add(newLine);
        writer.add(eventFactory.createStartElement("m", null, "inline"));

        addAtomElement(replacement, writer);

        writer.add(eventFactory.createEndElement("m", null, "inline"));
        writer.add(newLine);
        // ------------------------------------------

        writer.add(linkElement.getEnd());

        writer.add(reader);
        writer.flush();
        writer.close();
    } finally {
        reader.close();
        IOUtils.closeQuietly(toBeChanged);
    }

    return new ByteArrayInputStream(bos.toByteArray());
}

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();//w w w .  ja  va2s.com
            } 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   www  .ja  v  a2s .  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;//  w ww . j a va 2s . c  om
    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.emonocot.job.io.StaxEventItemWriter.java

/**
 * Writes simple XML header containing://from w w w.  ja  va2 s.  c om
 * <ul>
 * <li>xml declaration - defines encoding and XML version</li>
 * <li>opening tag of the root element and its attributes</li>
 * </ul>
 * If this is not sufficient for you, simply override this method. Encoding,
 * version and root tag name can be retrieved with corresponding getters.
 *
 * @param writer
 *            XML event writer
 * @throws XMLStreamException if there is a problem starting the document
 */
protected final void startDocument(final XMLEventWriter writer) throws XMLStreamException {

    XMLEventFactory factory = XMLEventFactory.newInstance();

    // write start document
    writer.add(factory.createStartDocument(getEncoding(), getVersion()));

    // write root tag
    writer.add(
            factory.createStartElement(getRootTagNamespacePrefix(), getRootTagNamespace(), getRootTagName()));
    if (StringUtils.hasText(getRootTagNamespace())) {
        if (StringUtils.hasText(getRootTagNamespacePrefix())) {
            writer.add(factory.createNamespace(getRootTagNamespacePrefix(), getRootTagNamespace()));
        } else {
            writer.add(factory.createNamespace(getRootTagNamespace()));
        }
    }

    // write root tag attributes
    if (!CollectionUtils.isEmpty(getRootElementAttributes())) {

        for (Map.Entry<String, String> entry : getRootElementAttributes().entrySet()) {
            String key = entry.getKey();
            if (key.startsWith("xmlns")) {
                String prefix = "";
                if (key.contains(":")) {
                    prefix = key.substring(key.indexOf(":") + 1);
                }
                writer.add(factory.createNamespace(prefix, entry.getValue()));
            } else {
                writer.add(factory.createAttribute(key, entry.getValue()));
            }
        }

    }

    /*
     * This forces the flush to write the end of the root element and avoids
     * an off-by-one error on restart.
     */
    writer.add(factory.createIgnorableSpace(""));
    writer.flush();

}

From source file:org.emonocot.job.io.StaxEventItemWriter.java

/**
 * Flush and close the output source.// w  w  w.j a  v  a2  s  .  c  o m
 *
 * @see org.springframework.batch.item.ItemStream#close()
 */
public final void close() {

    // harmless event to close the root tag if there were no items
    XMLEventFactory factory = XMLEventFactory.newInstance();
    try {
        delegateEventWriter.add(factory.createCharacters(""));
    } catch (XMLStreamException e) {
        log.error(e);
    }

    try {
        if (footerCallback != null) {
            footerCallback.write(delegateEventWriter);
        }
        delegateEventWriter.flush();
        endDocument(delegateEventWriter);
    } catch (IOException e) {
        throw new ItemStreamException("Failed to write footer items", e);
    } catch (XMLStreamException e) {
        throw new ItemStreamException("Failed to write end document tag", e);
    } finally {

        try {
            eventWriter.close();
        } catch (XMLStreamException e) {
            log.error("Unable to close file resource: [" + resource + "] " + e);
        } finally {
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                log.error("Unable to close file resource: [" + resource + "] " + e);
            } finally {
                if (!transactional) {
                    closeStream();
                }
            }
        }
    }
}

From source file:org.mule.transport.sap.transformer.JcoFunctionToXmlTransformer.java

/**
 * Describe <code>transform</code> method here.
 *
 * @param obj an <code>Object</code> value
 * @return an <code>Object</code> value
 * @exception XMLStreamException if an error occurs
 */// w  w  w.  j  a  v  a  2 s  .co m
public Object transform(Object obj, String encoding) throws XMLStreamException {
    // getting JCoFunction object
    JCoFunction function = (JCoFunction) obj;

    factory = XMLOutputFactory.newInstance();
    eventFactory = XMLEventFactory.newInstance();

    StringWriter stringWriter = new StringWriter();

    String result = null;

    try {
        // getting instance of writer
        writer = factory.createXMLEventWriter(stringWriter);

        // writing start document

        writeStartDocument(writer);

        // writing JCO start element

        writeCharacters(writer, "\n");
        writeStartElement(writer, MessageConstants.JCO);

        // writing NAME
        writeAttribute(writer, MessageConstants.JCO_ATTR_NAME, function.getName());

        // writing TIMESTAMP
        writeAttribute(writer, MessageConstants.JCO_ATTR_TIMESTAMP, String.valueOf(new Date().getTime()));

        // writing VERSION
        writeAttribute(writer, MessageConstants.JCO_ATTR_VERSION, MessageConstants.JCO_ATTR_VERSION_VALUE);

        // writing Import

        writeCharacters(writer, "\n");
        writeImportElement(writer, function);

        // writing Export
        writeCharacters(writer, "\n  ");
        writeExportElement(writer, function);

        // writing Tables

        writeCharacters(writer, "\n");
        writeTablesElement(writer, function);

        // writing Errors

        writeCharacters(writer, "\n  ");

        writeErrorElement(writer, function.getExceptionList());

        // writing JCO end element
        writeEndElement(writer, MessageConstants.JCO);

        // close document

        writeEndDocument(writer);
        writer.flush();

        result = stringWriter.toString();

    } catch (XMLStreamException ex) {
        throw ex;
    } finally {
        // close
        if (writer != null) {
            try {
                writer.close();
            } catch (XMLStreamException ex) {
            }
        }
        if (stringWriter != null) {
            try {
                stringWriter.close();
            } catch (IOException ex) {
            }
        }
    }
    return result;
}

From source file:org.springframework.batch.item.xml.builder.StaxEventItemWriterBuilderTests.java

@Test
public void testConfiguration() throws Exception {
    Map<String, String> rootElementAttributes = new HashMap<>();
    rootElementAttributes.put("baz", "quix");

    StaxEventItemWriter<Foo> staxEventItemWriter = new StaxEventItemWriterBuilder<Foo>().name("fooWriter")
            .marshaller(marshaller).encoding("UTF-16").footerCallback(writer -> {
                XMLEventFactory factory = XMLEventFactory.newInstance();
                try {
                    writer.add(factory.createEndElement("ns", "http://www.springframework.org/test", "group"));
                } catch (XMLStreamException e) {
                    throw new RuntimeException(e);
                }// w  w w  . ja v a  2 s . co m
            }).headerCallback(writer -> {
                XMLEventFactory factory = XMLEventFactory.newInstance();
                try {
                    writer.add(
                            factory.createStartElement("ns", "http://www.springframework.org/test", "group"));
                } catch (XMLStreamException e) {
                    throw new RuntimeException(e);
                }
            }).resource(this.resource).rootTagName("foobarred").rootElementAttributes(rootElementAttributes)
            .saveState(false).version("1.1").build();

    staxEventItemWriter.afterPropertiesSet();

    ExecutionContext executionContext = new ExecutionContext();
    staxEventItemWriter.open(executionContext);

    staxEventItemWriter.write(this.items);

    staxEventItemWriter.update(executionContext);
    staxEventItemWriter.close();

    assertEquals(FULL_OUTPUT, getOutputFileContent("UTF-16"));
    assertEquals(0, executionContext.size());
}

From source file:org.springframework.batch.item.xml.StaxEventItemWriter.java

/**
 * Subclasses can override to customize the event factory.
 * @return a factory for the xml events/* w  w  w. j  a  va 2  s .c o m*/
 * @throws FactoryConfigurationError
 */
protected XMLEventFactory createXmlEventFactory() throws FactoryConfigurationError {
    XMLEventFactory factory = XMLEventFactory.newInstance();
    return factory;
}