Example usage for javax.xml.stream XMLStreamReader getText

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

Introduction

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

Prototype

public String getText();

Source Link

Document

Returns the current value of the parse event as a string, this returns the string value of a CHARACTERS event, returns the value of a COMMENT, the replacement value for an ENTITY_REFERENCE, the string value of a CDATA section, the string value for a SPACE event, or the String value of the internal subset of the DTD.

Usage

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java

/**
 * /*from  w  ww .  ja v a2  s  .  c  om*/
 * @param fname
 * @throws XMLStreamException
 * @throws IOException
 */
private static void readProfile(String fname) throws XMLStreamException, IOException {
    //init profile map
    _profile = new HashMap<Integer, HashMap<Integer, CostFunction>>();

    //read existing profile
    FileInputStream fis = new FileInputStream(fname);

    try {
        //xml parsing
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader xsr = xif.createXMLStreamReader(fis);

        int e = xsr.nextTag(); // profile start

        while (true) //read all instructions
        {
            e = xsr.nextTag(); // instruction start
            if (e == XMLStreamConstants.END_ELEMENT)
                break; //reached profile end tag

            //parse instruction
            int ID = Integer.parseInt(xsr.getAttributeValue(null, XML_ID));
            //String name = xsr.getAttributeValue(null, XML_NAME).trim().replaceAll(" ", Lops.OPERAND_DELIMITOR);
            HashMap<Integer, CostFunction> tmp = new HashMap<Integer, CostFunction>();
            _profile.put(ID, tmp);

            while (true) {
                e = xsr.nextTag(); // cost function start
                if (e == XMLStreamConstants.END_ELEMENT)
                    break; //reached instruction end tag

                //parse cost function
                TestMeasure m = TestMeasure.valueOf(xsr.getAttributeValue(null, XML_MEASURE));
                TestVariable lv = TestVariable.valueOf(xsr.getAttributeValue(null, XML_VARIABLE));
                InternalTestVariable[] pv = parseTestVariables(
                        xsr.getAttributeValue(null, XML_INTERNAL_VARIABLES));
                DataFormat df = DataFormat.valueOf(xsr.getAttributeValue(null, XML_DATAFORMAT));
                int tDefID = getTestDefID(m, lv, df, pv);

                xsr.next(); //read characters
                double[] params = parseParams(xsr.getText());
                boolean multidim = _regTestDef.get(tDefID).getInternalVariables().length > 1;
                CostFunction cf = new CostFunction(params, multidim);
                tmp.put(tDefID, cf);

                xsr.nextTag(); // cost function end
                //System.out.println("added cost function");
            }
        }
        xsr.close();
    } finally {
        IOUtilFunctions.closeSilently(fis);
    }

    //mark profile as successfully read
    _flagReadData = true;
}

From source file:at.lame.hellonzb.parser.NzbParser.java

/**
 * This is the constructor of the class.
 * It parses the given XML file.//from w  w w .  ja  v  a2  s . c om
 *
 * @param mainApp The main application object
 * @param file The file name of the nzb file to parse
 * @throws XMLStreamException 
 * @throws IOException 
 */
public NzbParser(HelloNzbCradle mainApp, String file) throws XMLStreamException, IOException, ParseException {
    this.mainApp = mainApp;

    DownloadFile currentFile = null;
    DownloadFileSegment currentSegment = null;
    boolean groupFlag = false;
    boolean segmentFlag = false;

    this.name = file.trim();
    this.name = file.substring(0, file.length() - 4);
    this.downloadFiles = new Vector<DownloadFile>();

    this.origTotalSize = 0;
    this.downloadedBytes = 0;

    // create XML parser
    String string = reformatInputStream(file);
    InputStream in = new ByteArrayInputStream(string.getBytes());
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader parser = factory.createXMLStreamReader(in);

    // parse nzb file with a Java XML parser
    while (parser.hasNext()) {
        switch (parser.getEventType()) {
        // parser has reached the end of the xml file
        case XMLStreamConstants.END_DOCUMENT:
            parser.close();
            break;

        // parser has found a new element
        case XMLStreamConstants.START_ELEMENT:
            String elemName = parser.getLocalName().toLowerCase();
            if (elemName.equals("file")) {
                currentFile = newDownloadFile(parser);
                boolean found = false;
                for (DownloadFile dlf : downloadFiles)
                    if (dlf.getFilename().equals(currentFile.getFilename())) {
                        found = true;
                        break;
                    }

                if (!found)
                    downloadFiles.add(currentFile);
            } else if (elemName.equals("group"))
                groupFlag = true;
            else if (elemName.equals("segment")) {
                currentSegment = newDownloadFileSegment(parser, currentFile);
                currentFile.addSegment(currentSegment);
                segmentFlag = true;
            }
            break;

        // end of element
        case XMLStreamConstants.END_ELEMENT:
            groupFlag = false;
            segmentFlag = false;
            break;

        // get the elements value(s)
        case XMLStreamConstants.CHARACTERS:
            if (!parser.isWhiteSpace()) {
                if (groupFlag && (currentFile != null))
                    currentFile.addGroup(parser.getText());
                else if (segmentFlag && (currentSegment != null))
                    currentSegment.setArticleId(parser.getText());
            }
            break;

        // any other parser event?
        default:
            break;
        }

        parser.next();
    }

    checkFileSegments();
    this.origTotalSize = getCurrTotalSize();
}

