Example usage for javax.xml.stream XMLEventReader hasNext

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

Introduction

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

Prototype

@Override
public boolean hasNext();

Source Link

Document

Check if there are more events.

Usage

From source file:com.vistatec.ocelot.xliff.okapi.OkapiXLIFFFactory.java

@Override
public XLIFFVersion detectXLIFFVersion(File detectVersion) throws IOException, XMLStreamException {
    try (BOMInputStream bomInputStream = new BOMInputStream(new FileInputStream(detectVersion),
            ByteOrderMark.UTF_8, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_32BE,
            ByteOrderMark.UTF_32LE)) {/*from   w ww.  ja  va 2s . co m*/
        String bom = "UTF-8";
        if (bomInputStream.hasBOM()) {
            bom = bomInputStream.getBOMCharsetName();
        }

        XMLInputFactory xml = XMLInputFactory.newInstance();
        XMLEventReader reader = xml.createXMLEventReader(bomInputStream, bom);
        while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();
            switch (event.getEventType()) {
            case XMLEvent.START_ELEMENT:
                StartElement startElement = (StartElement) event;
                String localPart = startElement.getName().getLocalPart();
                if (localPart.equals("xliff")) {
                    @SuppressWarnings("unchecked")
                    Iterator<Attribute> attrs = startElement.getAttributes();
                    while (attrs.hasNext()) {
                        Attribute attr = attrs.next();
                        if (isXliffVersionAttributeName(attr.getName())) {
                            String value = attr.getValue();
                            reader.close();
                            if ("2.0".equals(value)) {
                                return XLIFFVersion.XLIFF20;
                            } else {
                                return XLIFFVersion.XLIFF12;
                            }
                        }
                    }
                }
                break;

            default:
                break;
            }
        }
        throw new IllegalStateException("Could not detect XLIFF version");
    }
}

From source file:com.predic8.membrane.core.ws.relocator.Relocator.java

public void relocate(InputStreamReader isr) throws Exception {
    XMLEventReader parser = XMLInputFactory.newInstance().createXMLEventReader(isr);

    while (parser.hasNext()) {
        writer.add(getEvent(parser));//from  w  ww .ja v  a2s.  c o  m
    }
    writer.flush();
}

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

public static StartElement getPropertyStartTag(final XMLEventReader propReader, final String[] path)
        throws Exception {
    int pos = 0;/*from w  w  w . j ava  2 s. c  o m*/

    StartElement property = null;

    while (propReader.hasNext() && pos < path.length) {
        final XMLEvent event = propReader.nextEvent();

        if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && (ATOM_PROPERTY_PREFIX + path[pos].trim())
                        .equals(event.asStartElement().getName().getLocalPart())) {
            pos++;
            if (path.length == pos) {
                property = event.asStartElement();
            }
        }
    }

    if (property == null) {
        throw new NotFoundException();
    }

    return property;
}

From source file:com.predic8.membrane.core.interceptor.xmlprotection.XMLProtector.java

public boolean protect(InputStreamReader isr) {
    try {// w ww  .  j  a va2 s  .  c om
        XMLEventReader parser;
        synchronized (xmlInputFactory) {
            parser = xmlInputFactory.createXMLEventReader(isr);
        }

        while (parser.hasNext()) {
            XMLEvent event = parser.nextEvent();
            if (event.isStartElement()) {
                StartElement startElement = (StartElement) event;
                if (maxElementNameLength != -1)
                    if (startElement.getName().getLocalPart().length() > maxElementNameLength) {
                        log.warn("Element name length: Limit exceeded.");
                        return false;
                    }
                if (maxAttibuteCount != -1) {
                    @SuppressWarnings("rawtypes")
                    Iterator i = startElement.getAttributes();
                    for (int attributeCount = 0; i.hasNext(); i.next())
                        if (++attributeCount == maxAttibuteCount) {
                            log.warn("Number of attributes per element: Limit exceeded.");
                            return false;
                        }
                }
            }
            if (event instanceof javax.xml.stream.events.DTD) {
                if (removeDTD) {
                    log.debug("removed DTD.");
                    continue;
                }
            }
            writer.add(event);
        }
        writer.flush();
    } catch (XMLStreamException e) {
        log.warn("Received not-wellformed XML.");
        return false;
    }
    return true;
}

From source file:org.fcrepo.serialization.JcrXmlSerializer.java

