Example usage for javax.xml.stream XMLStreamReader getAttributeName

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

Introduction

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

Prototype

public QName getAttributeName(int index);

Source Link

Document

Returns the qname of the attribute at the provided index

Usage

From source file:com.tamingtext.tagrecommender.ExtractStackOverflowData.java

/** Extract as many as <code>limit</code> questions from the <code>reader</code>
 *  provided, writing them to <code>writer</code>.
 * @param reader//from  w  w  w  .  j  a  va2 s  . c  om
 * @param writer
 * @param limit
 * @return
 * @throws XMLStreamException
 */
protected int extractXMLData(XMLStreamReader reader, XMLStreamWriter writer, int limit)
        throws XMLStreamException {

    int questionCount = 0;
    int attrCount;
    boolean copyElement = false;

    writer.writeStartDocument();
    writer.writeStartElement("posts");
    writer.writeCharacters("\n");
    while (reader.hasNext() && questionCount < limit) {
        switch (reader.next()) {
        case XMLEvent.START_ELEMENT:
            if (reader.getLocalName().equals("row")) {
                attrCount = reader.getAttributeCount();
                for (int i = 0; i < attrCount; i++) {
                    // copy only the questions.
                    if (reader.getAttributeName(i).getLocalPart().equals("PostTypeId")
                            && reader.getAttributeValue(i).equals("1")) {
                        copyElement = true;
                        break;
                    }
                }

                if (copyElement) {
                    writer.writeCharacters("  ");
                    writer.writeStartElement("row");
                    for (int i = 0; i < attrCount; i++) {
                        writer.writeAttribute(reader.getAttributeName(i).getLocalPart(),
                                reader.getAttributeValue(i));
                    }
                    writer.writeEndElement();
                    writer.writeCharacters("\n");
                    copyElement = false;
                    questionCount++;
                }
            }
            break;
        }
    }
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
    writer.close();

    return questionCount;
}

From source file:jp.co.atware.solr.geta.GETAssocComponent.java

/**
 * GETAssoc?????<code>NamedList</code>???????
 * //ww  w  . ja v a2 s  . com
 * @param inputStream GETAssoc??
 * @return <code>NamedList</code>?
 * @throws FactoryConfigurationError
 * @throws IOException
 */