From source file:StAXStreamTreeViewer.java

private void parseRestOfDocument(XMLStreamReader reader, DefaultMutableTreeNode current)
        throws XMLStreamException {

    while (reader.hasNext()) {
        int type = reader.next();
        switch (type) {
        case XMLStreamConstants.START_ELEMENT:

            DefaultMutableTreeNode element = new DefaultMutableTreeNode(reader.getLocalName());
            current.add(element);//from  w ww  . j a  v  a 2 s .  c  o m
            current = element;

            if (reader.getNamespaceURI() != null) {
                String prefix = reader.getPrefix();
                if (prefix == null) {
                    prefix = "[None]";
                }
                DefaultMutableTreeNode namespace = new DefaultMutableTreeNode(
                        "prefix = '" + prefix + "', URI = '" + reader.getNamespaceURI() + "'");
                current.add(namespace);
            }

            if (reader.getAttributeCount() > 0) {
                for (int i = 0; i < reader.getAttributeCount(); i++) {
                    DefaultMutableTreeNode attribute = new DefaultMutableTreeNode(
                            "Attribute (name = '" + reader.getAttributeLocalName(i) + "', value = '"
                                    + reader.getAttributeValue(i) + "')");
                    String attURI = reader.getAttributeNamespace(i);
                    if (attURI != null) {
                        String attPrefix = reader.getAttributePrefix(i);
                        if (attPrefix == null || attPrefix.equals("")) {
                            attPrefix = "[None]";
                        }
                        DefaultMutableTreeNode attNamespace = new DefaultMutableTreeNode(
                                "prefix=" + attPrefix + ",URI=" + attURI);
                        attribute.add(attNamespace);
                    }
                    current.add(attribute);
                }
            }

            break;
        case XMLStreamConstants.END_ELEMENT:
            current = (DefaultMutableTreeNode) current.getParent();
            break;
        case XMLStreamConstants.CHARACTERS:
            if (!reader.isWhiteSpace()) {
                DefaultMutableTreeNode data = new DefaultMutableTreeNode("CD:" + reader.getText());
                current.add(data);
            }
            break;
        case XMLStreamConstants.DTD:
            DefaultMutableTreeNode dtd = new DefaultMutableTreeNode("DTD:" + reader.getText());
            current.add(dtd);
            break;
        case XMLStreamConstants.SPACE:
            break;
        case XMLStreamConstants.COMMENT:
            DefaultMutableTreeNode comment = new DefaultMutableTreeNode(reader.getText());
            current.add(comment);
            break;
        default:
            System.out.println(type);
        }
    }
}

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

/**
 * Integrate jhove data./*from   www  . j a va2 s .c  om*/
 *
 * @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: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  www  . jav  a  2  s.com
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  
 * //from w w w.  j  a va 2  s  .c o  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:com.sun.socialsite.pojos.PropDefinition.java

