Example usage for javax.xml.stream XMLEventWriter add

List of usage examples for javax.xml.stream XMLEventWriter add

Introduction

In this page you can find the example usage for javax.xml.stream XMLEventWriter add.

Prototype


public void add(XMLEventReader reader) throws XMLStreamException;

Source Link

Document

Adds an entire stream to an output stream, calls next() on the inputStream argument until hasNext() returns false This should be treated as a convenience method that will perform the following loop over all the events in an event reader and call add on each event.

Usage

From source file:eu.delving.sip.xml.SourceConverter.java

public void parse(InputStream inputStream, OutputStream outputStream, Map<String, String> namespaces)
        throws StorageException {
    progressListener.prepareFor(totalRecords);
    //        anonymousRecords = Integer.parseInt(System.getProperty(ANONYMOUS_RECORDS_PROPERTY, "0"));
    Path path = Path.create();
    try {/*from   w  ww  .j  av a2  s  . com*/
        XMLEventReader in = inputFactory.createXMLEventReader(new StreamSource(inputStream, "UTF-8"));
        XMLEventWriter out = outputFactory.createXMLEventWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        processEvents: while (!finished) {
            XMLEvent event = in.nextEvent();
            switch (event.getEventType()) {
            case XMLEvent.START_DOCUMENT:
                out.add(eventFactory.createStartDocument());
                out.add(eventFactory.createCharacters("\n"));
                List<Namespace> nslist = new ArrayList<Namespace>();
                for (Map.Entry<String, String> entry : namespaces.entrySet()) {
                    if (entry.getKey().isEmpty() || entry.getValue().trim().isEmpty())
                        continue;
                    if (XSI_SCHEMA.equals(entry.getValue()))
                        continue;
                    nslist.add(eventFactory.createNamespace(entry.getKey(), entry.getValue()));
                }
                out.add(eventFactory.createStartElement("", "", ENVELOPE_TAG, null, nslist.iterator()));
                out.add(eventFactory.createCharacters("\n"));
                break;
            case XMLEvent.START_ELEMENT:
                boolean followsStart = start != null;
                start = event.asStartElement();
                if (linesAvailable()) {
                    eventBuffer.add(eventFactory.createCharacters("\n"));
                    eventBuffer.add(eventFactory.createStartElement("", "", TEXT_TAG, null, null));
                    Iterator<String> walk = lines.iterator();
                    while (walk.hasNext()) {
                        eventBuffer.add(eventFactory.createCharacters(walk.next()));
                        if (walk.hasNext()) {
                            eventBuffer.add(eventFactory.createEndElement("", "", TEXT_TAG));
                            eventBuffer.add(eventFactory.createCharacters("\n"));
                            eventBuffer.add(eventFactory.createStartElement("", "", TEXT_TAG, null, null));
                        }
                    }
                    eventBuffer.add(eventFactory.createEndElement("", "", TEXT_TAG));
                    lines.clear();
                }
                path = path.child(Tag.element(start.getName()));
                handleStartElement(path, followsStart);
                progressListener.setProgress(recordCount);
                break;
            case XMLEvent.END_ELEMENT:
                EndElement end = event.asEndElement();
                if (recordEvents) {
                    if (path.equals(recordRootPath)) {
                        if (unique != null) {
                            outputRecord(out);
                            recordCount++;
                        } else {
                            clearEvents();
                        }
                    } else {
                        if (!uniqueElementPath.peek().isAttribute() && path.equals(uniqueElementPath)) {
                            unique = StringUtils.join(lines, "");
                        }
                        boolean addEndTag = true;
                        if (linesAvailable()) {
                            Iterator<String> walk = lines.iterator();
                            while (walk.hasNext()) {
                                eventBuffer.add(eventFactory.createCharacters(walk.next()));
                                if (walk.hasNext()) {
                                    eventBuffer.add(end);
                                    eventBuffer.add(eventFactory.createCharacters("\n"));
                                    handleStartElement(path, false);
                                }
                            }
                        } else {
                            if (eventBuffer.get(eventBuffer.size() - 1).isStartElement()) {
                                eventBuffer.remove(eventBuffer.size() - 1); // remove the start event
                                addEndTag = false;
                            }
                        }
                        lines.clear();
                        if (addEndTag) {
                            eventBuffer.add(end);
                            eventBuffer.add(eventFactory.createCharacters("\n"));
                        }
                    }
                }
                start = null;
                path = path.parent();
                break;
            case XMLEvent.END_DOCUMENT:
                out.add(eventFactory.createEndElement("", "", ENVELOPE_TAG));
                out.add(eventFactory.createCharacters("\n"));
                out.add(eventFactory.createEndDocument());
                out.flush();
                break processEvents;
            case XMLEvent.CHARACTERS:
            case XMLEvent.CDATA:
                if (recordEvents)
                    extractLines(event.asCharacters().getData());
                break;
            }
        }
    } catch (CancelException e) {
        throw new StorageException("Cancelled", e);
    } catch (StorageException e) {
        throw e;
    } catch (Exception e) {
        throw new StorageException("Storage problem", e);
    } finally {
        if (uniqueRepeatCount > 0) {
            progressListener.getFeedback().alert(String.format("Uniqueness violations : " + uniqueRepeatCount));
        }
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
}

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

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    OutputStream docOS = null;//from ww  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(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:cz.zcu.kiv.eegdatabase.logic.controller.article.ArticleMultiController.java

private void createNode(XMLEventWriter eventWriter, String name, String value) {
    try {/*from   ww w  .  j a v  a 2  s .co m*/
        XMLEventFactory eventFactory = XMLEventFactory.newInstance();
        XMLEvent end = eventFactory.createDTD("\n");
        XMLEvent tab = eventFactory.createDTD("\t");
        // Create Start node
        StartElement sElement = eventFactory.createStartElement("", "", name);
        eventWriter.add(tab);
        eventWriter.add(sElement);
        // Create Content
        Characters characters = eventFactory.createCharacters(value);
        eventWriter.add(characters);
        // Create End node
        EndElement eElement = eventFactory.createEndElement("", "", name);
        eventWriter.add(eElement);
        eventWriter.add(end);
    } catch (Exception e) {
    }
}

From source file:eu.delving.sip.xml.SourceConverter.java

private void outputRecord(XMLEventWriter out) throws StorageException {
    //        if (anonymousRecords == 0 || recordCount < anonymousRecords) {
    String uniqueValue = getUniqueValue();
    if (!uniqueValue.isEmpty()) {
        if (uniqueness.contains(uniqueValue)) {
            uniqueRepeatCount++;//from w ww .  j  a v a 2 s  . c o  m
        } else {
            uniqueness.add(uniqueValue);
            Attribute id = eventFactory.createAttribute(Storage.UNIQUE_ATTR, uniqueValue);
            unique = null;
            List<Attribute> attrs = new ArrayList<Attribute>();
            attrs.add(id);
            try {
                out.add(eventFactory.createStartElement("", "", RECORD_TAG, attrs.iterator(), null));
                for (XMLEvent bufferedEvent : eventBuffer)
                    out.add(bufferedEvent);
                out.add(eventFactory.createEndElement("", "", RECORD_TAG));
                out.add(eventFactory.createCharacters("\n"));
            } catch (XMLStreamException e) {
                throw new StorageException("Problem writing XML", e);
            }
        }
    }
    //        }
    clearEvents();
}

From source file:org.javelin.sws.ext.bind.internal.model.AttributePattern.java

@Override
protected void replayNonNullString(String value, XMLEventWriter eventWriter, MarshallingContext context)
        throws XMLStreamException {
    if (!XMLConstants.NULL_NS_URI.equals(this.attributeName.getNamespaceURI())) {
        // we MUST create second namespace declaration if the current one has default ("") prefix, otherwise the attribute will have absent
        // namespace!
        // see: http://www.w3.org/TR/xml-names11/#defaulting - "The namespace name for an unprefixed attribute name always has no value."
        String prefix = this.safeRegisterNamespace(context, eventWriter, this.attributeName);
        if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) {
            Namespace namespace = this.safePrepareNamespace(
                    context, eventWriter, new QName(this.attributeName.getNamespaceURI(),
                            this.attributeName.getLocalPart(), context.newPrefix()),
                    NamespaceRegistration.IF_DEFAULT_PREFIX);
            prefix = namespace.getPrefix();
        }/* w  w  w . j av a 2s . c  o  m*/
        eventWriter.add(XML_EVENTS_FACTORY.createAttribute(prefix, this.attributeName.getNamespaceURI(),
                this.attributeName.getLocalPart(), value));
    } else {
        // attribute is unqalified and has no namespace
        eventWriter.add(XML_EVENTS_FACTORY.createAttribute(this.attributeName.getLocalPart(), value));
    }
}

