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:com.logiware.accounting.domain.EdiInvoice.java

private void createEcuLineInvoice(File file) throws Exception {
    InputStream inputStream = null;
    XMLEventReader eventReader = null;
    try {//  ww w . j  av  a 2 s. c  om
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        inputStream = new FileInputStream(file);
        eventReader = inputFactory.createXMLEventReader(inputStream);
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            if (event.isStartElement()) {
                StartElement startElement = event.asStartElement();
                if ("Header".equalsIgnoreCase(startElement.getName().toString())) {
                    isHeader = true;
                    elements.add("Header");
                } else if ("Body".equalsIgnoreCase(startElement.getName().toString())) {
                    isBody = true;
                    elements.add("Body");
                } else if (isBody && "Information".equalsIgnoreCase(startElement.getName().toString())) {
                    isInformation = true;
                    elements.add("Information");
                } else if (isBody && !isInformation
                        && "Details".equalsIgnoreCase(startElement.getName().toString())) {
                    isDetails = true;
                    elements.add("Details");
                } else if (isBody && !isInformation && !isDetails
                        && "Summary".equalsIgnoreCase(startElement.getName().toString())) {
                    isSummary = true;
                    elements.add("Summary");
                } else if (null == elementType) {
                    setElementType(startElement);
                } else if (null != elementType && null == characterType) {
                    setCharacterType(startElement);
                }
            } else if (event.isCharacters()) {
                setValue(event.asCharacters());
            } else if (event.isEndElement()) {
                EndElement endElement = event.asEndElement();
                if (null != characterType && null != elementType) {
                    removeCharacterType();
                } else if (null != elementType) {
                    removeElementType(endElement);
                } else if (isSummary && "Summary".equalsIgnoreCase(endElement.getName().toString())) {
                    isSummary = false;
                } else if (isDetails && "Details".equalsIgnoreCase(endElement.getName().toString())) {
                    isDetails = false;
                } else if (isBody && "Information".equalsIgnoreCase(endElement.getName().toString())) {
                    isInformation = false;
                } else if ("Body".equalsIgnoreCase(endElement.getName().toString())) {
                    isBody = false;
                } else if ("Header".equalsIgnoreCase(endElement.getName().toString())) {
                    isHeader = false;
                }
            }
        }
        this.company = Company.ECU_LINE;
        status = new EdiInvoiceDAO().getStatus(vendorNumber, invoiceNumber);
        if (!elements.contains("Header")) {
            throw new AccountingException("Bad File. <Header> element missing");
        } else if (!elements.contains("Body")) {
            throw new AccountingException("Bad File. <Body> missing");
        } else if (!elements.contains("Information")) {
            throw new AccountingException("Bad File. <Information> element under <Body> missing");
        } else if (!elements.contains("Details")) {
            throw new AccountingException("Bad File. <Details> element under <Body> missing");
        } else if (!elements.contains("Summary")) {
            throw new AccountingException("Bad File. <Summary> element under <Body> missing");
        } else if (!elements.contains("Applicationreference")) {
            throw new AccountingException("Bad File. <Applicationreference> element under <Header> missing");
        } else if (!elements.contains("Reference")) {
            throw new AccountingException("Bad File. <Reference> element under <Header> missing");
        } else if (!elements.contains("Sender")) {
            throw new AccountingException("Bad File. <Sender> element under <Header> missing");
        } else if (!elements.contains("Code")) {
            throw new AccountingException("Bad File. <Code> element under <Sender> of <Header> missing");
        } else if (!elements.contains("Invoice")) {
            throw new AccountingException(
                    "Bad File. <Invoice> element under <Information> element of <Body> missing");
        } else if (!elements.contains("RelatedReferences")) {
            throw new AccountingException(
                    "Bad File. <RelatedReferences> element under <Information> element of <Body> missing");
        } else if (!elements.contains("BY")) {
            throw new AccountingException(
                    "Bad File. <Parties Qualifier=\"BY\"> under <Information> element of <Body> missing");
        } else if (!elements.contains("SU")) {
            throw new AccountingException(
                    "Bad File. <Parties Qualifier=\"SU\"> under <Information> element of <Body> missing");
        } else if (!elements.contains("PaymentTerms")) {
            throw new AccountingException(
                    "Bad File. <PaymentTerms> element under <Information> element of <Body> missing");
        } else if (!elements.contains("ShipmentInformation")) {
            throw new AccountingException(
                    "Bad File. <ShipmentInformation> element under <Information> element of <Body> missing");
        } else if (!elements.contains("Detail")) {
            throw new AccountingException(
                    "Bad File. <Detail> element under <Details> element of <Body> missing");
        } else if (!elements.contains("TotalMonetaryAmount")) {
            throw new AccountingException(
                    "Bad File. <TotalMonetaryAmount> element under <Summary> element of <Body> missing");
        } else if (!elements.contains("TotalMonetaryAmountGroupByVAT")) {
            throw new AccountingException(
                    "Bad File. <TotalMonetaryAmountGroupByVAT> element under <Summary> element of <Body> missing");
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (null != eventReader) {
            eventReader.close();
        }
        if (null != inputStream) {
            inputStream.close();
        }
    }
}

