Example usage for javax.xml.stream XMLStreamConstants START_ELEMENT

List of usage examples for javax.xml.stream XMLStreamConstants START_ELEMENT

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamConstants START_ELEMENT.

Prototype

int START_ELEMENT

To view the source code for javax.xml.stream XMLStreamConstants START_ELEMENT.

Click Source Link

Document

Indicates an event is a start element

Usage

From source file:com.microsoft.tfs.core.memento.XMLMemento.java

/**
 * Reads an {@link XMLMemento} from the next XML element in the given given
 * {@link InputStream} in the encoding specified as
 * {@link #DEFAULT_ENCODING}./*from   www  .  j  a  va2 s.  c  om*/
 *
 * @param inputStream
 *        the {@link InputStream} read to read the {@link XMLMemento} from
 *        (must not be <code>null</code>)
 * @param encoding
 *        the encoding to use when reading the {@link InputStream},
 *        <code>null</code> to use the default encoding (
 *        {@link #DEFAULT_ENCODING})
 * @return a Memento modeled as the first Element in the document.
 * @throws MementoException
 *         if an error prevented the creation of the Memento.
 */
public static XMLMemento read(final InputStream inputStream, final String encoding) throws MementoException {
    Check.notNull(inputStream, "inputStream"); //$NON-NLS-1$

    try {
        final XMLStreamReader reader = StaxFactoryProvider.getXMLInputFactory(true)
                .createXMLStreamReader(inputStream, (encoding != null) ? encoding : DEFAULT_ENCODING);

        XMLMemento memento = null;
        String localName;
        int event;

        do {
            event = reader.next();

            if (event == XMLStreamConstants.START_ELEMENT) {
                localName = reader.getLocalName();

                memento = new XMLMemento(localName);
                memento.readFromElement(reader);
            }
        } while (event != XMLStreamConstants.END_ELEMENT && event != XMLStreamConstants.END_DOCUMENT);

        reader.close();

        return memento;
    } catch (final XMLStreamException e) {
        log.error("Error reading", e); //$NON-NLS-1$
        throw new MementoException(e);
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.collection_reader.YahooAnswersStreamParser.java

private ParsedQuestion fetchNext() throws XMLStreamException {
    ParsedQuestion parsed = null;/*w  w w. j  a v a 2  s.  c  om*/

    String question = "";
    String questDetail = "";
    String questUri = "";
    String bestAnsw = "";
    ArrayList<String> answers = new ArrayList<String>();

    boolean bStart = false;

    String tagContent = null;

    while (mReader.hasNext()) {
        switch (mReader.next()) {
        case XMLStreamConstants.START_ELEMENT:
            switch (mReader.getLocalName()) {
            case "vespaadd":
                bStart = true;
                break;
            }
            break;
        case XMLStreamConstants.CHARACTERS:
            tagContent = mReader.getText();
            break;
        case XMLStreamConstants.END_ELEMENT:
            switch (mReader.getLocalName()) {
            case "vespaadd":
                return new ParsedQuestion(question, questDetail, questUri, answers, bestAnsw, mDoCleanUp);
            case "uri":
                questUri = tagContent;
                break;
            case "subject":
                question = tagContent;
                break;
            case "content":
                questDetail = tagContent;
                break;
            case "bestanswer":
                bestAnsw = tagContent;
                break;
            case "answer_item":
                answers.add(tagContent);
                break;
            }

            break;
        }
    }

    return null;
}

From source file:io.cloudslang.content.xml.utils.XmlUtils.java

/**
 * Returns the Namespaces context from an xml.
 *
 * @param xmlString   xml as string/*from ww  w.j  a  v  a 2s. c o  m*/
 * @param xmlFilePath path to xml file
 * @return the Namespaces context from an xml.
 * @throws IOException        file reading exception
 * @throws XMLStreamException parsing exception
 */
public static NamespaceContext getNamespaceContext(String xmlString, String xmlFilePath) throws Exception {
    InputStream inputXML = getStream(xmlString, xmlFilePath);
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader reader = inputFactory.createXMLStreamReader(inputXML);
    Map<String, String> namespaces = new HashMap<>();
    while (reader.hasNext()) {
        int evt = reader.next();
        if (evt == XMLStreamConstants.START_ELEMENT) {
            QName qName = reader.getName();
            if (qName != null) {
                if (qName.getPrefix() != null && qName.getPrefix().compareTo("") != 0)
                    namespaces.put(qName.getPrefix(), qName.getNamespaceURI());
            }
        }
    }
    return new SimpleNamespaceContext(namespaces);
}

From source file:de.tuebingen.uni.sfs.germanet.api.IliLoader.java

/**
 * Loads <code>IliRecords</code> from the specified file into this
 * <code>IliLoader</code>'s <code>GermaNet</code> object.
 * @param iliFile the file containing <code>IliRecords</code> data
 * @throws java.io.FileNotFoundException
 * @throws javax.xml.stream.XMLStreamException
 *///from   w ww  .  ja  v a2s  .c o m
protected void loadILI(File iliFile) throws FileNotFoundException, XMLStreamException {
    InputStream in = new FileInputStream(iliFile);
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader parser = factory.createXMLStreamReader(in);
    int event;
    String nodeName;
    logger.debug("Loading " + iliFile.getName() + "...");

    //Parse entire file, looking for ili record start elements
    while (parser.hasNext()) {
        event = parser.next();
        switch (event) {
        case XMLStreamConstants.START_DOCUMENT:
            namespace = parser.getNamespaceURI();
            break;
        case XMLStreamConstants.START_ELEMENT:
            nodeName = parser.getLocalName();
            if (nodeName.equals(GermaNet.XML_ILI_RECORD)) {
                IliRecord ili = processIliRecord(parser);
                germaNet.addIliRecord(ili);
            }
            break;
        }
    }
    parser.close();
    logger.debug("Done.");
}

From source file:au.org.ala.bhl.DocumentPaginator.java

private void paginateImpl(XMLStreamReader parser, PageHandler handler) throws Exception {

    if (parser == null) {
        return;//w w  w. ja  v a 2 s  .  c o m
    }

    StringBuilder buffer = new StringBuilder();

    String currentPage = null;

    while (true) {
        int event = parser.next();
        if (event == XMLStreamConstants.END_DOCUMENT) {
            parser.close();
            break;
        }

        if (event == XMLStreamConstants.START_ELEMENT) {
            if (parser.getLocalName().equals("PARAM")) {
                String attrName = parser.getAttributeValue("", "name");
                if (attrName.equals("PAGE")) {

                    if (!StringUtils.isEmpty(currentPage)) {
                        if (handler != null) {
                            handler.handlePage(currentPage, buffer.toString());
                        }
                    }

                    buffer = new StringBuilder();
                    currentPage = parser.getAttributeValue("", "value");
                }
            }
        }

        if (event == XMLStreamConstants.CHARACTERS) {
            String value = StringUtils.trim(parser.getText());
            if (!StringUtils.isEmpty(value)) {
                buffer.append(value).append(" ");
            }
        }
    }

}

From source file:de.huxhorn.sulky.plist.impl.PropertyListReader.java

private Object readValue(XMLStreamReader reader) throws XMLStreamException {
    int type = reader.getEventType();
    if (XMLStreamConstants.START_ELEMENT == type && TRUE_NODE.equals(reader.getLocalName())) {
        reader.nextTag();//from  ww  w. ja  v  a  2  s .c  o  m
        reader.require(XMLStreamConstants.END_ELEMENT, null, TRUE_NODE);
        reader.nextTag();
        return Boolean.TRUE;
    }
    if (XMLStreamConstants.START_ELEMENT == type && FALSE_NODE.equals(reader.getLocalName())) {
        reader.nextTag();
        reader.require(XMLStreamConstants.END_ELEMENT, null, FALSE_NODE);
        reader.nextTag();
        return Boolean.FALSE;
    }
    if (XMLStreamConstants.START_ELEMENT == type && REAL_NODE.equals(reader.getLocalName())) {
        String text = StaxUtilities.readSimpleTextNodeIfAvailable(reader, null, REAL_NODE);

        return Double.parseDouble(text);
    }
    if (XMLStreamConstants.START_ELEMENT == type && INTEGER_NODE.equals(reader.getLocalName())) {
        String text = StaxUtilities.readSimpleTextNodeIfAvailable(reader, null, INTEGER_NODE);

        return Long.parseLong(text);
    }
    if (XMLStreamConstants.START_ELEMENT == type && STRING_NODE.equals(reader.getLocalName())) {
        return StaxUtilities.readSimpleTextNodeIfAvailable(reader, null, STRING_NODE);
    }
    if (XMLStreamConstants.START_ELEMENT == type && DATA_NODE.equals(reader.getLocalName())) {
        return readData(reader);
    }
    if (XMLStreamConstants.START_ELEMENT == type && DATE_NODE.equals(reader.getLocalName())) {
        return readDate(reader);
    }
    if (XMLStreamConstants.START_ELEMENT == type && ARRAY_NODE.equals(reader.getLocalName())) {
        return readArray(reader);
    }
    if (XMLStreamConstants.START_ELEMENT == type && DICT_NODE.equals(reader.getLocalName())) {
        return readDict(reader);
    }
    throw new RuntimeException("Unexpected XML-Node: " + reader.getLocalName());
}

From source file:ar.com.zauber.commons.spring.test.impl.TamperdataHttpServletRequestFactory.java

/** hace el trabajo sucio 
 * @throws UnsupportedEncodingException */
private HttpServletRequest parse(final XMLStreamReader reader)
        throws XMLStreamException, UnsupportedEncodingException {
    final MockHttpServletRequest ret = new MockHttpServletRequest();
    ret.setMethod("POST");
    String header = null;/*from  ww w.j a  v a2 s .  c  om*/
    String postHeader = null;
    int event;
    while ((event = reader.next()) != XMLStreamConstants.END_DOCUMENT) {
        if (event == XMLStreamConstants.START_ELEMENT) {
            final String name = reader.getLocalName();
            if (name.equals("tdRequestHeader") || name.equals("tdPostHeader")) {
                header = reader.getAttributeValue(0);
            } else if (name.equals("tdPostElements")) {
                ret.setMethod("POST");
            } else if (name.equals("tdPostElement")) {
                postHeader = reader.getAttributeValue(0);
            }
        } else if (event == XMLStreamConstants.CHARACTERS) {
            String text = reader.getText();
            if (text.length() > 1 && Character.isWhitespace(text.charAt(0))) {
                text = text.substring(1);
            }
            if (text.length() > 1 && Character.isWhitespace(text.charAt(text.length() - 1))) {
                text = text.substring(0, text.length() - 1);
            }

            final String value = URLDecoder.decode(URLDecoder.decode(text, encoding), encoding);
            if (header != null) {
                ret.addHeader(header, value);
            } else if (postHeader != null) {
                ret.addParameter(postHeader, value);
            }
            header = null;
            postHeader = null;
        } else {
            header = null;
            postHeader = null;
        }
    }
    reader.close();
    return ret;
}

From source file:de.huxhorn.whistler.services.TagdefTagDefinitionService.java

public TagDefinition define(String tag) {
    if (tag.startsWith("#")) {
        tag = tag.substring(1);// w w  w .  ja v a2s  .  c  o m
    }
    XMLStreamReader2 xmlStreamReader = null;
    try {
        BasicHttpParams params = new BasicHttpParams();
        DefaultHttpClient httpclient = new DefaultHttpClient(params);

        URI uri = URIUtils.createURI("http", "api.tagdef.com", -1, "/one." + tag, null, null);
        HttpGet httpget = new HttpGet(uri);
        if (logger.isDebugEnabled())
            logger.debug("HttpGet.uri={}", httpget.getURI());
        HttpResponse response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();

            /*
            <?xml version="1.0" encoding="UTF-8"?>
            <defs>
               <def>
                  <text>#ff is the same as (short for) #followfriday.</text>
                  <time>2009-05-08 00:00:00</time>
                  <upvotes>38</upvotes>
                  <downvotes>7</downvotes>
                  <uri>http://tagdef.com/ff</uri>
               </def>
            </defs>
                    
            <?xml version="1.0" encoding="UTF-8"?>
            <defs>
               <uri>http://tagdef.com/nonexisting</uri>
            </defs>
             */

            xmlStreamReader = (XMLStreamReader2) WstxInputFactory.newInstance().createXMLStreamReader(instream);
            while (xmlStreamReader.hasNext()) {
                int type = xmlStreamReader.next();
                if (type == XMLStreamConstants.START_ELEMENT) {
                    String tagName = xmlStreamReader.getName().getLocalPart();
                    if ("def".equals(tagName)) {
                        TagDefinition result = new TagDefinition();
                        result.setTag("#" + tag);
                        while (xmlStreamReader.hasNext()) {
                            type = xmlStreamReader.next();
                            if (type == XMLStreamConstants.START_ELEMENT) {
                                tagName = xmlStreamReader.getName().getLocalPart();
                                if ("text".equals(tagName)) {
                                    result.setDefinition(xmlStreamReader.getElementText());
                                } else if ("uri".equals(tagName)) {
                                    result.setUrl(xmlStreamReader.getElementText());
                                }
                            } else if (type == XMLStreamConstants.END_ELEMENT) {
                                tagName = xmlStreamReader.getName().getLocalPart();
                                if ("def".equals(tagName)) {
                                    break;
                                }
                            }
                        }

                        return result;
                    }
                }
            }
            /*
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
            StringBuilder builder=new StringBuilder();
            for(;;)
            {
               String line = reader.readLine();
               if(line == null)
               {
                  break;
               }
               if(builder.length() != 0)
               {
                  builder.append("\n");
               }
               builder.append(line);
            }
            if(logger.isInfoEnabled()) logger.info("Result: {}", builder);
            */
        }
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception!", ex);
    } catch (URISyntaxException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception!", ex);
    } catch (XMLStreamException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception!", ex);
    } finally {
        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.closeCompletely();
            } catch (XMLStreamException e) {
                // ignore
            }
        }
    }
    return null;
}

From source file:de.huxhorn.whistler.services.RealurlUrlUnshortener.java

public String unshorten(String url) {

    XMLStreamReader2 xmlStreamReader = null;
    try {/*from   ww  w . ja v  a  2s. c o m*/
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        // http://realurl.org/api/v1/getrealurl.php?url=
        qparams.add(new BasicNameValuePair("url", url));
        BasicHttpParams params = new BasicHttpParams();

        DefaultHttpClient httpclient = new DefaultHttpClient(params);

        URI uri = URIUtils.createURI("http", "realurl.org", -1, "/api/v1/getrealurl.php",
                URLEncodedUtils.format(qparams, "UTF-8"), null);
        HttpGet httpget = new HttpGet(uri);
        if (logger.isDebugEnabled())
            logger.debug("HttpGet.uri={}", httpget.getURI());
        HttpResponse response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            xmlStreamReader = (XMLStreamReader2) WstxInputFactory.newInstance().createXMLStreamReader(instream);

            /*
            <root>
              <status>1</status>
              <url>
                 <short>http://bit.ly/10QRTY</short>
                 <real>
                 http://uk.techcrunch.com/2009/04/09/tweetmeme-re-launches-to-gun-for-top-of-the-twitter-link-tree/
                 </real>
              </url>
            </root>
             */
            while (xmlStreamReader.hasNext()) {
                int type = xmlStreamReader.next();
                if (type == XMLStreamConstants.START_ELEMENT) {
                    if ("real".equals(xmlStreamReader.getName().getLocalPart())) {
                        return xmlStreamReader.getElementText();
                    }
                }
            }
            /*
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
            StringBuilder builder=new StringBuilder();
            for(;;)
            {
               String line = reader.readLine();
               if(line == null)
               {
                  break;
               }
               if(builder.length() != 0)
               {
                  builder.append("\n");
               }
               builder.append(line);
            }
            if(logger.isInfoEnabled()) logger.info("Result: {}", builder);
            */
        }
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception!", ex);
    } catch (URISyntaxException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception!", ex);
    } catch (XMLStreamException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception!", ex);
    } finally {
        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.closeCompletely();
            } catch (XMLStreamException e) {
                // ignore
            }
        }
    }
    return null;
}

