Example usage for javax.xml.stream XMLEventReader close

List of usage examples for javax.xml.stream XMLEventReader close

Introduction

In this page you can find the example usage for javax.xml.stream XMLEventReader close.

Prototype

public void close() throws XMLStreamException;

Source Link

Document

Frees any resources associated with this Reader.

Usage

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

@Override
public InputStream selectEntity(final InputStream entity, final String[] propertyNames) throws Exception {
    final XMLEventReader reader = getEventReader(entity);

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

    final List<String> found = new ArrayList<String>(Arrays.asList(propertyNames));

    boolean inProperties = false;
    boolean writeCurrent = true;
    Boolean writeNext = null;// ww  w  . ja v a  2  s . c  o m
    String currentName = null;

    final List<String> fieldToBeSaved = new ArrayList<String>(Arrays.asList(propertyNames));

    while (reader.hasNext()) {
        final XMLEvent event = reader.nextEvent();
        if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && Constants.get(ConstantKey.LINK).equals(event.asStartElement().getName().getLocalPart())
                && !fieldToBeSaved
                        .contains(event.asStartElement().getAttributeByName(new QName("title")).getValue())
                && !"edit".equals(event.asStartElement().getAttributeByName(new QName("rel")).getValue())) {
            writeCurrent = false;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && Constants.get(ConstantKey.LINK).equals(event.asEndElement().getName().getLocalPart())) {
            writeNext = true;
        } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && (Constants.get(ConstantKey.PROPERTIES))
                        .equals(event.asStartElement().getName().getLocalPart())) {
            writeCurrent = true;
            writeNext = false;
            inProperties = true;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && (Constants.get(ConstantKey.PROPERTIES))
                        .equals(event.asEndElement().getName().getLocalPart())) {
            writeCurrent = true;
        } else if (inProperties) {
            if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
                final String elementName = event.asStartElement().getName().getLocalPart();

                for (String propertyName : propertyNames) {
                    if ((Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + propertyName.trim())
                            .equals(elementName)) {
                        writeCurrent = true;
                        found.remove(propertyName);
                        currentName = propertyName;
                    }
                }

            } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                    && StringUtils.isNotBlank(currentName)
                    && (Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + currentName.trim())
                            .equals(event.asEndElement().getName().getLocalPart())) {
                writeNext = false;
                currentName = null;
            }

        }

        if (writeCurrent) {
            writer.add(event);
        }

        if (writeNext != null) {
            writeCurrent = writeNext;
            writeNext = null;
        }
    }

    writer.flush();
    writer.close();
    reader.close();
    IOUtils.closeQuietly(entity);

    // Do not raise any exception in order to support FC properties as well
    // if (!found.isEmpty()) {
    // throw new Exception(String.format("Could not find a properties '%s'", found));
    // }
    return new ByteArrayInputStream(bos.toByteArray());
}

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

@Override
public Map<String, InputStream> getChanges(final InputStream src) throws Exception {
    final Map<String, InputStream> res = new HashMap<String, InputStream>();

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copy(src, bos);//ww  w .j a v  a 2 s. c o m
    IOUtils.closeQuietly(src);

    // retrieve properties ...
    XMLEventReader reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

    final Map.Entry<Integer, XMLElement> propertyElement = extractElement(reader, null,
            Collections.<String>singletonList(Constants.get(ConstantKey.PROPERTIES)), 0, 2, 3);
    reader.close();

    reader = propertyElement.getValue().getContentReader();

    try {
        while (true) {
            final XMLElement property = extractElement(reader, null, null, 0, -1, -1).getValue();
            res.put(property.getStart().getName().getLocalPart(), property.toStream());
        }
    } catch (Exception ignore) {
        // end
    }

    reader.close();

    // retrieve links ...
    reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

    try {
        int pos = 0;
        while (true) {
            final Map.Entry<Integer, XMLElement> linkElement = extractElement(reader, null,
                    Collections.<String>singletonList(Constants.get(ConstantKey.LINK)), pos, 2, 2);

            res.put("[Constants.get(ConstantKey.LINK)]"
                    + linkElement.getValue().getStart().getAttributeByName(new QName("title")).getValue(),
                    linkElement.getValue().toStream());

            pos = linkElement.getKey();
        }
    } catch (Exception ignore) {
        // end
    }

    return res;
}

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 ww .ja v a  2s  .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.apache.olingo.fit.utils.XMLUtilities.java