protected NamedList<Object> convertResult(InputStream inputStream)
        throws FactoryConfigurationError, IOException {
    NamedList<Object> result = new NamedList<Object>();
    LinkedList<NamedList<Object>> stack = new LinkedList<NamedList<Object>>();
    stack.push(result);
    try {
        XMLStreamReader xml = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
        while (xml.hasNext()) {
            switch (xml.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                NamedList<Object> element = new NamedList<Object>();
                stack.peek().add(xml.getName().toString(), element);
                stack.push(element);
                for (int i = 0; i < xml.getAttributeCount(); i++) {
                    String name = xml.getAttributeName(i).toString();
                    String value = xml.getAttributeValue(i);
                    ValueOf valueOf = valueTransMap.get(name);
                    if (valueOf != null) {
                        try {
                            element.add(name, valueOf.toValue(value));
                        } catch (NumberFormatException e) {
                            element.add(name, value);
                        }
                    } else {
                        element.add(name, value);
                    }
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                stack.pop();
                break;
            default:
                break;
            }
            xml.next();

        }
        xml.close();
    } catch (XMLStreamException e) {
        throw new IOException(e);
    }

    LOG.debug(result.toString());
    return result;
}

From source file:com.rapidminer.gui.properties.OperatorPropertyPanel.java

/**
 * Starts a progress thread which parses the parameter descriptions for the provided operator ,
 * cleans the {@link #parameterDescriptionCache}, and stores parsed descriptions in the
 * {@link #parameterDescriptionCache}.//from  ww w. ja v  a 2 s  .c o  m
 */
private void parseParameterDescriptions(final Operator operator) {
    parameterDescriptionCache.clear();
    URL documentationURL = OperatorDocumentationBrowser.getDocResourcePath(operator);
    if (documentationURL != null) {
        try (InputStream documentationStream = documentationURL.openStream()) {
            XMLStreamReader reader = XML_STREAM_FACTORY.createXMLStreamReader(documentationStream);
            String parameterKey = null;

            // The builder that stores the parameter description text
            StringBuilder parameterTextBuilder = null;
            boolean inParameters = false;
            while (reader.hasNext()) {
                switch (reader.next()) {
                case XMLStreamReader.START_ELEMENT:
                    if (!inParameters && reader.getLocalName().equals(TAG_PARAMETERS)) {
                        inParameters = true;
                    } else {
                        AttributesImpl attributes = new AttributesImpl();
                        for (int i = 0; i < reader.getAttributeCount(); i++) {
                            attributes.addAttribute("", reader.getAttributeLocalName(i),
                                    reader.getAttributeName(i).toString(), reader.getAttributeType(i),
                                    reader.getAttributeValue(i));
                        }

                        // Check if no parameter was found
                        if (reader.getLocalName().equals(TAG_PARAMETER)) {
                            parameterKey = attributes.getValue(ATTRIBUTE_PARAMETER_KEY);

                            // In case a parameter key was found, create a new string
                            // builder
                            if (parameterKey != null) {
                                parameterTextBuilder = new StringBuilder();
                            }
                        }

                        if (parameterTextBuilder != null) {
                            appendParameterStartTag(reader.getLocalName(), attributes, parameterTextBuilder);
                        }
                    }
                    break;
                case XMLStreamReader.END_ELEMENT:
                    // end parsing when end of parameters element is reached
                    if (reader.getLocalName().equals(TAG_PARAMETERS)) {
                        return;
                    }

                    if (parameterTextBuilder != null) {

                        // otherwise add element to description text
                        parameterTextBuilder.append("</");
                        parameterTextBuilder.append(reader.getLocalName());
                        parameterTextBuilder.append(">");

                        // Store description when parameter element ends
                        if (reader.getLocalName().equals(TAG_PARAMETER)) {
                            final String parameterDescription = parameterTextBuilder.toString();
                            final String key = parameterKey;
                            if (!parameterDescriptionCache.containsKey(parameterKey)) {
                                Source xmlSource = new StreamSource(new StringReader(parameterDescription));
                                try {
                                    String desc = OperatorDocToHtmlConverter.applyXSLTTransformation(xmlSource);
                                    parameterDescriptionCache.put(key, StringEscapeUtils.unescapeHtml(desc));
                                } catch (TransformerException e) {
                                    // ignore
                                }
                            }
                        }
                    }
                    break;
                case XMLStreamReader.CHARACTERS:
                    if (parameterTextBuilder != null) {
                        parameterTextBuilder.append(StringEscapeUtils.escapeHtml(reader.getText()));
                    }
                    break;
                default:
                    // ignore other events
                    break;
                }
            }
        } catch (IOException | XMLStreamException e) {
            // ignore
        }
    }
}

From source file:de.uzk.hki.da.model.ObjectPremisXmlWriter.java

/**
 * Integrate jhove data.//from w w  w . java 2 s  .  c  o  m
 *
 * @param jhoveFilePath the jhove file path
 * @param tab the tab
 * @throws XMLStreamException the xML stream exception
 * @author Thomas Kleinke
 * @throws FileNotFoundException 
 */
private void integrateJhoveData(String jhoveFilePath, int tab)
        throws XMLStreamException, FileNotFoundException {
    File jhoveFile = new File(jhoveFilePath);
    if (!jhoveFile.exists())
        throw new FileNotFoundException("file does not exist. " + jhoveFile);

    FileInputStream inputStream = null;

    inputStream = new FileInputStream(jhoveFile);

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader streamReader = inputFactory.createXMLStreamReader(inputStream);

    boolean textElement = false;

    while (streamReader.hasNext()) {
        int event = streamReader.next();

        switch (event) {

        case XMLStreamConstants.START_ELEMENT:
            writer.writeDTD("\n");
            indent(tab);
            tab++;

            String prefix = streamReader.getPrefix();

            if (prefix != null && !prefix.equals("")) {
                writer.setPrefix(prefix, streamReader.getNamespaceURI());
                writer.writeStartElement(streamReader.getNamespaceURI(), streamReader.getLocalName());
            } else
                writer.writeStartElement(streamReader.getLocalName());

            for (int i = 0; i < streamReader.getNamespaceCount(); i++)
                writer.writeNamespace(streamReader.getNamespacePrefix(i), streamReader.getNamespaceURI(i));

            for (int i = 0; i < streamReader.getAttributeCount(); i++) {
                QName qname = streamReader.getAttributeName(i);
                String attributeName = qname.getLocalPart();
                String attributePrefix = qname.getPrefix();
                if (attributePrefix != null && !attributePrefix.equals(""))
                    attributeName = attributePrefix + ":" + attributeName;

                writer.writeAttribute(attributeName, streamReader.getAttributeValue(i));
            }

            break;

        case XMLStreamConstants.CHARACTERS:
            if (!streamReader.isWhiteSpace()) {
                writer.writeCharacters(streamReader.getText());
                textElement = true;
            }
            break;

        case XMLStreamConstants.END_ELEMENT:
            tab--;

            if (!textElement) {
                writer.writeDTD("\n");
                indent(tab);
            }

            writer.writeEndElement();
            textElement = false;
            break;

        default:
            break;
        }
    }

    streamReader.close();
    try {
        inputStream.close();
    } catch (IOException e) {
        throw new RuntimeException("Failed to close input stream", e);
    }
}

From source file:de.uzk.hki.da.cb.CreatePremisAction.java

/**
 * Accepts a premis.xml file and creates a new xml file for each jhove section  
 * //w  ww  .j a  v a  2s  .com
 * @author Thomas Kleinke
 * Extract jhove data.
 *
 * @param premisFilePath the premis file path
 * @param outputFolder the output folder
 * @throws XMLStreamException the xML stream exception
 */
public void extractJhoveData(String premisFilePath, String outputFolder) throws XMLStreamException {

    outputFolder += "/premis_output/";

    FileInputStream inputStream = null;

    try {
        inputStream = new FileInputStream(premisFilePath);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Couldn't find file " + premisFilePath, e);
    }

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader streamReader = inputFactory.createXMLStreamReader(inputStream);

    boolean textElement = false;
    boolean jhoveSection = false;
    boolean objectIdentifierValue = false;
    int tab = 0;
    String fileId = "";

    while (streamReader.hasNext()) {
        int event = streamReader.next();

        switch (event) {

        case XMLStreamConstants.START_ELEMENT:

            if (streamReader.getLocalName().equals("jhove")) {
                jhoveSection = true;
                String outputFilePath = outputFolder + fileId.replace('/', '_').replace('.', '_') + ".xml";
                if (!new File(outputFolder).exists())
                    new File(outputFolder).mkdirs();
                writer = startNewDocument(outputFilePath);
            }

            if (streamReader.getLocalName().equals("objectIdentifierValue"))
                objectIdentifierValue = true;

            if (jhoveSection) {
                writer.writeDTD("\n");
                indent(tab);
                tab++;

                String prefix = streamReader.getPrefix();

                if (prefix != null && !prefix.equals("")) {
                    writer.setPrefix(prefix, streamReader.getNamespaceURI());
                    writer.writeStartElement(streamReader.getNamespaceURI(), streamReader.getLocalName());
                } else
                    writer.writeStartElement(streamReader.getLocalName());

                for (int i = 0; i < streamReader.getNamespaceCount(); i++)
                    writer.writeNamespace(streamReader.getNamespacePrefix(i), streamReader.getNamespaceURI(i));

                for (int i = 0; i < streamReader.getAttributeCount(); i++) {
                    QName qname = streamReader.getAttributeName(i);
                    String attributeName = qname.getLocalPart();
                    String attributePrefix = qname.getPrefix();
                    if (attributePrefix != null && !attributePrefix.equals(""))
                        attributeName = attributePrefix + ":" + attributeName;

                    writer.writeAttribute(attributeName, streamReader.getAttributeValue(i));
                }
            }

            break;

        case XMLStreamConstants.CHARACTERS:
            if (objectIdentifierValue) {
                fileId = streamReader.getText();
                objectIdentifierValue = false;
            }

            if (jhoveSection && !streamReader.isWhiteSpace()) {
                writer.writeCharacters(streamReader.getText());
                textElement = true;
            }
            break;

        case XMLStreamConstants.END_ELEMENT:
            if (jhoveSection) {
                tab--;

                if (!textElement) {
                    writer.writeDTD("\n");
                    indent(tab);
                }

                writer.writeEndElement();
                textElement = false;

                if (streamReader.getLocalName().equals("jhove")) {
                    jhoveSection = false;
                    finalizeDocument();
                }
            }
            break;

        case XMLStreamConstants.END_DOCUMENT:
            streamReader.close();
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException("Failed to close input stream", e);
            }
            break;

        default:
            break;
        }
    }
}

