Example usage for javax.xml.stream XMLStreamReader getElementText

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

Introduction

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

Prototype

public String getElementText() throws XMLStreamException;

Source Link

Document

Reads the content of a text-only element, an exception is thrown if this is not a text-only element.

Usage

From source file:davmail.exchange.ews.EWSMethod.java

protected void handleAttendee(XMLStreamReader reader, Item item, String attendeeType)
        throws XMLStreamException {
    Attendee attendee = new Attendee();
    if ("RequiredAttendees".equals(attendeeType)) {
        attendee.role = "REQ-PARTICIPANT";
    } else {/*from  w ww .  java  2  s.  c  o m*/
        attendee.role = "OPT-PARTICIPANT";
    }
    while (reader.hasNext() && !(XMLStreamUtil.isEndTag(reader, "Attendee"))) {
        reader.next();
        if (XMLStreamUtil.isStartTag(reader)) {
            String tagLocalName = reader.getLocalName();
            if ("EmailAddress".equals(tagLocalName)) {
                attendee.email = reader.getElementText();
            } else if ("Name".equals(tagLocalName)) {
                attendee.name = XMLStreamUtil.getElementText(reader);
            } else if ("ResponseType".equals(tagLocalName)) {
                String responseType = XMLStreamUtil.getElementText(reader);
                attendee.partstat = responseTypeToPartstat(responseType);
            }
        }
    }
    item.addAttendee(attendee);
}

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  v a2 s  .c o m*/
 */
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:com.liferay.portal.util.LocalizationImpl.java

public String getLocalization(String xml, String requestedLanguageId, boolean useDefault) {

    String value = _getCachedValue(xml, requestedLanguageId, useDefault);

    if (value != null) {
        return value;
    } else {/*from www .  j av a  2  s  .  c  o  m*/
        value = StringPool.BLANK;
    }

    String systemDefaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

    String priorityLanguageId = null;

    Locale requestedLocale = LocaleUtil.fromLanguageId(requestedLanguageId);

    if (useDefault && LanguageUtil.isDuplicateLanguageCode(requestedLocale.getLanguage())) {

        Locale priorityLocale = LanguageUtil.getLocale(requestedLocale.getLanguage());

        if (!requestedLanguageId.equals(priorityLanguageId)) {
            priorityLanguageId = LocaleUtil.toLanguageId(priorityLocale);
        }
    }

    if (!Validator.isXml(xml)) {
        if (useDefault || requestedLanguageId.equals(systemDefaultLanguageId)) {

            value = xml;
        }

        _setCachedValue(xml, requestedLanguageId, useDefault, value);

        return value;
    }

    XMLStreamReader xmlStreamReader = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        String defaultLanguageId = StringPool.BLANK;

        // Skip root node

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            defaultLanguageId = xmlStreamReader.getAttributeValue(null, _DEFAULT_LOCALE);

            if (Validator.isNull(defaultLanguageId)) {
                defaultLanguageId = systemDefaultLanguageId;
            }
        }

        // Find specified language and/or default language

        String defaultValue = StringPool.BLANK;
        String priorityValue = StringPool.BLANK;

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

            if (event == XMLStreamConstants.START_ELEMENT) {
                String languageId = xmlStreamReader.getAttributeValue(null, _LANGUAGE_ID);

                if (Validator.isNull(languageId)) {
                    languageId = defaultLanguageId;
                }

                if (languageId.equals(defaultLanguageId) || languageId.equals(priorityLanguageId)
                        || languageId.equals(requestedLanguageId)) {

                    String text = xmlStreamReader.getElementText();

                    if (languageId.equals(defaultLanguageId)) {
                        defaultValue = text;
                    }

                    if (languageId.equals(priorityLanguageId)) {
                        priorityValue = text;
                    }

                    if (languageId.equals(requestedLanguageId)) {
                        value = text;
                    }

                    if (Validator.isNotNull(value)) {
                        break;
                    }
                }
            } else if (event == XMLStreamConstants.END_DOCUMENT) {
                break;
            }
        }

        if (useDefault && Validator.isNotNull(priorityLanguageId) && Validator.isNull(value)
                && Validator.isNotNull(priorityValue)) {

            value = priorityValue;
        }

        if (useDefault && Validator.isNull(value)) {
            value = defaultValue;
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (Exception e) {
            }
        }
    }

    _setCachedValue(xml, requestedLanguageId, useDefault, value);

    return value;
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizer.java

/**
 * Loads configuration from XML file, overriding the properties.
 *///from  w w  w.ja v a 2 s  .  co m
