Example usage for javax.xml.stream XMLStreamReader getAttributeValue

List of usage examples for javax.xml.stream XMLStreamReader getAttributeValue

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamReader getAttributeValue.

Prototype

public String getAttributeValue(String namespaceURI, String localName);

Source Link

Document

Returns the normalized attribute value of the attribute with the namespace and localName If the namespaceURI is null the namespace is not checked for equality

Usage

From source file:hudson.model.ExternalRun.java

/**
 * Instead of performing a build, accept the log and the return code from a
 * remote machine.//from  w  w  w  . j av a2 s  .c om
 *
 * <p> The format of the XML is:
 *
 * <pre><xmp>
 * <run>
 *  <log>...console output...</log>
 *  <result>exit code</result>
 * </run>
 * </xmp></pre>
 */
@SuppressWarnings({ "Since15" })
public void acceptRemoteSubmission(final Reader in) throws IOException {
    final long[] duration = new long[1];
    run(new Runner() {
        private String elementText(XMLStreamReader r) throws XMLStreamException {
            StringBuilder buf = new StringBuilder();
            while (true) {
                int type = r.next();
                if (type == CHARACTERS || type == CDATA) {
                    buf.append(r.getTextCharacters(), r.getTextStart(), r.getTextLength());
                } else {
                    return buf.toString();
                }
            }
        }

        public Result run(BuildListener listener) throws Exception {
            PrintStream logger = null;
            try {
                logger = new PrintStream(new DecodingStream(listener.getLogger()));

                XMLInputFactory xif = XMLInputFactory.newInstance();
                XMLStreamReader p = xif.createXMLStreamReader(in);

                p.nextTag(); // get to the <run>
                p.nextTag(); // get to the <log>

                charset = p.getAttributeValue(null, "content-encoding");
                while (p.next() != END_ELEMENT) {
                    int type = p.getEventType();
                    if (type == CHARACTERS || type == CDATA) {
                        logger.print(p.getText());
                    }
                }
                p.nextTag(); // get to <result>

                Result r = Integer.parseInt(elementText(p)) == 0 ? Result.SUCCESS : Result.FAILURE;

                p.nextTag(); // get to <duration> (optional)
                if (p.getEventType() == START_ELEMENT && p.getLocalName().equals("duration")) {
                    duration[0] = Long.parseLong(elementText(p));
                }

                return r;
            } finally {
                IOUtils.closeQuietly(logger);
            }
        }

        public void post(BuildListener listener) {
            // do nothing
        }

        public void cleanUp(BuildListener listener) {
            // do nothing
        }
    });

    if (duration[0] != 0) {
        super.duration = duration[0];
        // save the updated duration
        save();
    }
}

From source file:com.predic8.membrane.core.http.xml.Response.java

@Override
protected void parseChildren(XMLStreamReader token, String child) throws Exception {
    if (Headers.ELEMENT_NAME.equals(child)) {
        headers = (Headers) new Headers().parse(token);
    } else if ("status".equals(child)) {
        statusCode = Integer// w w w. j a  v  a 2  s .c  o  m
                .parseInt(StringUtils.defaultIfBlank(token.getAttributeValue("", "status-code"), "0"));
        statusMessage = "";
        while (token.hasNext()) {
            token.next();
            if (token.isStartElement()) {
                parseChildren(token, token.getName().getLocalPart());
            } else if (token.isCharacters()) {
                statusMessage += token.getText();
            } else if (token.isEndElement()) {
                break;
            }
        }
    }
}

From source file:com.hp.mqm.clt.XmlProcessorTest.java

private void assertElement(String elemName, boolean isReference, XMLStreamReader xmlStreamReader,
        Set<XmlElement> expectedElements) {
    String type = null;//from  w ww .j a v a 2  s. co  m
    String value;
    if (isReference) {
        value = xmlStreamReader.getAttributeValue(null, "id");
        Assert.assertNotNull(value);
    } else {
        type = xmlStreamReader.getAttributeValue(null, "type");
        value = xmlStreamReader.getAttributeValue(null, "value");
        Assert.assertNotNull(type);
        Assert.assertNotNull(value);
    }
    XmlElement element = new XmlElement(elemName, type, value);
    Assert.assertTrue(expectedElements.contains(element));
    expectedElements.remove(element);
}

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

/**
 * Returns the <code>WiktionaryParaphrase</code> for which the start tag was just encountered.
 * @param parser the <code>parser</code> being used on the current file
 * @return a <code>WiktionaryParaphrase</code> representing the data parsed
 * @throws javax.xml.stream.XMLStreamException
 *//*  www.  j  a v a2  s .  c o m*/