From source file:org.apache.olingo.fit.metadata.Metadata.java

public Metadata(final InputStream is) {
    DEF_NS = Constants.get(ConstantKey.EDM_NS);
    schemas = new HashMap<String, Schema>();

    try {//from   w  w w .  java 2  s .c om
        final XMLInputFactory ifactory = XMLInputFactory.newInstance();
        final XMLEventReader reader = ifactory.createXMLEventReader(is,
                org.apache.olingo.commons.api.Constants.UTF8);

        try {
            while (reader.hasNext()) {
                final XMLEvent event = reader.nextEvent();

                if (event.isStartElement()
                        && event.asStartElement().getName().equals(new QName(DEF_NS, "Schema"))) {
                    final Schema schema = getSchema(event.asStartElement(), reader);
                    schemas.put(schema.getNamespace(), schema);
                }
            }

        } catch (Exception ignore) {
            // ignore
        } finally {
            reader.close();
            IOUtils.closeQuietly(is);
        }
    } catch (Exception e) {
        LOG.error("Error parsing metadata", e);
    }

    for (Map.Entry<String, Schema> schemaEntry : schemas.entrySet()) {
        for (EntityType entityType : schemaEntry.getValue().getEntityTypes()) {
            for (NavigationProperty property : entityType.getNavigationProperties()) {
                property.setFeed(property.getType().startsWith("Collection("));

                final Collection<EntitySet> entitySets = schemaEntry.getValue().getContainers().iterator()
                        .next().getEntitySets(schemaEntry.getKey(), entityType.getName());

                final Iterator<EntitySet> iter = entitySets.iterator();
                boolean found = false;

                while (!found && iter.hasNext()) {
                    final EntitySet entitySet = iter.next();
                    final String target = entitySet.getTarget(property.getName());
                    if (StringUtils.isNotBlank(target)) {
                        property.setTarget(entitySet.getTarget(property.getName()));
                        found = true;
                    }
                }
            }
        }
    }
}

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

/**
 * {@inheritDoc }/*w ww. j ava2s .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());

    // 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(version, entitySetName, entitykey, link)));
        attributes.add(eventFactory.createAttribute(new QName("rel"), Constants.ATOM_LINK_REL + link));
        attributes.add(eventFactory.createAttribute(new QName("type"),
                Commons.linkInfo.get(version).isFeed(entitySetName, link) ? Constants.ATOM_LINK_FEED
                        : Constants.ATOM_LINK_ENTRY));

        writer.add(eventFactory.createStartElement(new QName(LINK), attributes.iterator(), null));
        writer.add(eventFactory.createEndElement(new QName(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.AbstractXMLUtilities.java

/**
 * {@inheritDoc }//from  w w  w .ja v  a  2 s  .  com
 */
@Override
protected Set<String> retrieveAllLinkNames(final InputStream is) throws Exception {
    final Set<String> links = new HashSet<String>();

    final XMLEventReader reader = getEventReader(is);

    try {

        int startDepth = 0;

        while (true) {
            final Map.Entry<Integer, XmlElement> linkInfo = extractElement(reader, null,
                    Collections.<String>singletonList(LINK), startDepth, 2, 2);

            startDepth = linkInfo.getKey();

            links.add(linkInfo.getValue().getStart().getAttributeByName(new QName("title")).getValue());
        }
    } catch (Exception ignore) {
        // ignore
    } finally {
        reader.close();
        IOUtils.closeQuietly(is);
    }

    return links;
}

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

/**
 * {@inheritDoc }//  w  ww.  jav a 2 s.  com
 */