private void loadXMLConfiguration(InputStream xmlConfigurationStream)
        throws ConfigException, XMLStreamException {
    assert xmlConfigurationStream != null;
    final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    final XMLStreamReader reader = inputFactory.createXMLStreamReader(xmlConfigurationStream);

    boolean config = false;
    Module module = null;
    while (reader.hasNext()) {
        final int event = reader.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT: {
            String name = reader.getLocalName();
            if (name.equals("config")) {
                config = true;
                break;
            }

            if (config && name.equals("module")) {
                if (reader.getAttributeCount() == 1) {
                    final String attributeName = reader.getAttributeLocalName(0);
                    final String attributeValue = reader.getAttributeValue(0);

                    if (attributeName.equals("name") && attributeValue != null) {
                        String fullyQualified = Settings.class.getPackage().getName() + ".modules."
                                + attributeValue;
                        try {
                            Class<?> moduleClass = Class.forName(fullyQualified);
                            module = (Module) moduleClass.newInstance();
                        } catch (InstantiationException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot instantiate module " + attributeValue, ex);
                        } catch (IllegalAccessException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot access module " + attributeValue, ex);
                        } catch (ClassNotFoundException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot load module " + attributeValue, ex);
                        }
                    }
                }
            }

            if (config && name.equals("property")) {
                if (reader.getAttributeCount() == 1) {
                    final String attributeName = reader.getAttributeLocalName(0);
                    final String attributeValue = reader.getAttributeValue(0);

                    if (attributeName.equals("name") && attributeValue != null) {
                        if (module == null) {
                            if (Settings.isProperty(attributeValue)) {
                                Settings.setProperty(attributeValue, reader.getElementText());
                            } else {
                                throw new ConfigException("configuration not valid\n"
                                        + "Tried to override non-existing global property " + attributeValue);
                            }
                        } else {
                            if (module.isProperty(attributeValue)) {
                                module.setProperty(attributeValue, reader.getElementText());
                            } else {
                                throw new ConfigException("configuration not valid\n"
                                        + "configuration tried to override non-existing property "
                                        + attributeValue);
                            }
                        }
                    }
                }
            }

            break;
        }
        case XMLStreamConstants.END_ELEMENT: {
            if (config && reader.getLocalName().equals("module")) {
                addModule(module);

                module = null;
            }

            if (config && reader.getLocalName().equals("config")) {
                config = false;
            }
        }
        }
    }
}

From source file:edu.harvard.iq.safe.lockss.impl.LOCKSSDaemonStatusTableXmlStreamParser.java

/**
 *
 * @param stream/*from  www  . ja  v  a  2 s  .co m*/
 * @param encoding
 */
