Example usage for javax.xml.stream XMLEventReader nextEvent

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

Introduction

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

Prototype

public XMLEvent nextEvent() throws XMLStreamException;

Source Link

Document

Gets the next XMLEvent.

Usage

From source file:org.qi4j.valueserialization.stax.StaxValueDeserializer.java

private static String readElementBody(XMLEventReader input) throws XMLStreamException {
    StringWriter buf = new StringWriter(1024);
    int depth = 0;
    while (input.hasNext()) {
        // peek event
        XMLEvent xmlEvent = input.peek();
        if (xmlEvent.isStartElement()) {
            ++depth;/* ww  w .  ja va2  s. com*/
        } else if (xmlEvent.isEndElement()) {
            --depth;
            // reached END_ELEMENT tag?
            // break loop, leave event in stream
            if (depth < 0) {
                break;
            }
        }
        // consume event
        xmlEvent = input.nextEvent();
        // print out event
        xmlEvent.writeAsEncodedUnicode(buf);
    }
    return buf.getBuffer().toString();
}

From source file:org.sakaiproject.nakamura.auth.cas.CasAuthenticationHandler.java

private String retrieveCredentials(String responseBody) {
    String username = null;/* ww w.  j av a2 s .c o m*/
    String pgtIou = null;
    String failureCode = null;
    String failureMessage = null;

    try {
        XMLInputFactory xmlInputFactory = new WstxInputFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
        xmlInputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
        XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(new StringReader(responseBody));

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

            // process the event if we're starting an element
            if (event.isStartElement()) {
                StartElement startEl = event.asStartElement();
                QName startElName = startEl.getName();
                String startElLocalName = startElName.getLocalPart();
                LOGGER.debug(responseBody);

                /*
                 * Example of failure XML
                <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
                  <cas:authenticationFailure code='INVALID_REQUEST'>
                    &#039;service&#039; and &#039;ticket&#039; parameters are both required
                  </cas:authenticationFailure>
                </cas:serviceResponse>
                */
                if ("authenticationFailure".equalsIgnoreCase(startElLocalName)) {
                    // get code of the failure
                    Attribute code = startEl.getAttributeByName(QName.valueOf("code"));
                    failureCode = code.getValue();

                    // get the message of the failure
                    event = eventReader.nextEvent();
                    assert event.isCharacters();
                    Characters chars = event.asCharacters();
                    failureMessage = chars.getData();
                    break;
                }

                /*
                 * Example of success XML
                <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
                  <cas:authenticationSuccess>
                    <cas:user>NetID</cas:user>
                  </cas:authenticationSuccess>
                </cas:serviceResponse>
                */
                if ("authenticationSuccess".equalsIgnoreCase(startElLocalName)) {
                    // skip to the user tag start
                    while (eventReader.hasNext()) {
                        event = eventReader.nextTag();
                        if (event.isEndElement()) {
                            if (eventReader.hasNext()) {
                                event = eventReader.nextTag();
                            } else {
                                break;
                            }
                        }
                        assert event.isStartElement();
                        startEl = event.asStartElement();
                        startElName = startEl.getName();
                        startElLocalName = startElName.getLocalPart();
                        if (proxy && "proxyGrantingTicket".equals(startElLocalName)) {
                            event = eventReader.nextEvent();
                            assert event.isCharacters();
                            Characters chars = event.asCharacters();
                            pgtIou = chars.getData();
                            LOGGER.debug("XML parser found pgt: {}", pgtIou);
                        } else if ("user".equals(startElLocalName)) {
                            // move on to the body of the user tag
                            event = eventReader.nextEvent();
                            assert event.isCharacters();
                            Characters chars = event.asCharacters();
                            username = chars.getData();
                            LOGGER.debug("XML parser found user: {}", username);
                        } else {
                            LOGGER.error("Found unexpected element [{}] while inside 'authenticationSuccess'",
                                    startElName);
                            break;
                        }
                        if (username != null && (!proxy || pgtIou != null)) {
                            break;
                        }
                    }
                }
            }
        }
    } catch (XMLStreamException e) {
        LOGGER.error(e.getMessage(), e);
    }

    if (failureCode != null || failureMessage != null) {
        LOGGER.error("Error response from server code={} message={}", failureCode, failureMessage);
    }
    String pgt = pgts.get(pgtIou);
    if (pgt != null) {
        savePgt(username, pgt, pgtIou);
    } else {
        LOGGER.debug("Caching '{}' as the IOU for '{}'", pgtIou, username);
        pgtIOUs.put(pgtIou, username);
    }
    return username;
}

