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(int index);

Source Link

Document

Returns the value of the attribute at the index

Usage

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   w  w w.  j  ava 2s. 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:ddf.catalog.source.solr.DynamicSchemaResolver.java

/**
 * Given xml as a string, this method will parse out element text and CDATA text. It separates
 * each by one space character.//from w w w  .  j a v  a  2 s . c  om
 *
 * @param xmlDatas List of XML as {@code String}
 * @return parsed CDATA and element text
 */
protected List<String> parseTextFrom(List<Serializable> xmlDatas) {

    StringBuilder builder = new StringBuilder();
    List<String> parsedTexts = new ArrayList<>();
    XMLStreamReader xmlStreamReader = null;
    StringReader sr = null;
    long starttime = System.currentTimeMillis();

    try {
        for (Serializable xmlData : xmlDatas) {
            // xml parser does not handle leading whitespace
            sr = new StringReader(xmlData.toString());
            xmlStreamReader = XML_INPUT_FACTORY.createXMLStreamReader(sr);

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

                if (event == XMLStreamConstants.CHARACTERS || event == XMLStreamConstants.CDATA) {

                    String text = xmlStreamReader.getText();

                    if (StringUtils.isNotBlank(text)) {
                        builder.append(" ").append(text.trim());
                    }

                }
                if (event == XMLStreamConstants.START_ELEMENT) {
                    for (int i = 0; i < xmlStreamReader.getAttributeCount(); i++) {

                        String text = xmlStreamReader.getAttributeValue(i);

                        if (StringUtils.isNotBlank(text)) {
                            builder.append(" ").append(text.trim());
                        }
                    }
                }
            }
            parsedTexts.add(builder.toString());
            builder.setLength(0);
        }
    } catch (XMLStreamException e1) {
        LOGGER.warn("Failure occurred in parsing the xml data. No data has been stored or indexed.", e1);
    } finally {
        IOUtils.closeQuietly(sr);
        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (XMLStreamException e) {
                LOGGER.debug("Exception closing XMLStreamReader", e);
            }
        }
    }
    long endTime = System.currentTimeMillis();

    LOGGER.debug("Parsing took {} ms", endTime - starttime);

    return parsedTexts;
}

From source file:ddf.security.assertion.impl.SecurityAssertionImpl.java

/**
 * Parses the SecurityToken by wrapping within an AssertionWrapper.
 *
 * @param securityToken SecurityToken//from w w w . ja va 2s.com
 */