@Override
public void read(InputStream stream, String encoding) {
    // logger.setLevel(Level.FINE);
    // 1. create Input factory
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    xmlif.setProperty("javax.xml.stream.isCoalescing", java.lang.Boolean.TRUE);
    xmlif.setProperty("javax.xml.stream.isNamespaceAware", java.lang.Boolean.TRUE);

    long startTime = System.currentTimeMillis();

    int noAUs = 0;
    String aus = null;
    String currentTableId = null;
    String currentTableTitle = null;
    String currentTableKey = null;
    boolean hasErrorsColumn = false;
    String siAuId = null;
    XMLStreamReader xmlr = null;

    try {

        // create reader
        xmlr = xmlif.createXMLStreamReader(new BufferedInputStream(stream), encoding);

        String curElement = "";

        boolean isLastTagnameTable = false;
        String targetTagName = "row";
        String cellTagName = "columnname";
        boolean withinSummaryinfo = false;
        boolean withinColumndescriptor = false;
        boolean withinRow = false;
        boolean withinCell = false;
        boolean withinReference = false;
        boolean isCrawlStatusActive = false;
        boolean isCrawlStatusColumn = false;
        int valueTagCounter = 0;
        String currentColumnName = null;
        String currentCellValue = null;
        String currentCellKey = null;
        SummaryInfo si = null;

        List<String> rowData = null;
        Map<String, String> rowDataH = null;

        w1: while (xmlr.hasNext()) {
            int eventType = xmlr.next();
            switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
                curElement = xmlr.getLocalName(); // note: getName() ->
                // QName
                logger.log(Level.FINE, "--------- start tag = <{0}> ---------", curElement);
                // check the table name first
                if (curElement.equals("table")) {
                    isLastTagnameTable = true;
                } else if (curElement.equals("error")) {
                    isTargetPageValid = false;
                    break w1;
                }

                if (isLastTagnameTable) {
                    if (curElement.equals("name")) {
                        currentTableId = xmlr.getElementText();
                        logger.log(Level.FINE, "########### table Id = [{0}] ###########", currentTableId);
                        tableId = currentTableId;
                        if (belongsInclusionTableList.contains(currentTableId)) {
                            logger.log(Level.FINE, "!!!!! Table ({0}) belongs to the target list !!!!!",
                                    currentTableId);

                        } else {
                            logger.log(Level.FINE,
                                    "XXXXXXXXXXX Table ({0}) does not belong to the target list XXXXXXXXXXX",
                                    currentTableId);
                            break w1;
                        }
                    } else if (curElement.equals("key")) {
                        currentTableKey = xmlr.getElementText();
                        logger.log(Level.FINE, "---------- table key = ({0}) ----------", currentTableKey);
                        tableKey = currentTableKey;
                    } else if (curElement.equals("title")) {
                        currentTableTitle = xmlr.getElementText();
                        logger.log(Level.FINE, "+++++++++ table Title = ({0}) +++++++++", currentTableTitle);
                        if (currentTableId.equals("PeerRepair")) {
                            if (currentTableTitle.startsWith("Repair candidates for AU: ")) {
                                currentTableTitle = currentTableTitle.replaceFirst("Repair candidates for AU: ",
                                        "");
                                logger.log(Level.FINE, "save this modified table-Title as auName={0}",
                                        currentTableTitle);
                                this.tableTitle = currentTableTitle;
                            } else {
                                logger.log(Level.WARNING,
                                        "The table-Title does not start with the expected token={0}",
                                        currentTableTitle);
                            }
                        }
                        isLastTagnameTable = false;
                    }
                }

                if (curElement.equals("columndescriptor")) {
                    withinColumndescriptor = true;
                } else if (curElement.equals("row")) {
                    withinRow = true;
                    rowCounter++;
                    logger.log(Level.FINE, "================== {0}-th row starts here ==================",
                            rowCounter);
                    // set-up the table storage
                    //if (rowCounter == 1) {
                    // 1st row
                    rowData = new ArrayList<String>();
                    rowDataH = new LinkedHashMap<String, String>();
                    //}
                } else if (curElement.equals("cell")) {
                    logger.log(Level.FINE, "entering a cell");
                    withinCell = true;
                } else if (curElement.equals("reference")) {
                    withinReference = true;
                    logger.log(Level.FINE, "within reference on");
                } else if (curElement.equals("summaryinfo")) {
                    withinSummaryinfo = true;
                    si = new SummaryInfo();
                } else if (curElement.equals("value")) {
                    logger.log(Level.FINE, "entering a value");
                    valueTagCounter++;
                }
                //---- columndescriptor tag ---------------------------------------------------
                if (withinColumndescriptor) {
                    if (curElement.equals("name")) {

                        String nameText = xmlr.getElementText();
                        logger.log(Level.FINE, "\tcolumndescriptor: name = {0}", nameText);
                        columndescriptorList.add(nameText);
                    } else if (curElement.equals("title")) {
                        String titleText = xmlr.getElementText();
                        logger.log(Level.FINE, "\tcolumndescriptor: title = {0}", titleText);
                    } else if (curElement.equals("type")) {
                        String typeText = xmlr.getElementText();
                        logger.log(Level.FINE, "\tcolumndescriptor: type = {0}", typeText);
                        getTypeList().add(typeText);
                    }
                }
                //---- cell tag ----------------------------------------------------------------
                if (withinCell) {
                    logger.log(Level.FINE, "parsing withinCell");
                    if (curElement.equals("columnname")) {

                        String columnname = xmlr.getElementText();
                        logger.log(Level.FINE, "\t\tcolumnname = {0}", columnname);
                        currentColumnName = columnname;
                        if (columnname.equals("crawl_status")) {
                            isCrawlStatusColumn = true;
                        } else {
                            isCrawlStatusColumn = false;
                        }

                        if (columnname.equals("Errors")) {
                            hasErrorsColumn = true;
                        }

                    } else {
                        // value tag block: either value-tag WO a child element
                        // or with a child element
                        /*
                         * <value><reference>...<value>xxxx</value>
                         * <value>xxxx</value>
                         */
                        if ((curElement.equals("value")) && (!withinReference)) {
                            logger.log(Level.FINE, "entering el:value/WO-REF block");
                            if (!hasReferenceTag.contains(currentColumnName)) {
                                logger.log(Level.FINE, "No child reference tag is expected for this value tag");
                                logger.log(Level.FINEST, "xmlr.getEventType():pre-parsing={0}",
                                        xmlr.getEventType());
                                String cellValue = xmlr.getElementText();
                                // note: the above parsing action moves the
                                // cursor to the end-tag, i.e., </value>
                                // therefore, the end-element-switch-block below
                                // cannot catch this </value> tag

                                logger.log(Level.FINE, "\t\t\t[No ref: value] {0} = {1}",
                                        new Object[] { currentColumnName, cellValue });

                                currentCellValue = cellValue;
                                logger.log(Level.FINEST, "xmlr.getEventType():post-parsing={0}",
                                        xmlr.getEventType());
                                // store this value
                                // rowData
                                logger.log(Level.FINE, "current column name={0}", currentColumnName);
                                logger.log(Level.FINE, "valueTagCounter={0}", valueTagCounter);
                                if (currentColumnName.endsWith("Damaged")) {
                                    if (valueTagCounter <= 1) {
                                        // 2nd value tag is footnot for this column
                                        // ignore this value
                                        rowData.add(cellValue);
                                        rowDataH.put(currentColumnName, currentCellValue);
                                    }
                                } else {
                                    rowData.add(cellValue);
                                    rowDataH.put(currentColumnName, currentCellValue);
                                }
                            } else {
                                // previously this block was unthinkable, but
                                // it was found that there are columns that
                                // temporarily have a <reference> tag in
                                // crawl_status_table; these columns are
                                // included in hasReferenceTag by default;
                                // thus, for such unstable columns,
                                // when they hava a <reference tag,
                                // data are caputred in another within-
                                // reference block; however, when these
                                // columns no longer have <reference> tag,
                                // text data would be left uncaptured unless
                                // some follow-up processing takes place here
                                logger.log(Level.FINE, "May have to capture data: column={0}",
                                        currentColumnName);
                                if (mayHaveReferenceTag.contains(currentColumnName) && !isCrawlStatusActive) {
                                    // because the crawling is not active,
                                    // it is safely assume that the maybe columns have no reference tag

                                    // 2011-10-24 the above assumption was found wrong
                                    // a crawling cell does not say active but
                                    // subsequent columns have a reference
                                    logger.log(Level.FINE,
                                            "a text or a reference tag : try to parse it as a text");
                                    String cellValue = null;
                                    try {
                                        cellValue = xmlr.getElementText();
                                    } catch (javax.xml.stream.XMLStreamException ex) {
                                        continue;
                                    } finally {
                                    }
                                    logger.log(Level.FINE, "\t\t\t[value WO-ref(crawling_NOT_active case)={0}]",
                                            currentColumnName + " = " + cellValue);
                                    currentCellValue = cellValue;
                                    // store this value
                                    // rowData
                                    logger.log(Level.FINE, "\t\t\tcurrent columnName={0}", currentColumnName);
                                    rowData.add(cellValue);
                                    rowDataH.put(currentColumnName, currentCellValue);

                                } else {
                                    logger.log(Level.FINE, "WO-Ref: no processing items now:{0}", curElement);
                                }
                            }
                        } else if (withinReference) {
                            // reference tag exists
                            logger.log(Level.FINE, "WR:curElement={0}", curElement);

                            if (curElement.equals("key")) {
                                String cellKey = xmlr.getElementText();
                                logger.log(Level.FINE, "\t\tcurrentCellKey is set to={0}", cellKey);
                                currentCellKey = cellKey;
                            } else if (curElement.equals("value")) {
                                String cellValue = xmlr.getElementText();

                                logger.log(Level.FINE, "\t\twr: {0} = {1}",
                                        new Object[] { currentColumnName, cellValue });

                                // exception cases follow:
                                if (currentColumnName.equals("AuName")) {
                                    logger.log(Level.FINE, "\t\tAuName is replaced with the key[=AuId]= {0}",
                                            currentCellKey);
                                    // rowData                                  // This block is for ArchivalUnitStatusTable
                                    // add the key as a new datum (auId)
                                    // ahead of its value
                                    rowData.add(currentCellKey);
                                    rowDataH.put("AuId", currentCellKey);
                                    currentCellValue = cellValue;
                                } else if (currentColumnName.equals("auId")) {
                                    // This block is for V3PollerTable
                                    logger.log(Level.FINE, "\t\tnew value for auId(V3PollerTable)={0}",
                                            currentCellKey);
                                    // deprecated after 2012-02-02: use key as data
                                    // currentCellValue = currentCellKey;
                                    // add auName as a new column ahead of auId

                                    rowData.add(cellValue);
                                    rowDataH.put("auName", cellValue);
                                    logger.log(Level.FINE, "\t\tauName(V3PollerTable)={0}", cellValue);

                                    currentCellValue = currentCellKey;
                                } else if (currentColumnName.equals("pollId")) {
                                    // this block is for V3PollerTable
                                    logger.log(Level.FINE, "\t\tFull string (key) is used={0}", currentCellKey);
                                    // The key has the complete string whereas
                                    // the value is its truncated copy
                                    currentCellValue = currentCellKey;

                                } else if (currentColumnName.equals("au")) {
                                    logger.log(Level.FINE,
                                            "\t\tauId is used instead for au(crawl_status_table)={0}",
                                            currentCellKey);

                                    // 2012-02-02: add auName ahead of au
                                    rowData.add(cellValue);
                                    rowDataH.put("auName", cellValue);
                                    logger.log(Level.FINE, "\t\tauName={0}", cellValue);

                                    // rowData                                  // This block is for crawl_status_table
                                    // save the key(auId) instead of value
                                    currentCellValue = currentCellKey;

                                } else if (currentColumnName.equals("Peers")) {

                                    logger.log(Level.FINE, "\t\tURL (key) is used={0}", currentCellKey);
                                    currentCellValue = DaemonStatusDataUtil.escapeHtml(currentCellKey);
                                    logger.log(Level.FINE, "\t\tAfter encoding ={0}", currentCellValue);

                                } else {
                                    if (isCrawlStatusColumn) {
                                        // if the craw status column is
                                        // "active", some later columns
                                        // may have a reference tag
                                        // so turn on the switch
                                        if (cellValue.equals("Active") || (cellValue.equals("Pending"))) {
                                            isCrawlStatusActive = true;
                                        } else {
                                            isCrawlStatusActive = false;
                                        }
                                    }
                                    // the default processing
                                    currentCellValue = cellValue;
                                }
                                // store currentCellValue
                                logger.log(Level.FINE, "currentCellValue={0}", currentCellValue);
                                // rowData
                                rowData.add(currentCellValue);
                                rowDataH.put(currentColumnName, currentCellValue);
                            } // Within ref tag: key and valu processing
                        } // value with text or value with ref tag
                    } // columnname or value
                } // within cell
                // ---- summaryinfo tag --------------------------------------------------------
                if (withinSummaryinfo) {
                    logger.log(Level.FINE,
                            "============================ Within SummaryInfo ============================ ");
                    if (curElement.equals("title")) {
                        String text = xmlr.getElementText();
                        si.setTitle(text);

                        logger.log(Level.FINE, "\tsi:titile={0}", si.getTitle());
                    } else if (curElement.equals("type")) {
                        String text = xmlr.getElementText();
                        si.setType(Integer.parseInt(text));
                        logger.log(Level.FINE, "\tsi:type={0}", si.getType());
                    } else if (curElement.equals("key")) {
                        if (withinReference && si.getTitle().equals("Volume")) {
                            String text = xmlr.getElementText();
                            logger.log(Level.FINE, "\tsi:key contents(Volume case)={0}", text);
                            siAuId = text;
                            //                                    si.setValue(text);
                            logger.log(Level.FINE, "\tsi:value(Volume case)={0}", siAuId);
                        }
                    } else if (curElement.equals("value")) {
                        if (withinReference) {
                            if (hasRefTitileTagsSI.contains(si.getTitle())) {
                                if (si.getTitle().equals("Volume")) {
                                    // 2012-02-02 use the au name
                                    String text = xmlr.getElementText();
                                    si.setValue(text);
                                    logger.log(Level.FINE, "\tsi:value(Volume case)={0}", si.getValue());
                                } else {
                                    String text = xmlr.getElementText();
                                    si.setValue(text);
                                    logger.log(Level.FINE, "\tsi:value={0}", si.getValue());
                                }
                            }
                        } else {
                            // note: 2012-02-07
                            // daemon 1.59.2 uses the new layout for AU page
                            // this layout includes a summaryinfo tag
                            // that now contains a reference tag
                            String text = null;

                            try {
                                text = xmlr.getElementText();
                                if (!hasRefTitileTagsSI.contains(si.getTitle())) {
                                    si.setValue(text);
                                    logger.log(Level.FINE, "\tsi:value={0}", si.getValue());
                                }
                            } catch (javax.xml.stream.XMLStreamException ex) {
                                logger.log(Level.WARNING, "encounter a reference tag rather than text");
                                continue;
                            } finally {
                            }
                        }
                    }

                    /*
                     * aus = xmlr.getElementText();
                     * out.println("found token=[" + aus + "]"); if
                     * (currentTableId.equals("ArchivalUnitStatusTable")) {
                     * m = pau.matcher(aus); if (m.find()) {
                     * out.println("How many AUs=" + m.group(1)); noAUs =
                     * Integer.parseInt(m.group(1)); } else {
                     * out.println("not found within[" + aus + "]"); } }
                     */
                }

                break;
            case XMLStreamConstants.CHARACTERS:
                break;

            case XMLStreamConstants.ATTRIBUTE:
                break;

            case XMLStreamConstants.END_ELEMENT:
                if (xmlr.getLocalName().equals("columndescriptor")) {
                    withinColumndescriptor = false;
                    logger.log(Level.FINE, "leaving columndescriptor");
                } else if (xmlr.getLocalName().equals("row")) {
                    if (withinRow) {
                        logger.log(Level.FINE, "========= end of the target row element");
                        withinRow = false;
                    }
                    if (!isCrawlStatusActive) {
                        tabularData.add(rowData);
                        tableData.add(rowDataH);

                    } else {
                        rowIgnored++;
                        rowCounter--;
                    }
                    rowData = null;
                    rowDataH = null;
                    isCrawlStatusActive = false;
                } else if (xmlr.getLocalName().equals("cell")) {
                    // rowDataH.add(cellDatum);
                    cellCounter++;
                    withinCell = false;
                    currentColumnName = null;
                    currentCellValue = null;
                    currentCellKey = null;
                    isCrawlStatusColumn = false;
                    valueTagCounter = 0;
                    logger.log(Level.FINE, "leaving cell");
                } else if (xmlr.getLocalName().equals("columnname")) {
                    logger.log(Level.FINE, "leaving columnname");
                } else if (xmlr.getLocalName().equals("reference")) {
                    withinReference = false;
                } else if (xmlr.getLocalName().equals("summaryinfo")) {
                    logger.log(Level.FINE, "si={0}", si.toString());
                    summaryInfoList.add(si);
                    si = null;
                    withinSummaryinfo = false;
                } else if (xmlr.getLocalName().equals("value")) {
                    logger.log(Level.FINE, "leaving value");
                } else {
                    logger.log(Level.FINE, "--------- end tag = <{0}> ---------", curElement);
                }

                break;
            case XMLStreamConstants.END_DOCUMENT:
                logger.log(Level.FINE, "Total of {0} row occurrences", rowCounter);
            } // end: switch
        } // end:while
    } catch (XMLStreamException ex) {
        logger.log(Level.WARNING, "XMLStreamException occurs", ex);
        this.isTargetPageValid = false;

    } catch (RuntimeException re) {
        logger.log(Level.WARNING, "some RuntimeException occurs", re);
        this.isTargetPageValid = false;
    } catch (Exception e) {
        logger.log(Level.WARNING, "some Exception occurs", e);
        this.isTargetPageValid = false;
    } finally {
        // 5. close reader/IO
        if (xmlr != null) {
            try {
                xmlr.close();
            } catch (XMLStreamException ex) {
                logger.log(Level.WARNING, "XMLStreamException occurs during close()", ex);
            }
        }
        if (!this.isTargetPageValid) {
            logger.log(Level.WARNING,
                    "This parsing session may not be complete due to some exception reported earlier");
        }
    } // end of try

    if (currentTableId.equals("V3PollerDetailTable")) {
        summaryInfoList.add(new SummaryInfo("auId", 4, siAuId));
        summaryInfoMap = new LinkedHashMap<String, String>();
        for (SummaryInfo si : summaryInfoList) {
            summaryInfoMap.put(si.getTitle(), si.getValue());
        }
    }

    // parsing summary
    logger.log(Level.FINE, "###################### parsing summary ######################");
    logger.log(Level.FINE, "currentTableId={0}", currentTableId);
    logger.log(Level.FINE, "currentTableTitle={0}", currentTableTitle);
    logger.log(Level.FINE, "currentTableKey={0}", currentTableKey);

    logger.log(Level.FINE, "columndescriptorList={0}", columndescriptorList);
    logger.log(Level.FINE, "# of columndescriptors={0}", columndescriptorList.size());
    logger.log(Level.FINE, "typeList={0}", typeList);
    logger.log(Level.FINE, "# of rows counted={0}", rowCounter);
    logger.log(Level.FINE, "# of rows excluded[active ones are excluded]={0}", rowIgnored);
    logger.log(Level.FINE, "summaryInfoList:size={0}", summaryInfoList.size());
    logger.log(Level.FINE, "summaryInfoList={0}", summaryInfoList);
    logger.log(Level.FINE, "table: cell counts = {0}", cellCounter);
    logger.log(Level.FINE, "tableData[map]=\n{0}", tableData);
    logger.log(Level.FINE, "tabularData[list]=\n{0}", tabularData);

    /*
     * if (currentTableId.equals("ArchivalUnitStatusTable")) { if
     * (rowCounter == noAUs) { out.println("au counting is OK=" +
     * rowCounter); } else { err.println("au counting disagreement"); throw
     * new RuntimeException("parsing error is suspected"); } }
     */
    logger.log(Level.FINE, " completed in {0} ms\n\n", (System.currentTimeMillis() - startTime));

    if (!columndescriptorList.isEmpty()) {
        int noCols = columndescriptorList.size();
        if (currentTableId.equals("V3PollerTable") && !hasErrorsColumn) {
            noCols--;
        }
        int noCellsExpd = rowCounter * noCols;
        if (noCols > 0) {
            // this table has a table
            logger.log(Level.FINE, "checking parsing results: table dimmensions");
            if (noCellsExpd == cellCounter) {
                logger.log(Level.FINE, "table dimensions and cell-count are consistent");
            } else {
                int diff = noCellsExpd - cellCounter;
                logger.log(Level.FINE, "The table has {0} incomplete cells", diff);
                hasIncompleteRows = true;
                setIncompleteRowList();
                logger.log(Level.FINE, "incomplete rows: {0}", incompleteRows);
            }
        }
    }
}