From source file:edu.indiana.d2i.htrc.portal.HTRCAgentClient.java

private Map<String, JobDetailsBean> parseJobDetailBeans(InputStream stream) throws XMLStreamException {
    Map<String, JobDetailsBean> res = new TreeMap<String, JobDetailsBean>();
    XMLStreamReader parser = factory.createXMLStreamReader(stream);
    while (parser.hasNext()) {
        int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (parser.hasName()) {
                if (parser.getLocalName().equals("job_status")) {
                    // one job status
                    JobDetailsBean detail = new JobDetailsBean();
                    Map<String, String> jobParams = new HashMap<String, String>();
                    Map<String, String> results = new HashMap<String, String>();
                    int innerEvent = parser.next();
                    while (true) {
                        if (innerEvent == XMLStreamConstants.END_ELEMENT
                                && parser.getLocalName().equals("job_status")) {
                            break;
                        }/*  ww w . ja v  a  2  s.  c o m*/

                        if (innerEvent == XMLStreamConstants.START_ELEMENT && parser.hasName()) {
                            // single tag
                            if (parser.getLocalName().equals("job_name")) {
                                detail.setJobTitle(parser.getElementText());
                            } else if (parser.getLocalName().equals("user")) {
                                detail.setUserName(parser.getElementText());
                            } else if (parser.getLocalName().equals("algorithm")) {
                                detail.setAlgorithmName(parser.getElementText());
                            } else if (parser.getLocalName().equals("job_id")) {
                                detail.setJobId(parser.getElementText());
                            } else if (parser.getLocalName().equals("date")) {
                                detail.setLastUpdatedDate(parser.getElementText());
                            }

                            // parameters
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.ONEPARAM)) {
                                String name, value;
                                name = value = "";
                                for (int i = 0; i < 3; i++) {
                                    if (parser.getAttributeName(i).toString().equals("name"))
                                        name = parser.getAttributeValue(i);
                                    if (parser.getAttributeName(i).toString().equals("value"))
                                        value = parser.getAttributeValue(i);
                                }
                                jobParams.put(name, value);
                            }

                            // status
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.STATUS)) {
                                String status = parser.getAttributeValue(0);
                                detail.setJobStatus(status);
                            }

                            // results
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.RESULT)) {
                                String name = parser.getAttributeValue(0);
                                String value = parser.getElementText();
                                results.put(name, value);
                            }

                            // message
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.MESSAGE)) {
                                detail.setMessage(parser.getElementText());
                            }

                            // saved or unsaved
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.SAVEDORNOT)) {
                                detail.setJobSavedStr(parser.getElementText());
                            }
                        }
                        innerEvent = parser.next();
                    }
                    detail.setJobParams(jobParams);
                    detail.setResults(results);
                    res.put(detail.getJobId(), detail);
                }
            }
        }
    }
    return res;
}