private void parseToken(SecurityToken securityToken) {
    XMLStreamReader xmlStreamReader = StaxUtils.createXMLStreamReader(securityToken.getToken());

    try {
        AttrStatement attributeStatement = null;
        AuthenticationStatement authenticationStatement = null;
        Attr attribute = null;
        int attrs = 0;
        while (xmlStreamReader.hasNext()) {
            int event = xmlStreamReader.next();
            switch (event) {
            case XMLStreamConstants.START_ELEMENT: {
                String localName = xmlStreamReader.getLocalName();
                switch (localName) {
                case NameID.DEFAULT_ELEMENT_LOCAL_NAME:
                    name = xmlStreamReader.getElementText();
                    for (int i = 0; i < xmlStreamReader.getAttributeCount(); i++) {
                        if (xmlStreamReader.getAttributeLocalName(i).equals(NameID.FORMAT_ATTRIB_NAME)) {
                            nameIDFormat = xmlStreamReader.getAttributeValue(i);
                            break;
                        }
                    }
                    break;
                case AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME:
                    attributeStatement = new AttrStatement();
                    attributeStatements.add(attributeStatement);
                    break;
                case AuthnStatement.DEFAULT_ELEMENT_LOCAL_NAME:
                    authenticationStatement = new AuthenticationStatement();
                    authenticationStatements.add(authenticationStatement);
                    attrs = xmlStreamReader.getAttributeCount();
                    for (int i = 0; i < attrs; i++) {
                        String name = xmlStreamReader.getAttributeLocalName(i);
                        String value = xmlStreamReader.getAttributeValue(i);
                        if (AuthnStatement.AUTHN_INSTANT_ATTRIB_NAME.equals(name)) {
                            authenticationStatement.setAuthnInstant(DateTime.parse(value));
                        }
                    }
                    break;
                case AuthnContextClassRef.DEFAULT_ELEMENT_LOCAL_NAME:
                    if (authenticationStatement != null) {
                        String classValue = xmlStreamReader.getText();
                        classValue = classValue.trim();
                        AuthenticationContextClassRef authenticationContextClassRef = new AuthenticationContextClassRef();
                        authenticationContextClassRef.setAuthnContextClassRef(classValue);
                        AuthenticationContext authenticationContext = new AuthenticationContext();
                        authenticationContext.setAuthnContextClassRef(authenticationContextClassRef);
                        authenticationStatement.setAuthnContext(authenticationContext);
                    }
                    break;
                case Attribute.DEFAULT_ELEMENT_LOCAL_NAME:
                    attribute = new Attr();
                    if (attributeStatement != null) {
                        attributeStatement.addAttribute(attribute);
                    }
                    attrs = xmlStreamReader.getAttributeCount();
                    for (int i = 0; i < attrs; i++) {
                        String name = xmlStreamReader.getAttributeLocalName(i);
                        String value = xmlStreamReader.getAttributeValue(i);
                        if (Attribute.NAME_ATTTRIB_NAME.equals(name)) {
                            attribute.setName(value);
                        } else if (Attribute.NAME_FORMAT_ATTRIB_NAME.equals(name)) {
                            attribute.setNameFormat(value);
                        }
                    }
                    break;
                case AttributeValue.DEFAULT_ELEMENT_LOCAL_NAME:
                    XSString xsString = new XMLString();
                    xsString.setValue(xmlStreamReader.getElementText());
                    if (attribute != null) {
                        attribute.addAttributeValue(xsString);
                    }
                    break;
                case Issuer.DEFAULT_ELEMENT_LOCAL_NAME:
                    issuer = xmlStreamReader.getElementText();
                    break;
                case Conditions.DEFAULT_ELEMENT_LOCAL_NAME:
                    attrs = xmlStreamReader.getAttributeCount();
                    for (int i = 0; i < attrs; i++) {
                        String name = xmlStreamReader.getAttributeLocalName(i);
                        String value = xmlStreamReader.getAttributeValue(i);
                        if (Conditions.NOT_BEFORE_ATTRIB_NAME.equals(name)) {
                            notBefore = DatatypeConverter.parseDateTime(value).getTime();
                        } else if (Conditions.NOT_ON_OR_AFTER_ATTRIB_NAME.equals(name)) {
                            notOnOrAfter = DatatypeConverter.parseDateTime(value).getTime();
                        }
                    }
                    break;
                case SubjectConfirmation.DEFAULT_ELEMENT_LOCAL_NAME:
                    attrs = xmlStreamReader.getAttributeCount();
                    for (int i = 0; i < attrs; i++) {
                        String name = xmlStreamReader.getAttributeLocalName(i);
                        String value = xmlStreamReader.getAttributeValue(i);
                        if (SubjectConfirmation.METHOD_ATTRIB_NAME.equals(name)) {
                            subjectConfirmations.add(value);
                        }
                    }
                case Assertion.DEFAULT_ELEMENT_LOCAL_NAME:
                    attrs = xmlStreamReader.getAttributeCount();
                    for (int i = 0; i < attrs; i++) {
                        String name = xmlStreamReader.getAttributeLocalName(i);
                        String value = xmlStreamReader.getAttributeValue(i);
                        if (Assertion.VERSION_ATTRIB_NAME.equals(name)) {
                            if ("2.0".equals(value)) {
                                tokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";
                            } else if ("1.1".equals(value)) {
                                tokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1";
                            }
                        }
                    }
                }
                break;
            }
            case XMLStreamConstants.END_ELEMENT: {
                String localName = xmlStreamReader.getLocalName();
                switch (localName) {
                case AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME:
                    attributeStatement = null;
                    break;
                case Attribute.DEFAULT_ELEMENT_LOCAL_NAME:
                    attribute = null;
                    break;
                default:
                    break;
                }
                break;
            }
            }
        }
    } catch (XMLStreamException e) {
        LOGGER.error("Unable to parse security token.", e);
    } finally {
        try {
            xmlStreamReader.close();
        } catch (XMLStreamException ignore) {
            //ignore
        }
    }
}

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