From source file:sapience.injectors.stax.inject.ModelBasedStaxStreamInjector.java

/**
 * If the reference is more then a simple attribute, we have to add new XML (subtree) to the stream. We transform
 * the reference into an InputStream and invoke another SAX parsing process for it. But the parsed events are added
 * to the main XMLEventWriter. /*w w  w.j  a  v a  2s. c o  m*/
 *
 * @param w
 * @param string
 * @throws XMLStreamException 
 * @throws XMLStreamException
 */
private void createEventsForElement(XMLEventWriter w, Reference ref) throws XMLStreamException {
    XMLEventReader r = null;
    try {
        StringBuilder target = new StringBuilder(ref.getTarget().toString());

        NamespaceContext c = w.getNamespaceContext();

        ByteArrayInputStream bais = new ByteArrayInputStream(target.toString().getBytes());
        getXMLInputFactory().setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
        r = getXMLInputFactory().createXMLEventReader(bais);

        while (r.hasNext()) {
            XMLEvent e = r.nextEvent();
            switch (e.getEventType()) {
            case XMLEvent.START_DOCUMENT:
                break;
            case XMLEvent.END_DOCUMENT:
                break;
            default:
                w.add(e);
                break;
            }
        }
    } finally {
        ;

        if (r != null)
            r.close();
    }

}