From source file:org.sakaiproject.nakamura.auth.cas.CasAuthenticationHandler.java

private String getProxyTicketFromXml(String responseBody) {
    String ticket = null;//from  w  ww. j  av a 2s  .  c  om

    try {
        XMLInputFactory xmlInputFactory = new WstxInputFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
        xmlInputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
        XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(new StringReader(responseBody));
        LOGGER.debug(responseBody);

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

            // process the event if we're starting an element
            if (event.isStartElement()) {
                StartElement startEl = event.asStartElement();
                QName startElName = startEl.getName();
                String startElLocalName = startElName.getLocalPart();

                // Example XML
                // <cas:serviceResponse>
                // <cas:proxySuccess>
                // <cas:proxyTicket>PT-957-ZuucXqTZ1YcJw81T3dxf</cas:proxyTicket>
                // </cas:proxySuccess>
                // </cas:serviceResponse>

                if ("proxySuccess".equalsIgnoreCase(startElLocalName)) {
                    event = eventReader.nextTag();
                    assert event.isStartElement();
                    startEl = event.asStartElement();
                    startElName = startEl.getName();
                    startElLocalName = startElName.getLocalPart();
                    if ("proxyTicket".equalsIgnoreCase(startElLocalName)) {
                        event = eventReader.nextEvent();
                        assert event.isCharacters();
                        Characters chars = event.asCharacters();
                        ticket = chars.getData();
                    } else {
                        LOGGER.error("Found unexpected element [{}] while inside 'proxySuccess'", startElName);
                        break;
                    }
                }
            }
        }
    } catch (XMLStreamException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return ticket;
}

From source file:org.sakaiproject.nakamura.docproxy.url.UrlRepositoryProcessor.java

/**
 * Parse search results information into documents.
 * <p>// w w  w.  j  a v a2s .  c om
 * The expected format of the returned information is:<br/>
 * <code>
 * <documents>
 *   <document contentLength="%s" contentType="%s" uri="%s">
 *     <properties>
 *       <key1>value1</key1>
 *       <key2>value2</key2>
 *     </properties>
 *   </document>
 * </documents>
 * </code>
 * </p>
 * 
 * @param body
 * @return
 * @throws JSONException
 */
protected List<ExternalDocumentResult> parseSearch(InputStream body) throws XMLStreamException {
    ArrayList<ExternalDocumentResult> results = new ArrayList<ExternalDocumentResult>();

    XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(body);
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();
        // process the event if we're starting an element
        if (event.isStartElement()) {

            StartElement startEl = event.asStartElement();
            QName startElName = startEl.getName();
            String startElLocalName = startElName.getLocalPart();

            // process the href element
            if ("document".equalsIgnoreCase(startElLocalName)) {
                results.add(parseDocument(startEl, null));
                event = eventReader.nextEvent();
                continue;
            }
        }
    }

    return results;
}

From source file:org.sakaiproject.nakamura.docproxy.url.UrlRepositoryProcessor.java

/**
 * Parse information about a doc from JSON to an {@link ExternalDocumentResult} object.<br/>
 * XML is expected to follow the format of:
 * <p>//ww  w.  j  a va 2 s.  c o m
 * <code>
 * <document contentLength="%s" contentType="%s" uri="%s">
 *   <properties>
 *     <key1>value1</key1>
 *     <key2>value2</key2>
 *   </properties>
 * </document>
 * </code>
 * </p>
 * 
 * @param is
 * @return
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 */
protected ExternalDocumentResult parseDocument(InputStream body) throws XMLStreamException {
    UrlDocumentResult doc = new UrlDocumentResult();
    XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(body);
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();

        // process the event if we're starting an element
        if (event.isStartElement()) {
            StartElement startEl = event.asStartElement();
            QName startElName = startEl.getName();
            String startElLocalName = startElName.getLocalPart();

            if ("document".equalsIgnoreCase(startElLocalName)) {
                parseDocument(startEl, doc);
                continue;
            }

            if ("properties".equalsIgnoreCase(startElLocalName)) {
                parseProperties(eventReader, doc);
                continue;
            }
        }
    }
    return doc;
}

From source file:org.sakaiproject.nakamura.docproxy.url.UrlRepositoryProcessor.java