private AlgorithmDetailsBean parseAlgorithmDetailBean(InputStream stream) throws XMLStreamException {
    AlgorithmDetailsBean res = new AlgorithmDetailsBean();
    XMLStreamReader parser = factory.createXMLStreamReader(stream);

    List<AlgorithmDetailsBean.Parameter> parameters = new ArrayList<AlgorithmDetailsBean.Parameter>();
    List<String> authors = new ArrayList<String>();
    while (parser.hasNext()) {
        int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (parser.hasName()) {
                // only parse the info tag!
                if (parser.getLocalName().equals(AlgorithmDetailsBean.NAME)) {
                    res.setName(parser.getElementText());
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.VERSION)) {
                    res.setVersion(parser.getElementText());
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.DESCRIPTION)) {
                    res.setDescription(parser.getElementText());
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.SUPPORTURL)) {
                    res.setSupportUrl(parser.getElementText());
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.PARAMETER)) {
                    AlgorithmDetailsBean.Parameter parameter = new AlgorithmDetailsBean.Parameter();
                    int count = parser.getAttributeCount();
                    for (int i = 0; i < count; i++) {
                        if (parser.getAttributeLocalName(i).equals("required"))
                            parameter.setRequired(Boolean.valueOf(parser.getAttributeValue(i)));
                        if (parser.getAttributeLocalName(i).equals("type"))
                            parameter.setType(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("name"))
                            parameter.setName(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("defaultValue"))
                            parameter.setDefaultValue(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("validation"))
                            parameter.setValidation(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("validationError"))
                            parameter.setValidationError(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("readOnly"))
                            parameter.setReadOnly(Boolean.parseBoolean(parser.getAttributeValue(i)));
                    }// w  w  w.  ja  v  a  2  s  .  com
                    parser.nextTag();
                    if (parser.getLocalName().equals("label"))
                        parameter.setLabel(parser.getElementText());
                    parser.nextTag();
                    if (parser.getLocalName().equals("description"))
                        parameter.setDescription(parser.getElementText());
                    parameters.add(parameter);
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.AUTHOR)) {
                    int count = parser.getAttributeCount();
                    for (int i = 0; i < count; i++) {
                        if (parser.getAttributeLocalName(i).equals("name"))
                            authors.add(parser.getAttributeValue(i));
                    }
                }
            }
        }
    }
    res.setParameters(parameters);
    res.setAuthors(authors);
    return res;
}

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