From source file:com.widowcrawler.exo.parse.Parser.java

public Sitemap parse(InputStream inputStream) throws XMLStreamException, SitemapParseException {

    final XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream, "utf-8");

    final Sitemap retval = new Sitemap(new HashSet<>());

    final Set<SitemapURL> sitemapURLs = new HashSet<>();
    SitemapURL.Builder urlBuilder = null;
    String urlContent;/*  w w w.j  a v a 2s.c  o m*/

    reader.getEventType();

    while (reader.hasNext()) {
        switch (state) {
        case START:
            reader.nextTag();

            if (StringUtils.equalsIgnoreCase(reader.getLocalName(), URLSET_TAG_NAME)) {
                state = State.URLSET;
            } else if (StringUtils.equalsIgnoreCase(reader.getLocalName(), SITEMAPINDEX_TAG_NAME)) {
                state = State.SITEMAPINDEX;
            } else {
                String message = "Invalid root element. Must be either urlset or sitemapindex";
                logger.error(message);
                throw new SitemapParseException(message);
            }

            break;

        case END:
            // consume all end tags
            if (reader.getEventType() != XMLStreamConstants.END_ELEMENT) {
                String message = decorate("There should be only one root element in each sitemap.xml",
                        reader.getLocation());
                logger.error(message);
                throw new SitemapParseException(message);
            }

            reader.next();
            break;

        /////////////////////
        // URLSET Hierarchy
        /////////////////////
        case URLSET:
            // If we're done with the URLs, we're done overall
            if (reader.nextTag() == XMLStreamConstants.END_ELEMENT) {
                state = State.END;
                break;
            }

            // Check that we're entering into a <url> element
            if (!StringUtils.equalsIgnoreCase(reader.getLocalName(), URL_TAG_NAME)) {
                String message = "A <urlset> element can only contain <url> elements. Found: "
                        + reader.getLocalName();
                logger.error(message);
                throw new SitemapParseException(message);
            }

            urlBuilder = new SitemapURL.Builder();
            state = State.URL;
            break;

        case URL:
            reader.nextTag();

            if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
                //logger.info("reader.getLocalName(): " + reader.getLocalName());
                switch (StringUtils.lowerCase(reader.getLocalName())) {
                case LOC_TAG_NAME:
                    state = State.URL_PROP_LOC;
                    break;
                case LASTMOD_TAG_NAME:
                    state = State.URL_PROP_LASTMOD;
                    break;
                case CHANGEFREQ_TAG_NAME:
                    state = State.URL_PROP_CHANGEFREQ;
                    break;
                case PRIORITY_TAG_NAME:
                    state = State.URL_PROP_PRIORITY;
                    break;
                case MOBILE_TAG_NAME:
                    state = State.URL_PROP_MOBILE;
                    break;
                default:
                    String message = "Unexpected tag in url: " + reader.getLocalName();
                    logger.error(message);
                    throw new SitemapParseException(message);
                }
            } else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
                // we're done collecting the data for this URL
                assert urlBuilder != null;
                sitemapURLs.add(urlBuilder.build());
                urlBuilder = new SitemapURL.Builder();
                state = State.URLSET;
            }
            break;

        case URL_PROP_LOC:
            urlContent = reader.getElementText();

            try {
                assert urlBuilder != null;
                urlBuilder.withLocation(new URL(StringUtils.trimToNull(urlContent)));

            } catch (MalformedURLException ex) {
                String message = String.format("Malformed URL found: %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);
            }
            state = State.URL;
            break;

        case URL_PROP_LASTMOD:
            assert urlBuilder != null;
            urlBuilder.withLastModified(DateTime.parse(reader.getElementText()));
            state = State.URL;
            break;

        case URL_PROP_CHANGEFREQ:
            assert urlBuilder != null;
            urlBuilder.withChangeFrequency(ChangeFreq.valueOf(StringUtils.upperCase(reader.getElementText())));
            state = State.URL;
            break;

        case URL_PROP_PRIORITY:
            assert urlBuilder != null;
            urlBuilder.withPriority(Double.valueOf(reader.getElementText()));
            state = State.URL;
            break;

        case URL_PROP_MOBILE:
            assert urlBuilder != null;
            urlBuilder.withIsMobileContent(true);
            // consume until "end tag" of self-closing tag
            // Also works if someone puts content in
            reader.getElementText();
            state = State.URL;
            break;

        ///////////////////////////
        // SITEMAPINDEX Hierarchy
        ///////////////////////////
        case SITEMAPINDEX:
            // If we're done with all the Sitemaps, we're done overall
            if (reader.nextTag() == XMLStreamConstants.END_ELEMENT) {
                state = State.END;
                break;
            }

            state = State.SITEMAP;
            break;

        case SITEMAP:
            if (!StringUtils.equalsIgnoreCase(reader.getLocalName(), SITEMAP_TAG_NAME)) {
                throw new SitemapParseException("A <sitemapindex> element can only contain <sitemap> elements");
            }

            reader.nextTag();

            if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
                switch (StringUtils.lowerCase(reader.getLocalName())) {
                case LOC_TAG_NAME:
                    state = State.URL_PROP_LOC;
                    break;
                case LASTMOD_TAG_NAME:
                    state = State.URL_PROP_LASTMOD;
                    break;
                default:
                    throw new SitemapParseException("Unexpected tag in sitemap: " + reader.getLocalName());
                }
            } else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
                // we're done collecting the data for this URL
                assert urlBuilder != null;
                sitemapURLs.add(urlBuilder.build());
                urlBuilder = new SitemapURL.Builder();
                state = State.URLSET;
            }

        case SITEMAP_PROP_LOC:
            urlContent = reader.getElementText();

            try {
                URL sitemapURL = new URL(StringUtils.trimToNull(urlContent));

                Sitemap temp = Retry.retry(() -> {
                    try {
                        return Exo.parse(sitemapURL.toString());
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                });

                retval.merge(temp);

            } catch (MalformedURLException ex) {
                String message = String.format("Malformed URL found: %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);

            } catch (InterruptedException e) {
                logger.warn("Thread interrupted while (re)trying");
                Thread.currentThread().interrupt();

            } catch (RetryFailedException e) {
                String message = String.format("Failed to retrieve sitemap of sitemap index at %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);
            }

            state = State.URL;
            break;

        case SITEMAP_PROP_LASTMOD:
            // Do nothing with this data for now
            reader.getElementText();
            break;
        }

        //System.out.println(state);
    }

    return retval.merge(new Sitemap(sitemapURLs));
}