/**
 * Parse subelements of a 'properties' element into properties on a
 * {@link UrlDocumentResult}./*from  www  . ja  va 2s  .c om*/
 * 
 * @param eventReader
 *          Source to process elements from. Is expected that calls to
 *          eventReader.nextEvent() will yield elements to be added to doc as
 *          properties. Nested elements are not considered.
 * @param doc
 *          The document to set attributes into.
 * @throws XMLStreamException
 *           If there is a problem processing the element.
 */
private void parseProperties(XMLEventReader eventReader, UrlDocumentResult doc) throws XMLStreamException {
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();

        // process the event if we're starting an element
        if (event.isStartElement()) {
            StartElement startEl = event.asStartElement();
            QName startElName = startEl.getName();
            String startElLocalName = startElName.getLocalPart();

            // collect simple elements as properties
            event = eventReader.nextEvent();
            if (event.isCharacters()) {
                Characters chars = event.asCharacters();
                doc.addProperty(startElLocalName, chars.getData());
            }
        }
    }
}

From source file:org.sakaiproject.nakamura.proxy.RSSProxyPostProcessor.java

public void process(Map<String, Object> templateParams, SlingHttpServletResponse response,
        ProxyResponse proxyResponse) throws IOException {
    if (proxyResponse.getResultCode() == HttpServletResponse.SC_PRECONDITION_FAILED) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This RSS feed is too big ");
        return;/*  w  w  w  .j  a  v a 2s  .c  o m*/
    }

    Map<String, String[]> headers = proxyResponse.getResponseHeaders();

    // Check if the content-length is smaller than the maximum (if any).
    String[] contentLengthHeader = headers.get("Content-Length");
    if (contentLengthHeader != null) {
        int length = Integer.parseInt(contentLengthHeader[0]);
        if (length > maxLength) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "This RSS feed is too big. The maximum for a feed is: " + maxLength);
            return;
        }
    }

    // Check if the Content-Type we get is valid (if any).
    String[] contentTypeHeader = headers.get("Content-Type");
    if (contentTypeHeader != null) {
        String contentType = contentTypeHeader[0];
        if (contentType.contains(";")) {
            contentType = contentType.substring(0, contentType.indexOf(';'));
        }
        if (!contentTypes.contains(contentType)) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "This URL doesn't send a proper Content-Type back");
            return;
        }
    }

    boolean isValid = false;
    InputStream in = proxyResponse.getResponseBodyAsInputStream();
    InputStreamReader reader = new InputStreamReader(in);

    // XMLStreamWriter writer = null;
    XMLEventWriter writer = null;
    ByteArrayOutputStream out = null;

    int i = 0;
    try {
        XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(reader);
        // Create a temporary outputstream where we can write to.
        out = new ByteArrayOutputStream();

        Set<String> checkedElements = null;

        XMLOutputFactory outputFactory = new WstxOutputFactory();
        writer = outputFactory.createXMLEventWriter(out);

        while (eventReader.hasNext()) {
            XMLEvent e = eventReader.nextEvent();
            // Stream it to an output stream.
            writer.add(e);

            if (!isValid) {
                if (e.getEventType() == XMLEvent.START_ELEMENT) {
                    StartElement el = e.asStartElement();
                    String name = el.getName().getLocalPart().toLowerCase();
                    if (checkedElements == null) {
                        // get the right format to validate against
                        String formatKey = name;
                        Attribute attr = el.getAttributeByName(new QName("version"));
                        if (attr != null) {
                            formatKey += "-" + attr.getValue();
                        }
                        Set<String> format = formats.get(formatKey);
                        if (format != null) {
                            checkedElements = new HashSet<String>(format);
                        }
                    } else {
                        checkedElements.remove(name);

                        if (checkedElements.isEmpty()) {
                            isValid = true;
                        }
                    }
                }

                if (i > eventsThreshold) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This file is too complex.");
                    return;
                }
                i++;
            }
        }

        if (!isValid) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid RSS file.");
            return;
        }

        // Check if we are not streaming a gigantic file..
        if (out.size() > maxLength) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This file is too big.");
            return;
        }

        for (Entry<String, String[]> h : proxyResponse.getResponseHeaders().entrySet()) {
            for (String v : h.getValue()) {
                response.setHeader(h.getKey(), v);
            }
        }
        // We always return 200 when we get to this point.
        response.setStatus(200);
        response.setHeader("Content-Length", Integer.toString(out.size()));
        // Write the cached stream to the output.
        out.writeTo(response.getOutputStream());

    } catch (XMLStreamException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This is not a valid XML file.");
    } catch (Exception e) {
        logger.warn("Exception reading RSS feed.", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "General exception caught.");
    } finally {
        if (out != null) {
            out.close();
        }
        reader.close();
        try {
            if (writer != null)
                writer.close();
        } catch (XMLStreamException e) {
            // Not much we can do?
            e.printStackTrace();
        }
    }

}

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