/**
 * Integrate jhove data./* ww  w.j  a  v a  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:gima.neo4j.testsuite.osmcheck.OSMImporter.java

private Map<String, Object> extractProperties(String name, XMLStreamReader parser) {
    // <node id="269682538" lat="56.0420950" lon="12.9693483" user="sanna" uid="31450" visible="true" version="1" changeset="133823" timestamp="2008-06-11T12:36:28Z"/>
    // <way id="27359054" user="spull" uid="61533" visible="true" version="8" changeset="4707351" timestamp="2010-05-15T15:39:57Z">
    // <relation id="77965" user="Grillo" uid="13957" visible="true" version="24" changeset="5465617" timestamp="2010-08-11T19:25:46Z">
    LinkedHashMap<String, Object> properties = new LinkedHashMap<String, Object>();
    for (int i = 0; i < parser.getAttributeCount(); i++) {
        String prop = parser.getAttributeLocalName(i);
        String value = parser.getAttributeValue(i);
        if (name != null && prop.equals("id")) {
            prop = name + "_osm_id";
            name = null;//from www.j  a  v a  2s. c  om
        }
        if (prop.equals("lat") || prop.equals("lon")) {
            properties.put(prop, Double.parseDouble(value));
        } else if (name != null && prop.equals("version")) {
            properties.put(prop, Integer.parseInt(value));
        } else if (prop.equals("visible")) {
            if (!value.equals("true") && !value.equals("1")) {
                properties.put(prop, false);
            }
        } else if (prop.equals("timestamp")) {
            try {
                Date timestamp = timestampFormat.parse(value);
                properties.put(prop, timestamp.getTime());
            } catch (ParseException e) {
                error("Error parsing timestamp", e);
            }
        } else {
            properties.put(prop, value);
        }
    }
    if (name != null) {
        properties.put("name", name);
    }
    return properties;
}

From source file:com.ikanow.infinit.e.harvest.extraction.document.file.XmlToMetadataParser.java

/**
 * Parses XML and returns a new feed with the resulting HashMap as Metadata
 * @param reader XMLStreamReader using Stax to avoid out of memory errors
 * @return List of Feeds with their Metadata set
 *///from  w w  w.  j  ava  2  s .  c om