protected void init(PropDefinition profileDef, InputStream input) throws SocialSiteException {
    try {//from  ww  w. j av a2s.c o  m
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader parser = factory.createXMLStreamReader(input);
        String ns = null; // TODO: namespace for ProfileDef

        // hold the current things we're working on
        Map<String, DisplaySectionDefinition> sdefs = new LinkedHashMap<String, DisplaySectionDefinition>();
        Stack<PropertyDefinitionHolder> propertyHolderStack = new Stack<PropertyDefinitionHolder>();
        List<AllowedValue> allowedValues = null;
        PropertyDefinition pdef = null;

        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                log.debug("START ELEMENT -- " + parser.getLocalName());

                if ("display-section".equals(parser.getLocalName())) {
                    propertyHolderStack.push(new DisplaySectionDefinition(parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey")));

                } else if ("property".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    pdef = new PropertyDefinition(holder.getBasePath(), parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey"), parser.getAttributeValue(ns, "type"));

                } else if ("object".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    propertyHolderStack.push(new PropertyObjectDefinition(holder.getBasePath(),
                            parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey")));

                } else if ("collection".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    propertyHolderStack.push(new PropertyObjectCollectionDefinition(holder.getBasePath(),
                            parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey")));

                } else if ("allowed-values".equals(parser.getLocalName())) {
                    allowedValues = new ArrayList<AllowedValue>();

                } else if ("value".equals(parser.getLocalName())) {
                    AllowedValue allowedValue = new AllowedValue(parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey"));
                    allowedValues.add(allowedValue);

                } else if ("default-value".equals(parser.getLocalName())) {
                    pdef.setDefaultValue(parser.getText());
                }
                break;

            case XMLStreamConstants.END_ELEMENT:
                log.debug("END ELEMENT -- " + parser.getLocalName());

                if ("display-section".equals(parser.getLocalName())) {
                    DisplaySectionDefinition sdef = (DisplaySectionDefinition) propertyHolderStack.pop();
                    sdefs.put(sdef.getName(), sdef);

                } else if ("property".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyDefinitions().add(pdef);
                    propertyDefs.put(pdef.getName(), pdef);
                    pdef = null;

                } else if ("object".equals(parser.getLocalName())) {
                    PropertyObjectDefinition odef = (PropertyObjectDefinition) propertyHolderStack.pop();
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyObjectDefinitions().add(odef);

                    // add to list of all property object defs
                    propertyObjectDefs.put(odef.getName(), odef);
                    odef = null;

                } else if ("collection".equals(parser.getLocalName())) {
                    PropertyObjectCollectionDefinition cdef = (PropertyObjectCollectionDefinition) propertyHolderStack
                            .pop();
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyObjectCollectionDefinitions().add(cdef);

                    // add to list of all property object defs
                    propertyObjectCollectionDefs.put(cdef.getName(), cdef);
                    cdef = null;

                } else if ("allowed-values".equals(parser.getLocalName())) {
                    pdef.setAllowedValues(allowedValues);
                    allowedValues = null;
                }
                break;

            case XMLStreamConstants.CHARACTERS:
                break;

            case XMLStreamConstants.CDATA:
                break;

            } // end switch
        } // end while

        parser.close();

        profileDef.sectionDefs = sdefs;

    } catch (Exception ex) {
        throw new SocialSiteException("ERROR parsing profile definitions", ex);
    }
}

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

/**
 * Parses the SecurityToken by wrapping within an AssertionWrapper.
 *
 * @param securityToken SecurityToken/*from   w  ww  .ja v a  2 s  .  co  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:davmail.exchange.ews.EWSMethod.java

protected void processResponseStream(InputStream inputStream) {
    responseItems = new ArrayList<Item>();
    XMLStreamReader reader = null;
    try {/*from   w w w .  j  a va  2  s . c o m*/
        inputStream = new FilterInputStream(inputStream) {
            int totalCount;
            int lastLogCount;

            @Override
            public int read(byte[] buffer, int offset, int length) throws IOException {
                int count = super.read(buffer, offset, length);
                totalCount += count;
                if (totalCount - lastLogCount > 1024 * 128) {
                    DavGatewayTray.debug(new BundleMessage("LOG_DOWNLOAD_PROGRESS",
                            String.valueOf(totalCount / 1024), EWSMethod.this.getURI()));
                    DavGatewayTray.switchIcon();
                    lastLogCount = totalCount;
                }
                return count;
            }
        };
        reader = XMLStreamUtil.createXMLStreamReader(inputStream);
        while (reader.hasNext()) {
            reader.next();
            handleErrors(reader);
            if (serverVersion == null && XMLStreamUtil.isStartTag(reader, "ServerVersionInfo")) {
                String majorVersion = getAttributeValue(reader, "MajorVersion");
                if ("14".equals(majorVersion)) {
                    String minorVersion = getAttributeValue(reader, "MinorVersion");
                    if ("0".equals(minorVersion)) {
                        serverVersion = "Exchange2010";
                    } else {
                        serverVersion = "Exchange2010_SP1";
                    }
                } else {
                    serverVersion = "Exchange2007_SP1";
                }
            } else if (XMLStreamUtil.isStartTag(reader, "RootFolder")) {
                includesLastItemInRange = "true"
                        .equals(reader.getAttributeValue(null, "IncludesLastItemInRange"));
            } else if (XMLStreamUtil.isStartTag(reader, responseCollectionName)) {
                handleItems(reader);
            } else {
                handleCustom(reader);
            }
        }
    } catch (XMLStreamException e) {
        LOGGER.error("Error while parsing soap response: " + e, e);
        if (reader != null) {
            try {
                LOGGER.error("Current text: " + reader.getText());
            } catch (IllegalStateException ise) {
                LOGGER.error(e + " " + e.getMessage());
            }
        }
    }
    if (errorDetail != null) {
        LOGGER.debug(errorDetail);
    }
}

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}.// w  ww  .j a  v a2s .  com
 */
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
        }
    }
}