From source file:org.apache.axis2.jaxws.message.util.impl.SAAJConverterImpl.java

/**
 * add attributes/* w  ww . j  av a 2 s  . c  om*/
 *
 * @param NameCreator nc
 * @param element     SOAPElement which is the target of the new attributes
 * @param reader      XMLStreamReader whose cursor is at START_ELEMENT
 * @throws SOAPException
 */
protected void addAttributes(NameCreator nc, SOAPElement element, XMLStreamReader reader) throws SOAPException {
    if (log.isDebugEnabled()) {
        log.debug("addAttributes: Entry");
    }

    // Add the attributes from the reader
    int size = reader.getAttributeCount();
    for (int i = 0; i < size; i++) {
        QName qName = reader.getAttributeName(i);
        String prefix = reader.getAttributePrefix(i);
        String value = reader.getAttributeValue(i);
        Name name = nc.createName(qName.getLocalPart(), prefix, qName.getNamespaceURI());
        element.addAttribute(name, value);

        try {
            if (log.isDebugEnabled()) {
                log.debug("Setting attrType");
            }
            String namespace = qName.getNamespaceURI();
            Attr attr = null; // This is an org.w3c.dom.Attr
            if (namespace == null || namespace.length() == 0) {
                attr = element.getAttributeNode(qName.getLocalPart());
            } else {
                attr = element.getAttributeNodeNS(namespace, qName.getLocalPart());
            }
            if (attr != null) {
                String attrType = reader.getAttributeType(i);
                attr.setUserData(SAAJConverter.OM_ATTRIBUTE_KEY, attrType, null);
                if (log.isDebugEnabled()) {
                    log.debug("Storing attrType in UserData: " + attrType);
                }
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("An error occured while processing attrType: " + e.getMessage());
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("addAttributes: Exit");
    }
}

From source file:org.apache.ddlutils.io.DatabaseIO.java

/**
 * Reads a database element from the XML stream reader.
 * /*from   w  ww  .jav  a 2s  . co  m*/
 * @param xmlReader The reader
 * @return The database object
 */
private Database readDatabaseElement(XMLStreamReader xmlReader) throws XMLStreamException, IOException {
    Database model = new Database();

    for (int idx = 0; idx < xmlReader.getAttributeCount(); idx++) {
        QName attrQName = xmlReader.getAttributeName(idx);

        if (isSameAs(attrQName, QNAME_ATTRIBUTE_NAME)) {
            model.setName(xmlReader.getAttributeValue(idx));
        } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_DEFAULT_ID_METHOD)) {
            model.setIdMethod(xmlReader.getAttributeValue(idx));
        } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_VERSION)) {
            model.setVersion(xmlReader.getAttributeValue(idx));
        }
    }
    readTableElements(xmlReader, model);
    consumeRestOfElement(xmlReader);
    return model;
}