From source file:net.bulletin.pdi.xero.step.support.XMLChunkerImpl.java

private String pullNextXmlChunkFromTopElementOnStack(XMLChunkerState data) throws KettleException {
    Stack<String> elementStack = data.getElementStack();
    XMLStreamReader xmlStreamReader = data.getXmlStreamReader();

    int elementStackDepthOnEntry = elementStack.size();
    StringWriter stringWriter = new StringWriter();

    try {/*w  ww.  j  a  va 2s . c  o  m*/
        XMLStreamWriter xmlStreamWriter = data.getXmlOutputFactory().createXMLStreamWriter(stringWriter);

        xmlStreamWriter.writeStartDocument(CharEncoding.UTF_8, "1.0");

        // put the current element on because presumably it's the open element for the one
        // that is being looked for.

        XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter);

        while (xmlStreamReader.hasNext() & elementStack.size() >= elementStackDepthOnEntry) {

            switch (xmlStreamReader.next()) {

            case XMLStreamConstants.END_DOCUMENT:
                break; // handled below explicitly.

            case XMLStreamConstants.END_ELEMENT:
                elementStack.pop();
                XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter);
                break;

            case XMLStreamConstants.START_ELEMENT:
                elementStack.push(xmlStreamReader.getLocalName());
                XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter);
                break;

            default:
                XmlReaderToWriter.write(xmlStreamReader, xmlStreamWriter);
                break;

            }

        }

        xmlStreamWriter.writeEndDocument();
        xmlStreamWriter.close();
    } catch (Exception e) {
        throw new KettleException("unable to process a chunk of the xero xml stream", e);
    }

    return stringWriter.toString();
}