From source file:com.predic8.membrane.core.multipart.XOPReconstitutor.java

private byte[] fillInXOPParts(InputStream inputStream, HashMap<String, Part> parts)
        throws XMLStreamException, FactoryConfigurationError {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(baos);

    try {//from  www . ja  v a  2s. c  o  m
        XMLEventReader parser = createEventReaderFromStream(inputStream);

        boolean xopIncludeOpen = false;

        while (parser.hasNext()) {
            XMLEvent event = parser.nextEvent();

            if (event instanceof StartElement) {
                StartElement start = (StartElement) event;
                if (XOP_NAMESPACE_URI.equals(start.getName().getNamespaceURI())
                        && start.getName().getLocalPart().equals("Include")) {
                    String href = start.getAttributeByName(new QName("href")).getValue();

                    if (href.startsWith("cid:"))
                        href = href.substring(4);

                    Part p = parts.get("<" + href + ">");
                    if (p == null)
                        throw new RuntimeException("Did not find multipart with id " + href);

                    writer.add(p.asXMLEvent());
                    xopIncludeOpen = true;
                    continue;
                }
            } else if (event instanceof EndElement) {
                EndElement start = (EndElement) event;
                if (XOP_NAMESPACE_URI.equals(start.getName().getNamespaceURI())
                        && start.getName().getLocalPart().equals("Include") && xopIncludeOpen) {
                    xopIncludeOpen = false;
                    continue;
                }
            }

            writer.add(event);
        }
        writer.flush();
    } catch (XMLStreamException e) {
        log.warn("Received not-wellformed XML.");
        return null;
    }
    return baos.toByteArray();
}

From source file:org.javelin.sws.ext.bind.internal.model.ElementPattern.java