From source file:org.apache.ddlutils.io.DatabaseIO.java

/**
 * Reads a table element from the XML stream reader.
 * //from  w  w  w .ja  v a  2  s. c om
 * @param xmlReader The reader
 * @return The table object
 */
private Table readTableElement(XMLStreamReader xmlReader) throws XMLStreamException, IOException {
    Table table = new Table();

    for (int idx = 0; idx < xmlReader.getAttributeCount(); idx++) {
        QName attrQName = xmlReader.getAttributeName(idx);

        if (isSameAs(attrQName, QNAME_ATTRIBUTE_NAME)) {
            table.setName(xmlReader.getAttributeValue(idx));
        } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_DESCRIPTION)) {
            table.setDescription(xmlReader.getAttributeValue(idx));
        }
    }
    readTableSubElements(xmlReader, table);
    consumeRestOfElement(xmlReader);
    return table;
}

From source file:org.apache.ddlutils.io.DatabaseIO.java

/**
 * Reads a column element from the XML stream reader.
 * //from  www.  j av  a2  s  .  co  m
 * @param xmlReader The reader
 * @return The column object
 */
private Column readColumnElement(XMLStreamReader xmlReader) throws XMLStreamException, IOException {
    Column column = new Column();

    for (int idx = 0; idx < xmlReader.getAttributeCount(); idx++) {
        QName attrQName = xmlReader.getAttributeName(idx);

        if (isSameAs(attrQName, QNAME_ATTRIBUTE_NAME)) {
            column.setName(xmlReader.getAttributeValue(idx));
        } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_PRIMARY_KEY)) {
            column.setPrimaryKey(getAttributeValueAsBoolean(xmlReader, idx));
        } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_REQUIRED)) {
            column.setRequired(getAttributeValueAsBoolean(xmlReader, idx));
        } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_TYPE)) {
            column.setType(xmlReader.getAttributeValue(idx));
        } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_SIZE)) {
            column.setSize(getAttributeValueBeingNullAware(xmlReader, idx));
        } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_DEFAULT)) {
            column.setDefaultValue(xmlReader.getAttributeValue(idx));
        } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_AUTO_INCREMENT)) {
            column.setAutoIncrement(getAttributeValueAsBoolean(xmlReader, idx));
        } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_DESCRIPTION)) {
            column.setDescription(xmlReader.getAttributeValue(idx));
        } else if (isSameAs(attrQName, QNAME_ATTRIBUTE_JAVA_NAME)) {
            column.setJavaName(xmlReader.getAttributeValue(idx));
        }
    }
    consumeRestOfElement(xmlReader);
    return column;
}