private WiktionaryParaphrase processWiktionaryParaphrase(XMLStreamReader parser) throws XMLStreamException {
    int lexUnitId;
    int wiktionaryId;
    int wiktionarySenseId;
    String wiktionarySense;
    boolean edited = false;
    WiktionaryParaphrase curWiki;

    lexUnitId = Integer.valueOf(parser.getAttributeValue(namespace, GermaNet.XML_LEX_UNIT_ID).substring(1));
    wiktionaryId = Integer
            .valueOf(parser.getAttributeValue(namespace, GermaNet.XML_WIKTIONARY_ID).substring(1));
    wiktionarySenseId = Integer.valueOf(parser.getAttributeValue(namespace, GermaNet.XML_WIKTIONARY_SENSE_ID));
    wiktionarySense = parser.getAttributeValue(namespace, GermaNet.XML_WIKTIONARY_SENSE);

    String edit = parser.getAttributeValue(namespace, GermaNet.XML_WIKTIONARY_EDITED);
    if (edit.equals(GermaNet.YES)) {
        edited = true;
    }

    curWiki = new WiktionaryParaphrase(lexUnitId, wiktionaryId, wiktionarySenseId, wiktionarySense, edited);

    return curWiki;
}

From source file:eionet.webq.converter.XmlSchemaExtractor.java

/**
 * Extracts {@code @xsi:noNamespaceSchemaLocation} or {@code @xsi:schemaLocation} attribute value from xml root element.
 *
 * @param source source to be searched.//from ww  w  . ja v a2 s. com
 * @return {@code @xsi:noNamespaceSchemaLocation} or {@code @xsi:schemaLocation} attribute value, default {@code null}
 */
public String extractXmlSchema(byte[] source) {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    ByteArrayInputStream bais = new ByteArrayInputStream(source);
    XMLStreamReader xmlStreamReader = null;
    try {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(bais);
        while (xmlStreamReader.hasNext()) {
            if (xmlStreamReader.next() == START_ELEMENT) {
                return StringUtils.defaultString(
                        parseNoNamespaceSchemaLocation(xmlStreamReader.getAttributeValue(XSI_NAMESPACE_URI,
                                "noNamespaceSchemaLocation")),
                        parseSchemaLocation(
                                xmlStreamReader.getAttributeValue(XSI_NAMESPACE_URI, "schemaLocation")));
            }
        }
    } catch (Exception e) {
        LOGGER.warn("exception thrown during extracting xml schema", e);
    } finally {
        IOUtils.closeQuietly(bais);
        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (XMLStreamException e) {
                LOGGER.warn("unable to close xml stream", e);
            }
        }
    }
    return null;
}

From source file:edu.indiana.d2i.htrc.io.index.solr.SolrClient.java

private NamedVector parseOneVolume(InputStream content) throws XMLStreamException, IOException {
    //      java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(content));
    //      String line = "";
    //      while ((line = br.readLine()) != null) {
    //         System.out.println(line);
    //      }/*from w w w  .  j av  a2s  .  c  o m*/
    //      br.close();

    String volumeID = null;
    Vector vector = null;
    XMLStreamReader parser = factory.createXMLStreamReader(content);
    while (parser.hasNext()) {
        int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT) {
            String attributeValue = parser.getAttributeValue(null, "name");
            if (attributeValue != null) {
                if (attributeValue.equals(VOLUME_ID)) {
                    volumeID = parser.getElementText();
                    volumeID = pairtree.uncleanId(volumeID);
                } else if (attributeValue.equals(VOLUME_OCR)) {
                    vector = createVector(parser);
                    break;
                }
            }
        }
    }

    NamedVector tv = new NamedVector(vector, volumeID);
    return tv;
}

From source file:com.microsoft.windowsazure.services.table.client.AtomPubParser.java

/**
 * Reserved for internal use. Reads the properties of an entity from the stream into a map of property names to
 * typed values. Reads the entity data as an AtomPub Entry Resource from the specified {@link XMLStreamReader} into
 * a map of <code>String</code> property names to {@link EntityProperty} data typed values.
 * /*from   w w w  .  j  a v a 2  s  .com*/
 * @param xmlr
 *            The <code>XMLStreamReader</code> to read the data from.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * 
 * @return
 *         A <code>java.util.HashMap</code> containing a map of <code>String</code> property names to
 *         {@link EntityProperty} data typed values found in the entity data.
 * @throws XMLStreamException
 *             if an error occurs accessing the stream.
 * @throws ParseException
 *             if an error occurs converting the input to a particular data type.
 */