@Override
public InputStream replaceProperty(final InputStream src, final InputStream replacement,
        final List<String> path, final boolean justValue) throws Exception {

    final List<String> pathElements = new ArrayList<String>();

    for (String element : path) {
        pathElements.add(Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + element);
    }/* ww w.ja v  a  2s .  c  o  m*/

    final XMLEventReader reader = getEventReader(src);

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

    final Map.Entry<Integer, XMLElement> element = extractElement(reader, writer, pathElements, 0, 3, 4);

    if (justValue) {
        writer.add(element.getValue().getStart());
    }

    final XMLEventReader changesReader = new XMLEventReaderWrapper(replacement);

    while (changesReader.hasNext()) {
        final XMLEvent event = changesReader.nextEvent();
        if (event.isStartElement()
                && event.asStartElement().getName().equals(element.getValue().getStart().getName())) {
            writer.add(element.getValue().getStart());
            writer.add(changesReader);
        } else {
            writer.add(event);
        }
    }

    changesReader.close();
    IOUtils.closeQuietly(replacement);

    if (justValue) {
        writer.add(element.getValue().getEnd());
    }

    writer.add(reader);

    reader.close();
    IOUtils.closeQuietly(src);

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

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

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

@Override
public InputStream deleteProperty(final InputStream src, final List<String> path) throws Exception {
    final XMLEventReader reader = getEventReader(src);

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

    final XMLEventReader changesReader = new XMLEventReaderWrapper(IOUtils.toInputStream(
            String.format("<%s m:null=\"true\" />", path.get(path.size() - 1)), Constants.ENCODING));

    writer.add(changesReader);//from   ww w . j av a 2  s .  co  m
    changesReader.close();

    writer.add(reader);

    reader.close();
    IOUtils.closeQuietly(src);

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

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

From source file:org.apache.synapse.commons.json.JsonUtil.java

/**
 * Converts an XML element to its JSON representation and writes it to an output stream.<br/>
 * Note that this method removes all existing namespace declarations and namespace prefixes of the provided XML element<br/>
 *
 * @param element      XML element of which JSON representation is expected.
 * @param outputStream Output Stream to write the JSON representation.<br/>
 *                     At the end of a successful conversion, its flush method will be called.
 * @throws AxisFault//  w  w w  . j a  va 2s.  co m
 */
public static void writeAsJson(OMElement element, OutputStream outputStream) throws AxisFault {
    XMLEventReader xmlEventReader = null;
    XMLEventWriter jsonWriter = null;
    if (element == null) {
        logger.error("#writeAsJson. OMElement is null. Cannot convert to JSON.");
        throw new AxisFault("OMElement is null. Cannot convert to JSON.");
    }
    if (outputStream == null) {
        return;
    }
    transformElement(element, true);
    try {
        org.apache.commons.io.output.ByteArrayOutputStream xmlStream = new org.apache.commons.io.output.ByteArrayOutputStream();
        element.serialize(xmlStream);
        xmlStream.flush();
        xmlEventReader = xmlInputFactory.createXMLEventReader(new XmlReaderDelegate(
                xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(xmlStream.toByteArray())),
                processNCNames));
        jsonWriter = jsonOutputFactory.createXMLEventWriter(outputStream);
        jsonWriter.add(xmlEventReader);
        outputStream.flush();
    } catch (XMLStreamException e) {
        logger.error("#writeAsJson. Could not convert OMElement to JSON. Invalid XML payload. Error>>> "
                + e.getLocalizedMessage());
        throw new AxisFault("Could not convert OMElement to JSON. Invalid XML payload.", e);
    } catch (IOException e) {
        logger.error("#writeAsJson. Could not convert OMElement to JSON. Error>>> " + e.getLocalizedMessage());
        throw new AxisFault("Could not convert OMElement to JSON.", e);
    } finally {
        if (xmlEventReader != null) {
            try {
                xmlEventReader.close();
            } catch (XMLStreamException ex) {
                //ignore
            }
        }
        if (jsonWriter != null) {
            try {
                jsonWriter.close();
            } catch (XMLStreamException ex) {
                //ignore
            }
        }
    }
}

From source file:org.dataconservancy.model.builder.WrappingEventReaderTest.java

private void commonCloseTest(XMLEventReader reader) throws XMLStreamException {
    // The input XML is EITHER:
    // <File><doc> </doc></File>
    // OR//from   ww w.  j  a va 2 s .co m
    // <dcp xmlns="http://dataconservancy.org/schemas/dcm/1.0"><Files><File><doc> </doc></File></Files></dcp>
    // This test works with either case.
    reader.nextEvent(); // START_DOC
    reader.nextEvent(); // START_ELEMENT

    reader.close(); // no-op

    reader.nextEvent(); // START_ELEMENT
}

From source file:org.omnaest.utils.xml.XMLNestedMapConverter.java

/**
 * Template method for {@link #newNamespaceAwareMapFromXML(CharSequence)} and {@link #newMapFromXML(CharSequence)} which allows
 * to convert the {@link QName} based key values to other representations.
 * /*from  www . jav  a  2s  .  c  o m*/
 * @param xmlContent
 * @return new (nested) {@link Map} instance
 */
protected <K> Map<K, Object> newMapFromXML(CharSequence xmlContent,
        final ElementConverter<QName, K> keyElementConverter) {
    //
    final Map<K, Object> retmap = new LinkedHashMap<K, Object>();

    //
    Assert.isNotNull(keyElementConverter, "keyElementConverter must not be null");

    //
    final ExceptionHandler exceptionHandler = this.exceptionHandler;

    //    
    try {
        //
        final XMLInputFactory xmlInputFactory = this.xmlInstanceContextFactory.newXmlInputFactory();
        Assert.isNotNull(xmlInputFactory, "xmlInputFactory must not be null");

        //
        final Reader reader = new CharSequenceReader(xmlContent);
        final XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(reader);

        //
        final class Helper {
            /* ********************************************** Variables ********************************************** */
            private List<TupleTwo<QName, Object>> stackList = new ArrayList<TupleTwo<QName, Object>>();

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

            /**
             * Manifests a single tag node recursively
             * 
             * @return
             * @throws XMLStreamException
             */
            @SuppressWarnings("unchecked")
            public TupleTwo<QName, Object> manifest() throws XMLStreamException {
                //
                TupleTwo<QName, Object> retval = null;

                //          
                while (xmlEventReader.hasNext()) {
                    //
                    final XMLEvent xmlEvent = xmlEventReader.nextEvent();

                    //
                    if (xmlEvent.isStartElement()) {
                        //
                        final StartElement startElement = xmlEvent.asStartElement();
                        final QName name = startElement.getName();

                        //
                        this.addNewStackElement().setValueFirst(name);

                        //
                        final Iterator<Attribute> attributeIterator = startElement.getAttributes();
                        if (attributeIterator.hasNext()) {
                            //
                            final Map<QName, Object> map = new LinkedHashMap<QName, Object>();
                            for (Attribute attribute : IterableUtils.valueOf(attributeIterator)) {
                                map.put(attribute.getName(), attribute.getValue());
                            }

                            //
                            this.updateCurrentStackValue(map);
                        }
                    } else if (xmlEvent.isEndElement()) {
                        //
                        retval = this.removeStackElement();

                        //
                        final Object manifestation = retval.getValueSecond();
                        final QName tagname = retval.getValueFirst();

                        //
                        updateCurrentStackValue(manifestation, tagname);
                    } else if (xmlEvent.isCharacters()) {
                        //
                        final Characters characters = xmlEvent.asCharacters();
                        if (!characters.isWhiteSpace()) {
                            //
                            final TupleTwo<QName, Object> currentStackValue = this.getCurrentStackValue();
                            currentStackValue.setValueSecond(
                                    ObjectUtils.defaultIfNull(currentStackValue.getValueSecond(), "")
                                            + characters.getData());

                        }
                    }

                }

                //
                return retval;
            }

            /**
             * Updates the current stack value
             * 
             * @param manifestation
             * @param tagname
             */
            private void updateCurrentStackValue(Object manifestation, QName tagname) {
                //
                final Map<QName, Object> tagNameToManifestationMap = new LinkedHashMap<QName, Object>();
                tagNameToManifestationMap.put(tagname, manifestation);
                this.updateCurrentStackValue(tagNameToManifestationMap);
            }

            @SuppressWarnings("unchecked")
            private void updateCurrentStackValue(Map<QName, Object> tagNameToManifestationMap) {
                //
                final TupleTwo<QName, Object> currentStackValue = this.getCurrentStackValue();

                //
                if (currentStackValue != null) {
                    //
                    Map<K, Object> map = null;
                    {
                        //
                        final Object valueSecond = currentStackValue.getValueSecond();
                        if (valueSecond instanceof Map) {
                            map = (Map<K, Object>) valueSecond;
                        } else {
                            //
                            map = new LinkedHashMap<K, Object>();
                            if (valueSecond instanceof String) {
                                map.put(keyElementConverter.convert(new QName("")), valueSecond);
                            }
                        }
                    }

                    //
                    for (Entry<QName, Object> tagNameToManifestationEntry : tagNameToManifestationMap
                            .entrySet()) {
                        //
                        final K tagname = keyElementConverter.convert(tagNameToManifestationEntry.getKey());
                        final Object manifestation = tagNameToManifestationEntry.getValue();

                        //
                        if (!map.containsKey(tagname)) {
                            map.put(tagname, manifestation);
                        } else {
                            //
                            final Object object = map.get(tagname);
                            if (object instanceof List) {
                                //
                                final List<Object> list = (List<Object>) object;
                                list.add(manifestation);
                            } else {
                                //
                                final List<Object> list = new ArrayList<Object>();
                                list.add(object);
                                list.add(manifestation);
                                map.put(tagname, list);
                            }
                        }
                    }

                    //
                    currentStackValue.setValueSecond(map);
                }
            }

            private TupleTwo<QName, Object> getCurrentStackValue() {
                return ListUtils.firstElement(this.stackList);
            }

            private TupleTwo<QName, Object> removeStackElement() {
                return ListUtils.removeFirst(this.stackList);
            }

            private TupleTwo<QName, Object> addNewStackElement() {
                //
                final TupleTwo<QName, Object> retval = new TupleTwo<QName, Object>();
                this.stackList.add(0, retval);
                return retval;
            }
        }

        //  
        try {
            final Helper helper = new Helper();
            final TupleTwo<QName, Object> result = helper.manifest();
            retmap.put(keyElementConverter.convert(result.getValueFirst()), result.getValueSecond());
        } catch (Exception e) {
            if (exceptionHandler != null) {
                exceptionHandler.handleException(e);
            }
        }

        //
        xmlEventReader.close();
        reader.close();

    } catch (Exception e) {
        if (exceptionHandler != null) {
            exceptionHandler.handleException(e);
        }
    }

    //
    return retmap;
}

From source file:org.openhealthtools.openatna.archive.Loader.java

public void extract() throws Exception {
    File f = new File(archive);
    if (!f.exists() || f.length() == 0) {
        throw new Exception("archive does not exist");
    }//from ww  w.jav  a2s  .co m
    if (loadEntities) {
        InputStream min = ArchiveHandler.readEntities(f);
        if (min != null) {
            XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(min);
            loadEntities(reader);
            reader.close();
        } else {
            log.info(" Input stream to " + f.getAbsolutePath() + " message file is null");
        }
    }
    if (loadMessages) {
        InputStream min = ArchiveHandler.readMessages(f);
        if (min != null) {
            XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(min);
            loadMessages(reader);
            reader.close();
        } else {
            log.info(" Input stream to " + f.getAbsolutePath() + " message file is null");
        }
    }

    if (loadErrors) {
        InputStream min = ArchiveHandler.readErrors(f);
        if (min != null) {
            XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(min);
            loadErrors(reader);
            reader.close();
        } else {
            log.info(" Input stream to " + f.getAbsolutePath() + " message file is null");
        }
    }

}

From source file:org.talend.repository.json.util.ConvertJSONString.java

public static void main(String[] args) {
    ConvertJSONString convertJSON = new ConvertJSONString();
    de.odysseus.staxon.json.JsonXMLConfig jsonConfig = new de.odysseus.staxon.json.JsonXMLConfigBuilder()
            .multiplePI(false).build();/*  www  . j  a  v a  2s.c om*/
    de.odysseus.staxon.json.JsonXMLInputFactory jsonXMLInputFactory = new de.odysseus.staxon.json.JsonXMLInputFactory(
            jsonConfig);
    javax.xml.stream.XMLOutputFactory xmlOutputFactory = javax.xml.stream.XMLOutputFactory.newInstance();

    // org.dom4j.io.SAXReader reader_tExtractJSONFields_1 = new org.dom4j.io.SAXReader();
    // org.dom4j.Document doc_tExtractJSONFields_1 = null;
    // java.util.HashMap xmlNameSpaceMap_tExtractJSONFields_1 = new java.util.HashMap<String, String>();
    // org.dom4j.XPath x_tExtractJSONFields_1 = null;
    // java.util.List<org.dom4j.tree.AbstractNode> nodeList_tExtractJSONFields_1 = null;
    // boolean isStructError = true;
    java.io.ByteArrayOutputStream outStream = new java.io.ByteArrayOutputStream();
    java.io.ByteArrayInputStream inStream = null;
    File file = new File("E:/builds/source_file.json");
    try {
        FileInputStream input = new FileInputStream(file);
        String jsonStr = IOUtils.toString(input);

        // String loopQuery_tExtractJSONFields_1 = "/rcp.authorized_plug-ins";
        // String oraginalJsonStr_tExtractJSONFields_1 = jsonStr_tExtractJSONFields_1;
        convertJSON.setJsonString(jsonStr);
        // cjs_tExtractJSONFields_1.setLoopString(loopQuery_tExtractJSONFields_1);

        convertJSON.generate();
        jsonStr = convertJSON.getJsonString4XML();
        // loopQuery_tExtractJSONFields_1 = cjs_tExtractJSONFields_1.getLoopString4XML();
        inStream = new ByteArrayInputStream(jsonStr.getBytes());
        javax.xml.stream.XMLEventReader xmlEventReader = jsonXMLInputFactory.createXMLEventReader(inStream);
        javax.xml.stream.XMLEventWriter xmLEventWriter = xmlOutputFactory.createXMLEventWriter(outStream);
        xmLEventWriter.add(xmlEventReader);
        // convert json string to xml
        String xmlStr = outStream.toString();
        // System.out.println(xmlStr_tExtractJSONFields_1);

        FileWriter writer = new FileWriter("D:/CLOUD1.xml");
        writer.write(xmlStr);
        writer.flush();
        writer.close();
        // xmlStr_tExtractJSONFields_1 =
        // "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><rcp.authorized_plug-ins><s1>4</s1><upk>false</upk><psn>org.eclipse.jface.databinging.n1_de</psn><v>3.6.0.v20100814043401</v><pa>MDM1,TIS,DI</pa><sd>false</sd></rcp.authorized_plug-ins><rcp.authorized_plug-ins><s1>1</s1><upk>false</upk><psn>org.eclipse.jface.databinging.n1_de</psn><v>3.6.0.v20100814043401</v><pa>TDQ,Test</pa><sd>false</sd></rcp.authorized_plug-ins></root>";
        xmLEventWriter.close();
        xmlEventReader.close();

        // doc_tExtractJSONFields_1 = reader_tExtractJSONFields_1.read(new
        // java.io.StringReader(xmlStr_tExtractJSONFields_1));
        // x_tExtractJSONFields_1 = doc_tExtractJSONFields_1.createXPath(loopQuery_tExtractJSONFields_1);
        // x_tExtractJSONFields_1.setNamespaceURIs(xmlNameSpaceMap_tExtractJSONFields_1);
        // nodeList_tExtractJSONFields_1 = (java.util.List<org.dom4j.tree.AbstractNode>) x_tExtractJSONFields_1
        // .selectNodes(doc_tExtractJSONFields_1);
        // isStructError = false;
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (java.lang.Exception ex_tExtractJSONFields_1) {
        ex_tExtractJSONFields_1.printStackTrace();
    } finally {
        try {
            outStream.close();
            if (inStream != null) {
                inStream.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}