public List<DocumentPojo> parseDocument(XMLStreamReader reader) throws XMLStreamException {
    DocumentPojo doc = new DocumentPojo();
    List<DocumentPojo> docList = new ArrayList<DocumentPojo>();
    boolean justIgnored = false;
    boolean hitIdentifier = false;

    while (reader.hasNext()) {
        int eventCode = reader.next();

        switch (eventCode) {
        case (XMLStreamReader.START_ELEMENT): {
            String tagName = reader.getLocalName();

            if (null == levelOneFields || levelOneFields.size() == 0) {
                levelOneFields = new ArrayList<String>();
                levelOneFields.add(tagName);
                doc = new DocumentPojo();
                sb.delete(0, sb.length());
                justIgnored = false;
            } else if (levelOneFields.contains(tagName)) {
                sb.delete(0, sb.length());
                doc = new DocumentPojo();
                justIgnored = false;
            } else if ((null != ignoreFields) && ignoreFields.contains(tagName)) {
                justIgnored = true;
            } else {
                if (this.bPreserveCase) {
                    sb.append("<").append(tagName).append(">");
                } else {
                    sb.append("<").append(tagName.toLowerCase()).append(">");
                }
                justIgnored = false;
            }
            hitIdentifier = tagName.equalsIgnoreCase(PKElement);

            if (!justIgnored && (null != this.AttributePrefix)) { // otherwise ignore attributes anyway
                int nAttributes = reader.getAttributeCount();
                StringBuffer sb2 = new StringBuffer();
                for (int i = 0; i < nAttributes; ++i) {
                    sb2.setLength(0);
                    sb.append('<');

                    sb2.append(this.AttributePrefix);
                    if (this.bPreserveCase) {
                        sb2.append(reader.getAttributeLocalName(i).toLowerCase());
                    } else {
                        sb2.append(reader.getAttributeLocalName(i));
                    }
                    sb2.append('>');

                    sb.append(sb2);
                    sb.append("<![CDATA[").append(reader.getAttributeValue(i).trim()).append("]]>");
                    sb.append("</").append(sb2);
                }
            }
        }
            break;

        case (XMLStreamReader.CHARACTERS): {
            if (reader.getText().trim().length() > 0 && justIgnored == false)
                sb.append("<![CDATA[").append(reader.getText().trim()).append("]]>");
            if (hitIdentifier) {
                String tValue = reader.getText().trim();
                if (null != XmlSourceName) {
                    if (tValue.length() > 0) {
                        doc.setUrl(XmlSourceName + tValue);
                    }
                }
            }
        }
            break;
        case (XMLStreamReader.END_ELEMENT): {
            hitIdentifier = !reader.getLocalName().equalsIgnoreCase(PKElement);
            if ((null != ignoreFields) && !ignoreFields.contains(reader.getLocalName())) {
                if (levelOneFields.contains(reader.getLocalName())) {
                    JSONObject json;
                    try {
                        json = XML.toJSONObject(sb.toString());
                        for (String names : JSONObject.getNames(json)) {
                            JSONObject rec = null;
                            JSONArray jarray = null;

                            try {
                                jarray = json.getJSONArray(names);
                                doc.addToMetadata(names, handleJsonArray(jarray, false));
                            } catch (JSONException e) {
                                try {
                                    rec = json.getJSONObject(names);
                                    doc.addToMetadata(names, convertJsonObjectToLinkedHashMap(rec));
                                } catch (JSONException e2) {
                                    try {
                                        Object[] val = { json.getString(names) };
                                        doc.addToMetadata(names, val);
                                    } catch (JSONException e1) {
                                        e1.printStackTrace();
                                    }
                                }
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    sb.delete(0, sb.length());
                    docList.add(doc);
                } else {
                    if (this.bPreserveCase) {
                        sb.append("</").append(reader.getLocalName()).append(">");
                    } else {
                        sb.append("</").append(reader.getLocalName().toLowerCase()).append(">");
                    }

                }
            }
        } // (end case)
            break;
        } // (end switch)
    }
    return docList;
}

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  
 * /*www  .ja v  a  2 s .co  m*/
 * @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;
                        }/*w w w  .  j  a  v  a2 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:gima.neo4j.testsuite.osmcheck.OSMImporter.java

public void importFile(OSMWriter<?> osmWriter, String dataset, boolean allPoints, Charset charset)
        throws IOException, XMLStreamException {
    System.out.println("Importing with osm-writer: " + osmWriter);
    osmWriter.getOrCreateOSMDataset(layerName);
    osm_dataset = osmWriter.getDatasetId();

    long startTime = System.currentTimeMillis();
    long[] times = new long[] { 0L, 0L, 0L, 0L };
    javax.xml.stream.XMLInputFactory factory = javax.xml.stream.XMLInputFactory.newInstance();
    CountedFileReader reader = new CountedFileReader(dataset, charset);
    javax.xml.stream.XMLStreamReader parser = factory.createXMLStreamReader(reader);
    int countXMLTags = 0;
    beginProgressMonitor(100);/*from w w w.j  a  v a  2  s  .c  o m*/
    setLogContext(dataset);
    boolean startedWays = false;
    boolean startedRelations = false;
    try {
        ArrayList<String> currentXMLTags = new ArrayList<String>();
        int depth = 0;
        Map<String, Object> wayProperties = null;
        ArrayList<Long> wayNodes = new ArrayList<Long>();
        Map<String, Object> relationProperties = null;
        ArrayList<Map<String, Object>> relationMembers = new ArrayList<Map<String, Object>>();
        LinkedHashMap<String, Object> currentNodeTags = new LinkedHashMap<String, Object>();
        while (true) {
            updateProgressMonitor(reader.getPercentRead());
            incrLogContext();
            int event = parser.next();
            if (event == javax.xml.stream.XMLStreamConstants.END_DOCUMENT) {
                break;
            }
            switch (event) {
            case javax.xml.stream.XMLStreamConstants.START_ELEMENT:
                currentXMLTags.add(depth, parser.getLocalName());
                String tagPath = currentXMLTags.toString();
                if (tagPath.equals("[osm]")) {
                    osmWriter.setDatasetProperties(extractProperties(parser));
                } else if (tagPath.equals("[osm, bounds]")) {
                    osmWriter.addOSMBBox(extractProperties("bbox", parser));
                } else if (tagPath.equals("[osm, node]")) {
                    // <node id="269682538" lat="56.0420950" lon="12.9693483" user="sanna" uid="31450" visible="true" version="1" changeset="133823" timestamp="2008-06-11T12:36:28Z"/>
                    osmWriter.createOSMNode(extractProperties("node", parser));
                } else if (tagPath.equals("[osm, way]")) {
                    // <way id="27359054" user="spull" uid="61533" visible="true" version="8" changeset="4707351" timestamp="2010-05-15T15:39:57Z">
                    if (!startedWays) {
                        startedWays = true;
                        times[0] = System.currentTimeMillis();
                        osmWriter.optimize();
                        times[1] = System.currentTimeMillis();
                    }
                    wayProperties = extractProperties("way", parser);
                    wayNodes.clear();
                } else if (tagPath.equals("[osm, way, nd]")) {
                    Map<String, Object> properties = extractProperties(parser);
                    wayNodes.add(Long.parseLong(properties.get("ref").toString()));
                } else if (tagPath.endsWith("tag]")) {
                    Map<String, Object> properties = extractProperties(parser);
                    currentNodeTags.put(properties.get("k").toString(), properties.get("v").toString());
                } else if (tagPath.equals("[osm, relation]")) {
                    // <relation id="77965" user="Grillo" uid="13957" visible="true" version="24" changeset="5465617" timestamp="2010-08-11T19:25:46Z">
                    if (!startedRelations) {
                        startedRelations = true;
                        times[2] = System.currentTimeMillis();
                        osmWriter.optimize();
                        times[3] = System.currentTimeMillis();
                    }
                    relationProperties = extractProperties("relation", parser);
                    relationMembers.clear();
                } else if (tagPath.equals("[osm, relation, member]")) {
                    relationMembers.add(extractProperties(parser));
                }
                if (startedRelations) {
                    if (countXMLTags < 10) {
                        log("Starting tag at depth " + depth + ": " + currentXMLTags.get(depth) + " - "
                                + currentXMLTags.toString());
                        for (int i = 0; i < parser.getAttributeCount(); i++) {
                            log("\t" + currentXMLTags.toString() + ": " + parser.getAttributeLocalName(i) + "["
                                    + parser.getAttributeNamespace(i) + "," + parser.getAttributePrefix(i) + ","
                                    + parser.getAttributeType(i) + "," + "] = " + parser.getAttributeValue(i));
                        }
                    }
                    countXMLTags++;
                }
                depth++;
                break;
            case javax.xml.stream.XMLStreamConstants.END_ELEMENT:
                if (currentXMLTags.toString().equals("[osm, node]")) {
                    osmWriter.addOSMNodeTags(allPoints, currentNodeTags);
                } else if (currentXMLTags.toString().equals("[osm, way]")) {
                    osmWriter.createOSMWay(wayProperties, wayNodes, currentNodeTags);
                } else if (currentXMLTags.toString().equals("[osm, relation]")) {
                    osmWriter.createOSMRelation(relationProperties, relationMembers, currentNodeTags);
                }
                depth--;
                currentXMLTags.remove(depth);
                // log("Ending tag at depth "+depth+": "+currentTags.get(depth));
                break;
            default:
                break;
            }
        }
    } finally {
        endProgressMonitor();
        parser.close();
        osmWriter.finish();
        this.osm_dataset = osmWriter.getDatasetId();
    }
    describeTimes(startTime, times);
    osmWriter.describeMissing();
    osmWriter.describeLoaded();

    long stopTime = System.currentTimeMillis();
    log("info | Elapsed time in seconds: " + (1.0 * (stopTime - startTime) / 1000.0));
    stats.dumpGeomStats();
    stats.printTagStats();
}