@Override
protected NavigationLinks retrieveNavigationInfo(final String entitySetName, final InputStream is)
        throws Exception {

    final NavigationLinks links = new NavigationLinks();

    final XMLEventReader reader = getEventReader(is);

    try {
        final List<Map.Entry<String, String>> filter = new ArrayList<Map.Entry<String, String>>();
        filter.add(new AbstractMap.SimpleEntry<String, String>("type", "application/atom+xml;type=entry"));
        filter.add(new AbstractMap.SimpleEntry<String, String>("type", "application/atom+xml;type=feed"));

        int startDepth = 0;

        while (true) {
            // a. search for link with type attribute equals to "application/atom+xml;type=entry/feed"
            final Map.Entry<Integer, XmlElement> linkInfo = extractElement(reader, null,
                    Collections.<String>singletonList(LINK), filter, true, startDepth, 2, 2);
            final XmlElement link = linkInfo.getValue();
            startDepth = linkInfo.getKey();

            final String title = link.getStart().getAttributeByName(new QName("title")).getValue();

            final Attribute hrefAttr = link.getStart().getAttributeByName(new QName("href"));
            final String href = hrefAttr == null ? null : hrefAttr.getValue();

            try {
                final XmlElement inlineElement = extractElement(link.getContentReader(), null,
                        Collections.<String>singletonList(INLINE), 0, -1, -1).getValue();
                final XMLEventReader inlineReader = inlineElement.getContentReader();

                try {
                    while (true) {
                        final XmlElement entry = extractElement(inlineReader, null,
                                Collections.<String>singletonList("entry"), 0, -1, -1).getValue();
                        links.addInlines(title, entry.toStream());
                    }
                } catch (Exception e) {
                    // Reached the end of document
                }

                inlineReader.close();
            } catch (Exception ignore) {
                // inline element not found (inlines are not mondatory).
                if (StringUtils.isNotBlank(href) && entityUriPattern.matcher(href).matches()) {
                    links.addLinks(title, href.substring(href.lastIndexOf('/') + 1));
                }
            }
        }
    } catch (Exception ignore) {
        // ignore
    } finally {
        reader.close();
    }

    return links;
}

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

/**
 * {@inheritDoc }//  w w w. j  a  v a  2  s  .com
 */
@Override
protected InputStream normalizeLinks(final String entitySetName, final String entityKey, final InputStream is,
        final NavigationLinks links) throws Exception {

    // -----------------------------------------
    // 0. Build reader and writer
    // -----------------------------------------
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copy(is, bos);
    is.close();

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

    final XMLEventReader reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));
    // -----------------------------------------

    // -----------------------------------------
    // 1. Normalize links
    // -----------------------------------------
    final Set<String> added = new HashSet<String>();

    try {
        final List<Map.Entry<String, String>> filter = new ArrayList<Map.Entry<String, String>>();
        filter.add(new AbstractMap.SimpleEntry<String, String>("type", "application/atom+xml;type=entry"));
        filter.add(new AbstractMap.SimpleEntry<String, String>("type", "application/atom+xml;type=feed"));

        Map.Entry<Integer, XmlElement> linkInfo = null;

        while (true) {
            // a. search for link with type attribute equals to "application/atom+xml;type=entry/feed"
            linkInfo = extractElement(reader, writer, Collections.<String>singletonList(LINK), filter, true,
                    linkInfo == null ? 0 : linkInfo.getKey(), 2, 2);
            final XmlElement link = linkInfo.getValue();

            final String title = link.getStart().getAttributeByName(new QName("title")).getValue();

            if (!added.contains(title)) {
                added.add(title);

                final String normalizedLink = String.format(
                        "<link href=\"%s(%s)/%s\" rel=\"%s\" title=\"%s\" type=\"%s\"/>", entitySetName,
                        entityKey, title, link.getStart().getAttributeByName(new QName("rel")).getValue(),
                        title, link.getStart().getAttributeByName(new QName("type")).getValue());

                addAtomElement(IOUtils.toInputStream(normalizedLink), writer);
            }
        }
    } catch (Exception ignore) {
        // ignore
    } finally {
        writer.close();
        reader.close();
    }
    // -----------------------------------------

    // -----------------------------------------
    // 2. Add edit link if missing
    // -----------------------------------------
    final InputStream content = addEditLink(new ByteArrayInputStream(tmpBos.toByteArray()), entitySetName,
            Constants.DEFAULT_SERVICE_URL + entitySetName + "(" + entityKey + ")");
    // -----------------------------------------

    // -----------------------------------------
    // 3. Add content element if missing
    // -----------------------------------------
    return addAtomContent(content, entitySetName,
            Constants.DEFAULT_SERVICE_URL + entitySetName + "(" + entityKey + ")");
    // -----------------------------------------

}

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