private void validateJCRXML(final File file) throws InvalidSerializationFormatException, IOException {
    int depth = 0;
    try (final FileInputStream fis = new FileInputStream(file)) {
        final XMLEventReader reader = XMLInputFactory.newFactory().createXMLEventReader(fis);
        while (reader.hasNext()) {
            final XMLEvent event = reader.nextEvent();
            if (event.isStartElement()) {
                depth++;/*www. ja  va 2  s  .  c o m*/
                final StartElement startElement = event.asStartElement();
                final Attribute nameAttribute = startElement
                        .getAttributeByName(new QName("http://www.jcp.org/jcr/sv/1.0", "name"));
                if (depth == 1 && nameAttribute != null && "jcr:content".equals(nameAttribute.getValue())) {
                    throw new InvalidSerializationFormatException(
                            "Cannot import JCR/XML starting with content node.");
                }
                if (depth == 1 && nameAttribute != null && "jcr:frozenNode".equals(nameAttribute.getValue())) {
                    throw new InvalidSerializationFormatException("Cannot import historic versions.");
                }
                final QName name = startElement.getName();
                if (!(name.getNamespaceURI().equals("http://www.jcp.org/jcr/sv/1.0")
                        && (name.getLocalPart().equals("node") || name.getLocalPart().equals("property")
                                || name.getLocalPart().equals("value")))) {
                    throw new InvalidSerializationFormatException(
                            "Unrecognized element \"" + name.toString() + "\", in import XML.");
                }
            } else {
                if (event.isEndElement()) {
                    depth--;
                }
            }
        }
        reader.close();
    } catch (XMLStreamException e) {
        throw new InvalidSerializationFormatException(
                "Unable to parse XML" + (e.getMessage() != null ? " (" + e.getMessage() + ")." : "."));
    }
}

From source file:corpus.sinhala.crawler.blog.rss.RSSFeedParser.java

public String getBlogId() {
    Feed feed = null;//w w w  . ja  v a 2  s .c o  m
    String atomId = "";
    try {
        // First create a new XMLInputFactory
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        // Setup a new eventReader
        InputStream in = read();
        XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
        // Read the XML document
        int location = -1;
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            if (event.isStartElement()) {
                String localPart = event.asStartElement().getName().getLocalPart();
                //System.out.println(localPart);
                switch (localPart) {

                case CHANNEL:
                    event = eventReader.nextEvent();
                    atomId = getCharacterData(event, eventReader);
                    //System.out.println("Atom Id "+atomId );
                    return atomId.split("-")[1];
                }
            }
        }
    } catch (XMLStreamException e) {

        throw new RuntimeException(e);
    }

    return null;
}

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  w  ww.j  a v a  2  s.  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:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

public static XmlElement getAtomElement(final StartElement start, final XMLEventReader reader)
        throws Exception {

    final XmlElement res = new XmlElement();
    res.setStart(start);//from  w w w .j  a v a  2  s  . c  o  m

    StringWriter content = new StringWriter();

    int depth = 1;

    while (reader.hasNext() && depth > 0) {
        final XMLEvent event = reader.nextEvent();

        if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && start.getName().getLocalPart().equals(event.asStartElement().getName().getLocalPart())) {
            depth++;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && start.getName().getLocalPart().equals(event.asEndElement().getName().getLocalPart())) {
            depth--;
        }

        if (depth == 0) {
            res.setEnd(event.asEndElement());
        } else {
            event.writeAsEncodedUnicode(content);
        }
    }

    content.flush();
    content.close();

    res.setContent(new ByteArrayInputStream(content.toString().getBytes()));

    return res;
}

From source file:fr.openwide.talendalfresco.rest.client.ClientCommandBase.java

public final void handleResponse(XMLEventReader xmlReader) throws XMLStreamException {
    // Read the response body and parse it
    while (xmlReader.hasNext()) {
        XMLEvent event = xmlReader.nextEvent();

        if (isInCommandResponseContent) {

            // within command content tag case
            switch (event.getEventType()) {
            case XMLEvent.END_ELEMENT:
                commandResponseContentDepth--;
                if (commandResponseContentDepth == -1) {
                    // means the content tag has been closed
                    isInCommandResponseContent = false;
                }//from w ww .jav  a  2 s .co m
                break;
            case XMLEvent.START_ELEMENT:
                commandResponseContentDepth++;
            }
            // delegate impl of command content tag case
            handleResponseContentEvent(event);

        } else {

            // outside command content tag case
            handleResponseTopLevelEvent(event);
        }
    }

    resultCode = elementValueMap.get(RestConstants.TAG_CODE);
    resultError = elementValueMap.get(RestConstants.TAG_ERROR);
    resultMessage = elementValueMap.get(RestConstants.TAG_MESSAGE);
}

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;// w ww .  j  a v a2 s  . c om
    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 {

    }
}