/**
 * Responsible for moving the cursor before the StartElement of the fragment root.
 * /* ww  w. j a  v a2  s. com*/
 * This implementation simply looks for the next corresponding element, it does not care about element nesting. You
 * will need to override this method to correctly handle composite fragments.
 * 
 * @return <code>true</code> if next fragment was found, <code>false</code> otherwise.
 * 
 * @throws NonTransientResourceException if the cursor could not be moved. This will be treated as fatal and
 * subsequent calls to read will return null.
 */
protected boolean moveCursorToNextFragment(XMLEventReader reader) throws NonTransientResourceException {
    try {
        while (true) {
            while (reader.peek() != null && !reader.peek().isStartElement()) {
                reader.nextEvent();
            }
            if (reader.peek() == null) {
                return false;
            }
            QName startElementName = ((StartElement) reader.peek()).getName();
            if (isFragmentRootElementName(startElementName)) {
                return true;
            }
            reader.nextEvent();

        }
    } catch (XMLStreamException e) {
        throw new NonTransientResourceException("Error while reading from event reader", e);
    }
}

From source file:org.xmlsh.commands.internal.xml2json.java

public int run(List<XValue> args) throws Exception {
    Options opts = new Options("p=print", SerializeOpts.getOptionDefs());

    opts.parse(args);//from w  w  w.j  a va 2  s .c  o m

    bIndent = opts.hasOpt("p");

    args = opts.getRemainingArgs();

    OutputPort stdout = getStdout();

    InputPort inp = args.isEmpty() ? getStdin() : getInput(args.get(0));

    SerializeOpts serializeOpts = getSerializeOpts(opts);
    XMLEventReader reader = inp.asXMLEventReader(serializeOpts);

    // Override the text encoding to UTF-8 - JSON is *always* USTF8
    mSerializeOpts = serializeOpts.clone();
    serializeOpts.setOutputTextEncoding(kENCODING_UTF_8);
    PrintWriter writer = stdout.asPrintWriter(serializeOpts);

    parse(reader, writer, false);
    writer.flush();
    writer.close();

    // Consume input or we can get a Piped Close
    while (reader.hasNext())
        reader.nextEvent();

    reader.close();
    inp.release();

    return 0;

}

From source file:org.xmlsh.commands.internal.xml2json.java

private boolean parse(XMLEventReader reader, PrintWriter writer, boolean bComma) throws XMLStreamException,
        CoreException, UnsupportedEncodingException, IOException, TransformException, SaxonApiException {
    mLevel++;/* w  ww .  j av  a  2s  .co m*/

    while (reader.hasNext()) {
        XMLEvent e = reader.nextEvent();
        if (e.isStartElement()) {
            StartElement start = e.asStartElement();
            QName name = start.getName();

            if (name.equals(kELEM_XJSON)) {
                if (mLevel != 1)
                    throw new UnexpectedException("XJSON element must be at document root");

                // Children become the new roots

                mLevel = 0;
                while (parse(reader, writer, bComma))
                    ;
                return false;

            } else if (name.equals(kELEM_FILE)) {
                if (!writeFile(start, reader, writer))
                    return false;

            }

            else if (bComma)
                writer.print(",");

            if (name.equals(kELEM_OBJECT))
                writeObject(start, reader, writer);
            else if (name.equals(kELEM_ARRAY))
                writeArray(start, reader, writer);
            else if (name.equals(kELEM_MEMBER))
                writeMember(start, reader, writer);
            else if (name.equals(kELEM_NUMBER))
                writeNumber(start, reader, writer);
            else if (name.equals(kELEM_BOOLEAN))
                writeBoolean(start, reader, writer);
            else if (name.equals(kELEM_NULL))
                writeNull(reader, writer);
            else if (name.equals(kELEM_STRING))
                writeString(start, reader, writer);
            else
                readToEnd(reader);

            mLevel--;
            return true;

        } else if (e.isEndElement()) {
            mLevel--;

            return false;
        }
    }
    mLevel--;
    return false;
}