@Override
public void replay(Object object, XMLEventWriter eventWriter, MarshallingContext context)
        throws XMLStreamException {
    // <elementName>
    StartElement startElement = this.safeCreateElement(context, eventWriter, this.elementName);

    boolean isNil = false;
    if (object instanceof JAXBElement) {
        // is it xsi:nil?
        if (((JAXBElement<?>) object).isNil())
            isNil = true;/*  w w  w  .  j  a  v  a 2s .c  om*/
        // dereference marshalled value
        object = ((JAXBElement<?>) object).getValue();
    } else if (object == null) {
        isNil = true;
    }

    // TODO: defer writing xsi:type for multiRefs
    // TODO: move safeGetQValue() and safeRegisterNamespace() out of this hierarchy into helper class
    if (context.isSendTypes()/* || TODO: must send xsi:type anyway*/) {
        String qValue = this.safeGetQValue(context, eventWriter, this.nestedPattern.getSchemaType());
        String prefix = this.safeRegisterNamespace(context, eventWriter, SweJaxbConstants.XSI_TYPE);
        eventWriter.add(XML_EVENTS_FACTORY.createAttribute(prefix, SweJaxbConstants.XSI_TYPE.getNamespaceURI(),
                SweJaxbConstants.XSI_TYPE.getLocalPart(), qValue));
    }

    if (isNil) {
        String prefix = this.safeRegisterNamespace(context, eventWriter, SweJaxbConstants.XSI_NIL);
        eventWriter.add(XML_EVENTS_FACTORY.createAttribute(prefix, SweJaxbConstants.XSI_NIL.getNamespaceURI(),
                SweJaxbConstants.XSI_NIL.getLocalPart(), "true"));
    } else {
        for (QName ns : this.nestedPattern.getNamespacesToRegister()) {
            this.safeRegisterNamespace(context, eventWriter, ns);
        }

        if (context.isMultiRefEncoding()) {
            // choices:
            // - marshal SimpleContentPattern.INSTANCE pattern "inline" or as @href?
            // - marshal single references "inline" or as @href to multiRef? - requires deferred marshalling to see wether there will more references
            // to this value
            // - add xsi:type?

            // the "href" attribute should be unqualified
            // TODO: what about @href attributes inside elements in default, non-empty namespace? Like: <a xmlns="b" href="#1" />...

            context.getMultiRefSupport().registerMultiRef(object, eventWriter, this.nestedPattern);
        } else {
            // inline children/attribute information items
            this.nestedPattern.replay(object, eventWriter, context);
        }
    }

    // </elementName>
    eventWriter.add(XML_EVENTS_FACTORY.createEndElement(startElement.getName(), null));
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

public InputStream addAtomInlinecount(final InputStream feed, final int count, final Accept accept)
        throws Exception {
    final XMLEventReader reader = getEventReader(feed);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    final XMLEventWriter writer = xof.createXMLEventWriter(bos);

    try {/*from  w  ww.  j  av a2 s .  c  o  m*/

        final XmlElement feedElement = getAtomElement(reader, writer, "feed");

        writer.add(feedElement.getStart());
        addAtomElement(IOUtils.toInputStream(String.format("<m:count>%d</m:count>", count)), writer);
        writer.add(feedElement.getContentReader());
        writer.add(feedElement.getEnd());

        while (reader.hasNext()) {
            writer.add(reader.nextEvent());
        }

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

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

From source file:com.github.lindenb.jvarkit.tools.blast.BlastFilterJS.java

@Override
protected Collection<Throwable> call(String inputName) throws Exception {

    final CompiledScript compiledScript;
    Unmarshaller unmarshaller;/*from w ww .  ja  v  a2 s. c o  m*/
    Marshaller marshaller;
    try {
        compiledScript = super.compileJavascript();

        JAXBContext jc = JAXBContext.newInstance("gov.nih.nlm.ncbi.blast");

        unmarshaller = jc.createUnmarshaller();
        marshaller = jc.createMarshaller();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        PrintWriter pw = openFileOrStdoutAsPrintWriter();
        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
        XMLEventWriter w = xof.createXMLEventWriter(pw);

        StreamSource src = null;
        if (inputName == null) {
            LOG.info("Reading stdin");
            src = new StreamSource(stdin());
        } else {
            LOG.info("Reading file " + inputName);
            src = new StreamSource(new File(inputName));
        }

        XMLEventReader r = xmlInputFactory.createXMLEventReader(src);

        XMLEventFactory eventFactory = XMLEventFactory.newFactory();

        SimpleBindings bindings = new SimpleBindings();
        while (r.hasNext()) {
            XMLEvent evt = r.peek();
            switch (evt.getEventType()) {
            case XMLEvent.START_ELEMENT: {
                StartElement sE = evt.asStartElement();
                Hit hit = null;
                JAXBElement<Hit> jaxbElement = null;
                if (sE.getName().getLocalPart().equals("Hit")) {
                    jaxbElement = unmarshaller.unmarshal(r, Hit.class);
                    hit = jaxbElement.getValue();
                } else {
                    w.add(r.nextEvent());
                    break;
                }

                if (hit != null) {

                    bindings.put("hit", hit);

                    boolean accept = super.evalJavaScriptBoolean(compiledScript, bindings);

                    if (accept) {
                        marshaller.marshal(jaxbElement, w);
                        w.add(eventFactory.createCharacters("\n"));
                    }
                }

                break;
            }
            case XMLEvent.SPACE:
                break;
            default: {
                w.add(r.nextEvent());
                break;
            }
            }
            r.close();
        }
        w.flush();
        w.close();
        pw.flush();
        pw.close();
        return RETURN_OK;
    } catch (Exception err) {
        return wrapException(err);
    } finally {

    }
}