@Override
public InputStream addEditLink(final InputStream content, final String title, final String href)
        throws Exception {

    final ByteArrayOutputStream copy = new ByteArrayOutputStream();
    IOUtils.copy(content, copy);/*from  w w w  .ja  v a2s .  c o  m*/

    IOUtils.closeQuietly(content);

    XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

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

    final String editLinkElement = String.format("<link rel=\"edit\" title=\"%s\" href=\"%s\" />", title, href);

    try {
        // check edit link existence
        extractElement(reader, writer, Collections.<String>singletonList(LINK),
                Collections.<Map.Entry<String, String>>singletonList(
                        new AbstractMap.SimpleEntry<String, String>("rel", "edit")),
                false, 0, -1, -1);

        addAtomElement(IOUtils.toInputStream(editLinkElement), writer);
        writer.add(reader);

    } catch (Exception e) {
        reader.close();
        reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

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

        final XmlElement entryElement = extractElement(reader, writer,
                Collections.<String>singletonList("entry"), 0, 1, 1).getValue();

        writer.add(entryElement.getStart());

        addAtomElement(IOUtils.toInputStream(editLinkElement), writer);

        writer.add(entryElement.getContentReader());
        writer.add(entryElement.getEnd());

        writer.add(reader);

        writer.flush();
        writer.close();
    } finally {
        reader.close();
    }

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

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

public InputStream addAtomContent(final InputStream content, final String title, final String href)
        throws Exception {

    final ByteArrayOutputStream copy = new ByteArrayOutputStream();
    IOUtils.copy(content, copy);/*from  w  ww  . j  av a2 s.  c  o m*/

    IOUtils.closeQuietly(content);

    XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

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

    try {
        // check edit link existence
        XmlElement contentElement = extractElement(reader, writer, Collections.<String>singletonList("content"),
                0, 2, 2).getValue();
        writer.add(contentElement.getStart());
        writer.add(contentElement.getContentReader());
        writer.add(contentElement.getEnd());
        writer.add(reader);
    } catch (Exception e) {
        reader.close();
        reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

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

        if (isMediaContent(title)) {
            final XmlElement entryElement = extractElement(reader, writer,
                    Collections.<String>singletonList("entry"), 0, 1, 1).getValue();

            writer.add(entryElement.getStart());
            writer.add(entryElement.getContentReader());

            addAtomElement(
                    IOUtils.toInputStream(String.format("<content type=\"*/*\" src=\"%s/$value\" />", href)),
                    writer);

            writer.add(entryElement.getEnd());
        } else {
            try {
                final XmlElement entryElement = extractElement(reader, writer,
                        Collections.<String>singletonList(PROPERTIES), 0, 2, 3).getValue();

                addAtomElement(IOUtils.toInputStream("<content type=\"application/xml\">"), writer);

                writer.add(entryElement.getStart());
                writer.add(entryElement.getContentReader());
                writer.add(entryElement.getEnd());

                addAtomElement(IOUtils.toInputStream("</content>"), writer);
            } catch (Exception nf) {
                reader.close();
                reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

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

                final XmlElement entryElement = extractElement(reader, writer,
                        Collections.<String>singletonList("entry"), 0, 1, 1).getValue();
                writer.add(entryElement.getStart());
                writer.add(entryElement.getContentReader());

                addAtomElement(IOUtils.toInputStream("<content type=\"application/xml\"/>"), writer);

                writer.add(entryElement.getEnd());
            }
        }

        writer.add(reader);

        writer.flush();
        writer.close();
    } finally {
        reader.close();
    }

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

From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.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 XMLEventWriter writer = getEventWriter(bos);

    try {//from w  w w .  ja  v a 2  s. c  o  m

        final XmlElement feedElement = extractElement(reader, writer, Collections.<String>singletonList("feed"),
                0, 1, 1).getValue();

        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:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

@Override
public InputStream getPropertyValue(final InputStream is, final List<String> path) throws Exception {

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

    for (String element : path) {
        pathElements.add(ATOM_PROPERTY_PREFIX + element);
    }// ww w .j a v  a  2s .c  om

    final XMLEventReader reader = getEventReader(is);
    final Map.Entry<Integer, XmlElement> property = extractElement(reader, null, pathElements, 0, 3, 4);

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

    return property.getValue().getContent();
}