From source file:net.sourceforge.subsonic.service.ITunesParser.java

private String readNextTag(XMLStreamReader streamReader) throws XMLStreamException {
    while (streamReader.next() != XMLStreamConstants.START_ELEMENT) {
    }/*  ww  w .j a v a  2s . co  m*/
    return streamReader.getElementText();
}

From source file:net.sourceforge.subsonic.service.ITunesParser.java

private String readKey(XMLStreamReader streamReader) {
    try {//from ww w  .j  av a 2 s . co m
        if (streamReader.getEventType() == XMLStreamConstants.START_ELEMENT
                && "key".equals(streamReader.getName().getLocalPart())) {
            return streamReader.getElementText();
        }
    } catch (XMLStreamException e) {
        // TODO
        System.out.println(streamReader.getName().getLocalPart() + " " + e);
    }
    return null;
}

From source file:org.activiti.bpmn.converter.child.ActivitiMapExceptionParser.java

@Override
public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model)
        throws Exception {
    if (!(parentElement instanceof Activity))
        return;/*  www. j  av  a 2  s .  c om*/

    String errorCode = xtr.getAttributeValue(null, MAP_EXCEPTION_ERRORCODE);
    String andChildren = xtr.getAttributeValue(null, MAP_EXCEPTION_ANDCHILDREN);
    String exceptionClass = xtr.getElementText();
    boolean hasChildrenBool = false;

    if (StringUtils.isEmpty(andChildren) || andChildren.toLowerCase().equals("false")) {
        hasChildrenBool = false;
    } else if (andChildren.toLowerCase().equals("true")) {
        hasChildrenBool = true;
    } else {
        throw new XMLException("'" + andChildren + "' is not valid boolean in mapException with errorCode="
                + errorCode + " and class=" + exceptionClass);
    }

    if (StringUtils.isEmpty(errorCode) || StringUtils.isEmpty(errorCode.trim())) {
        throw new XMLException("No errorCode defined mapException with errorCode=" + errorCode + " and class="
                + exceptionClass);
    }

    ((Activity) parentElement).getMapExceptions()
            .add(new MapExceptionEntry(errorCode, exceptionClass, hasChildrenBool));
}