protected static HashMap<String, EntityProperty> readProperties(final XMLStreamReader xmlr,
        final OperationContext opContext) throws XMLStreamException, ParseException {
    int eventType = xmlr.getEventType();
    xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.PROPERTIES);
    final HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>();

    while (xmlr.hasNext()) {
        eventType = xmlr.next();
        if (eventType == XMLStreamConstants.CHARACTERS) {
            xmlr.getText();
            continue;
        }

        if (eventType == XMLStreamConstants.START_ELEMENT
                && xmlr.getNamespaceURI().equals(ODataConstants.DATA_SERVICES_NS)) {
            final String key = xmlr.getLocalName();
            String val = Constants.EMPTY_STRING;
            String edmType = null;

            if (xmlr.getAttributeCount() > 0) {
                edmType = xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE);
            }

            // move to chars
            eventType = xmlr.next();

            if (eventType == XMLStreamConstants.CHARACTERS) {
                val = xmlr.getText();

                // end element
                eventType = xmlr.next();
            }

            xmlr.require(XMLStreamConstants.END_ELEMENT, null, key);

            final EntityProperty newProp = new EntityProperty(val, EdmType.parse(edmType));
            properties.put(key, newProp);
        } else if (eventType == XMLStreamConstants.END_ELEMENT && xmlr.getName().toString()
                .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) {
            // End read properties
            break;
        }
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.PROPERTIES);
    return properties;
}

From source file:edu.indiana.d2i.htrc.io.index.solr.SolrClient.java

public List<String> getIDList(String queryStr) {
    List<String> idlist = new ArrayList<String>();
    try {/*from  ww w . j  av a2  s.  c  o m*/
        // get num of hits
        String url = mainURL + QUERY_PREFIX + queryStr;

        System.out.println(url);

        HttpGet getRequest = new HttpGet(url);
        HttpResponse response = httpClient.execute(getRequest);
        InputStream content = response.getEntity().getContent();

        int numFound = 0;
        XMLStreamReader parser = factory.createXMLStreamReader(content);
        while (parser.hasNext()) {
            int event = parser.next();
            if (event == XMLStreamConstants.START_ELEMENT) {
                String attributeValue = parser.getAttributeValue(null, NUM_FOUND);
                if (attributeValue != null) {
                    numFound = Integer.valueOf(attributeValue);
                    break;
                }
            }
        }
        content.close();

        // 
        String idurl = mainURL + QUERY_PREFIX + queryStr + "&start=0&rows=" + numFound;
        //         String idurl = mainURL + QUERY_PREFIX + queryStr + "&start=0&rows=" + 10;
        HttpResponse idresponse = httpClient.execute(new HttpGet(idurl));
        InputStream idcontent = idresponse.getEntity().getContent();

        XMLStreamReader idparser = factory.createXMLStreamReader(idcontent);
        while (idparser.hasNext()) {
            int event = idparser.next();
            if (event == XMLStreamConstants.START_ELEMENT) {
                String attributeValue = idparser.getAttributeValue(null, "name");
                if (attributeValue != null) {
                    if (attributeValue.equals(SOLR_QUERY_ID)) {
                        String volumeId = idparser.getElementText();
                        idlist.add(volumeId);
                    }
                }
            }
        }
        idcontent.close();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (XMLStreamException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return idlist;
}

From source file:edu.indiana.d2i.htrc.io.index.solr.SolrClient.java

private Vector createVector(XMLStreamReader parser) throws XMLStreamException {
    Vector vector = new RandomAccessSparseVector(dictionary.size());
    while (parser.hasNext()) {
        int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT) {
            String attributeValue = parser.getAttributeValue(null, "name");
            if (attributeValue != null) {
                //               if (dictionary.containsKey(attributeValue)) {
                //                  parser.next();
                //                  int tf = Integer.valueOf(parser.getElementText());
                //                  vector.setQuick(dictionary.get(attributeValue), tf);
                //               }

                parser.next();/* ww w .java 2  s  . c  om*/
                int freq = Integer.valueOf(parser.getElementText());
                if (filter.accept(attributeValue, freq)) {
                    vector.setQuick(dictionary.get(attributeValue), freq);
                }
            }
        }
    }
    return vector;
}

From source file:edu.harvard.iq.dvn.core.analysis.NetworkDataServiceBean.java

/**"
 * If this key element is for a node, add a DataVariable to the
 * vertexDataTable, else add a DataVariable to edgeDataTable
 * @param xmlr/*  w  w  w  .java 2s .  com*/
 */
private void processKey(XMLStreamReader xmlr, NetworkDataFile ndf) {
    DataVariable dataVariable = new DataVariable();

    String attrName = xmlr.getAttributeValue(null, "attr.name");
    dataVariable.setName(attrName);
    dataVariable.setLabel(attrName);

    String attrType = xmlr.getAttributeValue(null, "attr.type");
    if (attrType.equals("string") || attrType.equals("boolean")) {
        dbgLog.fine("attrType = " + attrType);
        dataVariable.setVariableFormatType(varService.findVariableFormatTypeByName("character"));
    } else {
        dataVariable.setVariableFormatType(varService.findVariableFormatTypeByName("numeric"));

    }

    if (xmlr.getAttributeValue(null, "for").equals("node")) {
        ndf.getVertexDataTable().getDataVariables().add(dataVariable);
        dataVariable.setDataTable(ndf.getVertexDataTable());
    } else {
        ndf.getEdgeDataTable().getDataVariables().add(dataVariable);
        dataVariable.setDataTable(ndf.getEdgeDataTable());

    }
}