Example usage for javax.xml.stream XMLStreamConstants START_ELEMENT

List of usage examples for javax.xml.stream XMLStreamConstants START_ELEMENT

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamConstants START_ELEMENT.

Prototype

int START_ELEMENT

To view the source code for javax.xml.stream XMLStreamConstants START_ELEMENT.

Click Source Link

Document

Indicates an event is a start element

Usage

From source file:org.apache.solr.handler.loader.XMLLoader.java

/**
 * Given the input stream, read a document
 *
 * @since solr 1.3/*from w w  w .j ava  2  s .c  o  m*/
 */
public SolrInputDocument readDoc(XMLStreamReader parser) throws XMLStreamException {
    SolrInputDocument doc = new SolrInputDocument();

    String attrName = "";
    for (int i = 0; i < parser.getAttributeCount(); i++) {
        attrName = parser.getAttributeLocalName(i);
        if ("boost".equals(attrName)) {
            doc.setDocumentBoost(Float.parseFloat(parser.getAttributeValue(i)));
        } else {
            log.warn("XML element <doc> has invalid XML attr:" + attrName);
        }
    }

    StringBuilder text = new StringBuilder();
    String name = null;
    float boost = 1.0f;
    boolean isNull = false;
    String update = null;
    Collection<SolrInputDocument> subDocs = null;
    Map<String, Map<String, Object>> updateMap = null;
    boolean complete = false;
    while (!complete) {
        int event = parser.next();
        switch (event) {
        // Add everything to the text
        case XMLStreamConstants.SPACE:
        case XMLStreamConstants.CDATA:
        case XMLStreamConstants.CHARACTERS:
            text.append(parser.getText());
            break;

        case XMLStreamConstants.END_ELEMENT:
            if ("doc".equals(parser.getLocalName())) {
                if (subDocs != null && !subDocs.isEmpty()) {
                    doc.addChildDocuments(subDocs);
                    subDocs = null;
                }
                complete = true;
                break;
            } else if ("field".equals(parser.getLocalName())) {
                // should I warn in some text has been found too
                Object v = isNull ? null : text.toString();
                if (update != null) {
                    if (updateMap == null)
                        updateMap = new HashMap<>();
                    Map<String, Object> extendedValues = updateMap.get(name);
                    if (extendedValues == null) {
                        extendedValues = new HashMap<>(1);
                        updateMap.put(name, extendedValues);
                    }
                    Object val = extendedValues.get(update);
                    if (val == null) {
                        extendedValues.put(update, v);
                    } else {
                        // multiple val are present
                        if (val instanceof List) {
                            List list = (List) val;
                            list.add(v);
                        } else {
                            List<Object> values = new ArrayList<>();
                            values.add(val);
                            values.add(v);
                            extendedValues.put(update, values);
                        }
                    }
                    break;
                }
                doc.addField(name, v, boost);
                boost = 1.0f;
                // field is over
                name = null;
            }
            break;

        case XMLStreamConstants.START_ELEMENT:
            text.setLength(0);
            String localName = parser.getLocalName();
            if ("doc".equals(localName)) {
                if (subDocs == null)
                    subDocs = Lists.newArrayList();
                subDocs.add(readDoc(parser));
            } else {
                if (!"field".equals(localName)) {
                    String msg = "XML element <doc> has invalid XML child element: " + localName;
                    log.warn(msg);
                    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, msg);
                }
                boost = 1.0f;
                update = null;
                isNull = false;
                String attrVal = "";
                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    attrName = parser.getAttributeLocalName(i);
                    attrVal = parser.getAttributeValue(i);
                    if (NAME.equals(attrName)) {
                        name = attrVal;
                    } else if ("boost".equals(attrName)) {
                        boost = Float.parseFloat(attrVal);
                    } else if ("null".equals(attrName)) {
                        isNull = StrUtils.parseBoolean(attrVal);
                    } else if ("update".equals(attrName)) {
                        update = attrVal;
                    } else {
                        log.warn("XML element <field> has invalid XML attr: " + attrName);
                    }
                }
            }
            break;
        }
    }

    if (updateMap != null) {
        for (Map.Entry<String, Map<String, Object>> entry : updateMap.entrySet()) {
            name = entry.getKey();
            Map<String, Object> value = entry.getValue();
            doc.addField(name, value, 1.0f);
        }
    }

    return doc;
}

From source file:org.apache.solr.handler.XMLLoader.java

/**
 * @since solr 1.2/*from   www  .  j  av  a  2 s .c  o  m*/
 */
void processUpdate(SolrQueryRequest req, UpdateRequestProcessor processor, XMLStreamReader parser)
        throws XMLStreamException, IOException, FactoryConfigurationError, InstantiationException,
        IllegalAccessException, TransformerConfigurationException {
    AddUpdateCommand addCmd = null;
    // Need to instansiate a SolrParams, even if req is null, for backward compat with legacyUpdate
    SolrParams params = (req != null) ? req.getParams() : new ModifiableSolrParams();
    while (true) {
        int event = parser.next();
        switch (event) {
        case XMLStreamConstants.END_DOCUMENT:
            parser.close();
            return;

        case XMLStreamConstants.START_ELEMENT:
            String currTag = parser.getLocalName();
            if (currTag.equals(XmlUpdateRequestHandler.ADD)) {
                XmlUpdateRequestHandler.log.trace("SolrCore.update(add)");

                addCmd = new AddUpdateCommand();

                // First look for commitWithin parameter on the request, will be overwritten for individual <add>'s
                addCmd.commitWithin = params.getInt(UpdateParams.COMMIT_WITHIN, -1);

                boolean overwrite = true; // the default

                Boolean overwritePending = null;
                Boolean overwriteCommitted = null;
                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String attrName = parser.getAttributeLocalName(i);
                    String attrVal = parser.getAttributeValue(i);
                    if (XmlUpdateRequestHandler.OVERWRITE.equals(attrName)) {
                        overwrite = StrUtils.parseBoolean(attrVal);
                    } else if (XmlUpdateRequestHandler.ALLOW_DUPS.equals(attrName)) {
                        overwrite = !StrUtils.parseBoolean(attrVal);
                    } else if (XmlUpdateRequestHandler.COMMIT_WITHIN.equals(attrName)) {
                        addCmd.commitWithin = Integer.parseInt(attrVal);
                    } else if (XmlUpdateRequestHandler.OVERWRITE_PENDING.equals(attrName)) {
                        overwritePending = StrUtils.parseBoolean(attrVal);
                    } else if (XmlUpdateRequestHandler.OVERWRITE_COMMITTED.equals(attrName)) {
                        overwriteCommitted = StrUtils.parseBoolean(attrVal);
                    } else {
                        XmlUpdateRequestHandler.log.warn("Unknown attribute id in add:" + attrName);
                    }
                }

                // check if these flags are set
                if (overwritePending != null && overwriteCommitted != null) {
                    if (overwritePending != overwriteCommitted) {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                                "can't have different values for 'overwritePending' and 'overwriteCommitted'");
                    }
                    overwrite = overwritePending;
                }
                addCmd.overwriteCommitted = overwrite;
                addCmd.overwritePending = overwrite;
                addCmd.allowDups = !overwrite;
            } else if ("doc".equals(currTag)) {
                //            if(addCmd != null) {
                XmlUpdateRequestHandler.log.trace("adding doc...");
                addCmd.clear();
                addCmd.solrDoc = readDoc(parser);
                processor.processAdd(addCmd);
                //            } else {
                //              throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Unexpected <doc> tag without an <add> tag surrounding it.");
                //            }
            } else if (XmlUpdateRequestHandler.COMMIT.equals(currTag)
                    || XmlUpdateRequestHandler.OPTIMIZE.equals(currTag)) {
                XmlUpdateRequestHandler.log.trace("parsing " + currTag);

                CommitUpdateCommand cmd = new CommitUpdateCommand(
                        XmlUpdateRequestHandler.OPTIMIZE.equals(currTag));

                boolean sawWaitSearcher = false, sawWaitFlush = false;
                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String attrName = parser.getAttributeLocalName(i);
                    String attrVal = parser.getAttributeValue(i);
                    if (XmlUpdateRequestHandler.WAIT_FLUSH.equals(attrName)) {
                        cmd.waitFlush = StrUtils.parseBoolean(attrVal);
                        sawWaitFlush = true;
                    } else if (XmlUpdateRequestHandler.WAIT_SEARCHER.equals(attrName)) {
                        cmd.waitSearcher = StrUtils.parseBoolean(attrVal);
                        sawWaitSearcher = true;
                    } else if (UpdateParams.MAX_OPTIMIZE_SEGMENTS.equals(attrName)) {
                        cmd.maxOptimizeSegments = Integer.parseInt(attrVal);
                    } else if (UpdateParams.EXPUNGE_DELETES.equals(attrName)) {
                        cmd.expungeDeletes = StrUtils.parseBoolean(attrVal);
                    } else {
                        XmlUpdateRequestHandler.log.warn("unexpected attribute commit/@" + attrName);
                    }
                }

                // If waitFlush is specified and waitSearcher wasn't, then
                // clear waitSearcher.
                if (sawWaitFlush && !sawWaitSearcher) {
                    cmd.waitSearcher = false;
                }
                processor.processCommit(cmd);
            } // end commit
            else if (XmlUpdateRequestHandler.ROLLBACK.equals(currTag)) {
                XmlUpdateRequestHandler.log.trace("parsing " + currTag);

                RollbackUpdateCommand cmd = new RollbackUpdateCommand();

                processor.processRollback(cmd);
            } // end rollback
            else if (XmlUpdateRequestHandler.DELETE.equals(currTag)) {
                XmlUpdateRequestHandler.log.trace("parsing delete");
                processDelete(processor, parser);
            } // end delete
            break;
        }
    }
}

From source file:org.apache.solr.handler.XMLLoader.java

/**
 * @since solr 1.3//from  www .  j a  va  2  s .c  o  m
 */
void processDelete(UpdateRequestProcessor processor, XMLStreamReader parser)
        throws XMLStreamException, IOException {
    // Parse the command
    DeleteUpdateCommand deleteCmd = new DeleteUpdateCommand();
    deleteCmd.fromPending = true;
    deleteCmd.fromCommitted = true;
    for (int i = 0; i < parser.getAttributeCount(); i++) {
        String attrName = parser.getAttributeLocalName(i);
        String attrVal = parser.getAttributeValue(i);
        if ("fromPending".equals(attrName)) {
            deleteCmd.fromPending = StrUtils.parseBoolean(attrVal);
        } else if ("fromCommitted".equals(attrName)) {
            deleteCmd.fromCommitted = StrUtils.parseBoolean(attrVal);
        } else {
            XmlUpdateRequestHandler.log.warn("unexpected attribute delete/@" + attrName);
        }
    }

    StringBuilder text = new StringBuilder();
    while (true) {
        int event = parser.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            String mode = parser.getLocalName();
            if (!("id".equals(mode) || "query".equals(mode))) {
                XmlUpdateRequestHandler.log.warn("unexpected XML tag /delete/" + mode);
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                        "unexpected XML tag /delete/" + mode);
            }
            text.setLength(0);
            break;

        case XMLStreamConstants.END_ELEMENT:
            String currTag = parser.getLocalName();
            if ("id".equals(currTag)) {
                deleteCmd.id = text.toString();
            } else if ("query".equals(currTag)) {
                deleteCmd.query = text.toString();
            } else if ("delete".equals(currTag)) {
                return;
            } else {
                XmlUpdateRequestHandler.log.warn("unexpected XML tag /delete/" + currTag);
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                        "unexpected XML tag /delete/" + currTag);
            }
            processor.processDelete(deleteCmd);
            deleteCmd.id = null;
            deleteCmd.query = null;
            break;

        // Add everything to the text
        case XMLStreamConstants.SPACE:
        case XMLStreamConstants.CDATA:
        case XMLStreamConstants.CHARACTERS:
            text.append(parser.getText());
            break;
        }
    }
}

From source file:org.apache.solr.handler.XMLLoader.java

/**
 * Given the input stream, read a document
 *
 * @since solr 1.3/* ww w  .  java 2  s . c  o  m*/
 */
SolrInputDocument readDoc(XMLStreamReader parser) throws XMLStreamException {
    SolrInputDocument doc = new SolrInputDocument();

    String attrName = "";
    for (int i = 0; i < parser.getAttributeCount(); i++) {
        attrName = parser.getAttributeLocalName(i);
        if ("boost".equals(attrName)) {
            doc.setDocumentBoost(Float.parseFloat(parser.getAttributeValue(i)));
        } else {
            XmlUpdateRequestHandler.log.warn("Unknown attribute doc/@" + attrName);
        }
    }

    StringBuilder text = new StringBuilder();
    String name = null;
    float boost = 1.0f;
    boolean isNull = false;
    while (true) {
        int event = parser.next();
        switch (event) {
        // Add everything to the text
        case XMLStreamConstants.SPACE:
        case XMLStreamConstants.CDATA:
        case XMLStreamConstants.CHARACTERS:
            text.append(parser.getText());
            break;

        case XMLStreamConstants.END_ELEMENT:
            if ("doc".equals(parser.getLocalName())) {
                return doc;
            } else if ("field".equals(parser.getLocalName())) {
                if (!isNull) {
                    doc.addField(name, text.toString(), boost);
                    boost = 1.0f;
                }
            }
            break;

        case XMLStreamConstants.START_ELEMENT:
            text.setLength(0);
            String localName = parser.getLocalName();
            if (!"field".equals(localName)) {
                XmlUpdateRequestHandler.log.warn("unexpected XML tag doc/" + localName);
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                        "unexpected XML tag doc/" + localName);
            }
            boost = 1.0f;
            String attrVal = "";
            for (int i = 0; i < parser.getAttributeCount(); i++) {
                attrName = parser.getAttributeLocalName(i);
                attrVal = parser.getAttributeValue(i);
                if ("name".equals(attrName)) {
                    name = attrVal;
                } else if ("boost".equals(attrName)) {
                    boost = Float.parseFloat(attrVal);
                } else if ("null".equals(attrName)) {
                    isNull = StrUtils.parseBoolean(attrVal);
                } else {
                    XmlUpdateRequestHandler.log.warn("Unknown attribute doc/field/@" + attrName);
                }
            }
            break;
        }
    }
}

From source file:org.apache.synapse.commons.json.JsonDataSource.java

public void serialize(XMLStreamWriter xmlWriter) throws XMLStreamException {
    XMLStreamReader reader = getReader();
    xmlWriter.writeStartDocument();/*from w ww.ja  v  a 2s  .  c om*/
    while (reader.hasNext()) {
        int x = reader.next();
        switch (x) {
        case XMLStreamConstants.START_ELEMENT:
            xmlWriter.writeStartElement(reader.getPrefix(), reader.getLocalName(), reader.getNamespaceURI());
            int namespaceCount = reader.getNamespaceCount();
            for (int i = namespaceCount - 1; i >= 0; i--) {
                xmlWriter.writeNamespace(reader.getNamespacePrefix(i), reader.getNamespaceURI(i));
            }
            int attributeCount = reader.getAttributeCount();
            for (int i = 0; i < attributeCount; i++) {
                xmlWriter.writeAttribute(reader.getAttributePrefix(i), reader.getAttributeNamespace(i),
                        reader.getAttributeLocalName(i), reader.getAttributeValue(i));
            }
            break;
        case XMLStreamConstants.START_DOCUMENT:
            break;
        case XMLStreamConstants.CHARACTERS:
            xmlWriter.writeCharacters(reader.getText());
            break;
        case XMLStreamConstants.CDATA:
            xmlWriter.writeCData(reader.getText());
            break;
        case XMLStreamConstants.END_ELEMENT:
            xmlWriter.writeEndElement();
            break;
        case XMLStreamConstants.END_DOCUMENT:
            xmlWriter.writeEndDocument();
            break;
        case XMLStreamConstants.SPACE:
            break;
        case XMLStreamConstants.COMMENT:
            xmlWriter.writeComment(reader.getText());
            break;
        case XMLStreamConstants.DTD:
            xmlWriter.writeDTD(reader.getText());
            break;
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            xmlWriter.writeProcessingInstruction(reader.getPITarget(), reader.getPIData());
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            xmlWriter.writeEntityRef(reader.getLocalName());
            break;
        default:
            throw new OMException();
        }
    }
    xmlWriter.writeEndDocument();
    xmlWriter.flush();
    xmlWriter.close();
}

From source file:org.apache.tajo.catalog.store.XMLCatalogSchemaManager.java

protected void loadFromXmlFile(XMLInputFactory xmlIf, URL filePath, List<StoreObject> storeObjects)
        throws IOException, XMLStreamException {
    XMLStreamReader xmlReader;/*from   w  w  w  .  j  a  va 2 s .  c  o  m*/

    xmlReader = xmlIf.createXMLStreamReader(filePath.openStream());

    try {
        while (xmlReader.hasNext()) {
            if (xmlReader.next() == XMLStreamConstants.START_ELEMENT
                    && "store".equals(xmlReader.getLocalName())) {
                StoreObject catalogStore = loadCatalogStore(xmlReader);
                if (catalogStore != null) {
                    storeObjects.add(catalogStore);
                }
            }
        }
    } finally {
        try {
            xmlReader.close();
        } catch (XMLStreamException ignored) {
        }
    }
}

From source file:org.apache.tomcat.maven.plugin.tomcat7.run.AbstractRunMojo.java

protected StandardContext parseContextFile(File file) throws MojoExecutionException {
    try {/*from   w w  w.  j a  va 2s.  c  o  m*/
        StandardContext standardContext = new StandardContext();
        XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(new FileInputStream(file));

        int tag = reader.next();

        while (true) {
            if (tag == XMLStreamConstants.START_ELEMENT
                    && StringUtils.equals("Context", reader.getLocalName())) {
                String path = reader.getAttributeValue(null, "path");
                if (StringUtils.isNotBlank(path)) {
                    standardContext.setPath(path);
                }

                String docBase = reader.getAttributeValue(null, "docBase");
                if (StringUtils.isNotBlank(docBase)) {
                    standardContext.setDocBase(docBase);
                }
            }
            if (!reader.hasNext()) {
                break;
            }
            tag = reader.next();
        }

        return standardContext;
    } catch (XMLStreamException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.apache.xml.security.stax.impl.processor.input.AbstractDecryptInputProcessor.java

private XMLSecEvent processEvent(InputProcessorChain inputProcessorChain, boolean isSecurityHeaderEvent)
        throws XMLStreamException, XMLSecurityException {

    if (!tmpXmlEventList.isEmpty()) {
        return tmpXmlEventList.pollLast();
    }/*from w  w  w .  j ava2 s .  co  m*/

    XMLSecEvent xmlSecEvent = isSecurityHeaderEvent ? inputProcessorChain.processHeaderEvent()
            : inputProcessorChain.processEvent();

    boolean encryptedHeader = false;

    if (xmlSecEvent.getEventType() == XMLStreamConstants.START_ELEMENT) {
        XMLSecStartElement xmlSecStartElement = xmlSecEvent.asStartElement();

        //buffer the events until the EncryptedData Element appears and discard it if we found the reference inside it
        //otherwise replay it
        if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_wsse11_EncryptedHeader)) {
            xmlSecEvent = readAndBufferEncryptedHeader(inputProcessorChain, isSecurityHeaderEvent, xmlSecEvent);
            xmlSecStartElement = xmlSecEvent.asStartElement();
            encryptedHeader = true;
        }

        //check if the current start-element has the name EncryptedData and an Id attribute
        if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_xenc_EncryptedData)) {
            ReferenceType referenceType = null;
            if (references != null) {
                referenceType = matchesReferenceId(xmlSecStartElement);
                if (referenceType == null) {
                    //if the events were not for us (no matching reference-id the we have to replay the EncryptedHeader elements)
                    if (!tmpXmlEventList.isEmpty()) {
                        return tmpXmlEventList.pollLast();
                    }
                    return xmlSecEvent;
                }
                //duplicate id's are forbidden
                if (processedReferences.contains(referenceType)) {
                    throw new XMLSecurityException("signature.Verification.MultipleIDs");
                }

                processedReferences.add(referenceType);
            }
            tmpXmlEventList.clear();

            //the following logic reads the encryptedData structure and doesn't pass them further
            //through the chain
            InputProcessorChain subInputProcessorChain = inputProcessorChain.createSubChain(this);

            EncryptedDataType encryptedDataType = parseEncryptedDataStructure(isSecurityHeaderEvent,
                    xmlSecEvent, subInputProcessorChain);
            if (encryptedDataType.getId() == null) {
                encryptedDataType.setId(IDGenerator.generateID(null));
            }

            InboundSecurityToken inboundSecurityToken = getSecurityToken(inputProcessorChain,
                    xmlSecStartElement, encryptedDataType);
            handleSecurityToken(inboundSecurityToken, inputProcessorChain.getSecurityContext(),
                    encryptedDataType);

            final String algorithmURI = encryptedDataType.getEncryptionMethod().getAlgorithm();
            final int ivLength = JCEAlgorithmMapper.getIVLengthFromURI(algorithmURI) / 8;
            Cipher symCipher = getCipher(algorithmURI);

            if (encryptedDataType.getCipherData().getCipherReference() != null) {
                handleCipherReference(inputProcessorChain, encryptedDataType, symCipher, inboundSecurityToken);
                subInputProcessorChain.reset();
                return isSecurityHeaderEvent ? subInputProcessorChain.processHeaderEvent()
                        : subInputProcessorChain.processEvent();
            }

            //create a new Thread for streaming decryption
            DecryptionThread decryptionThread = new DecryptionThread(subInputProcessorChain,
                    isSecurityHeaderEvent);
            Key decryptionKey = inboundSecurityToken.getSecretKey(algorithmURI, XMLSecurityConstants.Enc,
                    encryptedDataType.getId());
            decryptionKey = XMLSecurityUtils.prepareSecretKey(algorithmURI, decryptionKey.getEncoded());
            decryptionThread.setSecretKey(decryptionKey);
            decryptionThread.setSymmetricCipher(symCipher);
            decryptionThread.setIvLength(ivLength);
            XMLSecStartElement parentXMLSecStartElement = xmlSecStartElement.getParentXMLSecStartElement();
            if (encryptedHeader) {
                parentXMLSecStartElement = parentXMLSecStartElement.getParentXMLSecStartElement();
            }
            AbstractDecryptedEventReaderInputProcessor decryptedEventReaderInputProcessor = newDecryptedEventReaderInputProcessor(
                    encryptedHeader, parentXMLSecStartElement, encryptedDataType, inboundSecurityToken,
                    inputProcessorChain.getSecurityContext());

            //add the new created EventReader processor to the chain.
            inputProcessorChain.addProcessor(decryptedEventReaderInputProcessor);

            inputProcessorChain.getDocumentContext().setIsInEncryptedContent(
                    inputProcessorChain.getProcessors().indexOf(decryptedEventReaderInputProcessor),
                    decryptedEventReaderInputProcessor);

            //fire here only ContentEncryptedElementEvents
            //the other ones will be fired later, because we don't know the encrypted element name yet
            //important: this must occur after setIsInEncryptedContent!
            if (SecurePart.Modifier.Content.getModifier().equals(encryptedDataType.getType())) {
                handleEncryptedContent(inputProcessorChain, xmlSecStartElement.getParentXMLSecStartElement(),
                        inboundSecurityToken, encryptedDataType);
            }

            Thread thread = new Thread(decryptionThread);
            thread.setPriority(Thread.NORM_PRIORITY + 1);
            thread.setName("decryption thread");
            //when an exception in the decryption thread occurs, we want to forward them:
            thread.setUncaughtExceptionHandler(decryptedEventReaderInputProcessor);

            decryptedEventReaderInputProcessor.setDecryptionThread(thread);

            //we have to start the thread before we call decryptionThread.getPipedInputStream().
            //Otherwise we will end in a deadlock, because the StAX reader expects already data.
            //@See some lines below:
            log.debug("Starting decryption thread");
            thread.start();

            InputStream prologInputStream;
            InputStream epilogInputStream;
            try {
                prologInputStream = writeWrapperStartElement(xmlSecStartElement);
                epilogInputStream = writeWrapperEndElement();
            } catch (UnsupportedEncodingException e) {
                throw new XMLSecurityException(e);
            } catch (IOException e) {
                throw new XMLSecurityException(e);
            }

            InputStream decryptInputStream = decryptionThread.getPipedInputStream();
            decryptInputStream = applyTransforms(referenceType, decryptInputStream);

            //spec says (4.2): "The cleartext octet sequence obtained in step 3 is
            //interpreted as UTF-8 encoded character data."
            XMLStreamReader xmlStreamReader = inputProcessorChain.getSecurityContext()
                    .<XMLInputFactory>get(XMLSecurityConstants.XMLINPUTFACTORY).createXMLStreamReader(
                            new MultiInputStream(prologInputStream, decryptInputStream, epilogInputStream),
                            "UTF-8");

            //forward to wrapper element
            forwardToWrapperElement(xmlStreamReader);

            decryptedEventReaderInputProcessor.setXmlStreamReader(xmlStreamReader);

            if (isSecurityHeaderEvent) {
                return decryptedEventReaderInputProcessor.processNextHeaderEvent(inputProcessorChain);
            } else {
                return decryptedEventReaderInputProcessor.processNextEvent(inputProcessorChain);
            }
        }
    }
    return xmlSecEvent;
}

From source file:org.apache.xml.security.stax.impl.processor.input.AbstractDecryptInputProcessor.java

private void forwardToWrapperElement(XMLStreamReader xmlStreamReader) throws XMLStreamException {
    do {/* ww w .  j  av a 2s.  c o  m*/
        if (xmlStreamReader.getEventType() == XMLStreamConstants.START_ELEMENT
                && xmlStreamReader.getName().equals(wrapperElementName)) {
            xmlStreamReader.next();
            break;
        }
        xmlStreamReader.next();
    } while (xmlStreamReader.hasNext());
}

From source file:org.apache.xml.security.stax.impl.processor.input.AbstractDecryptInputProcessor.java

private EncryptedDataType parseEncryptedDataStructure(boolean isSecurityHeaderEvent, XMLSecEvent xmlSecEvent,
        InputProcessorChain subInputProcessorChain) throws XMLStreamException, XMLSecurityException {

    Deque<XMLSecEvent> xmlSecEvents = new ArrayDeque<XMLSecEvent>();
    xmlSecEvents.push(xmlSecEvent);//from  w ww.  j  ava  2 s. co m
    XMLSecEvent encryptedDataXMLSecEvent;
    int count = 0;
    int keyInfoCount = 0;
    do {
        subInputProcessorChain.reset();
        if (isSecurityHeaderEvent) {
            encryptedDataXMLSecEvent = subInputProcessorChain.processHeaderEvent();
        } else {
            encryptedDataXMLSecEvent = subInputProcessorChain.processEvent();
        }

        xmlSecEvents.push(encryptedDataXMLSecEvent);
        if (++count >= maximumAllowedEncryptedDataEvents) {
            throw new XMLSecurityException("stax.xmlStructureSizeExceeded",
                    new Object[] { maximumAllowedEncryptedDataEvents });
        }

        //the keyInfoCount is necessary to prevent early while-loop abort when the KeyInfo also contains a CipherValue.
        if (encryptedDataXMLSecEvent.getEventType() == XMLStreamConstants.START_ELEMENT
                && encryptedDataXMLSecEvent.asStartElement().getName()
                        .equals(XMLSecurityConstants.TAG_dsig_KeyInfo)) {
            keyInfoCount++;
        } else if (encryptedDataXMLSecEvent.getEventType() == XMLStreamConstants.END_ELEMENT
                && encryptedDataXMLSecEvent.asEndElement().getName()
                        .equals(XMLSecurityConstants.TAG_dsig_KeyInfo)) {
            keyInfoCount--;
        }
    } while (!((encryptedDataXMLSecEvent.getEventType() == XMLStreamConstants.START_ELEMENT
            && encryptedDataXMLSecEvent.asStartElement().getName()
                    .equals(XMLSecurityConstants.TAG_xenc_CipherValue)
            || encryptedDataXMLSecEvent.getEventType() == XMLStreamConstants.END_ELEMENT
                    && encryptedDataXMLSecEvent.asEndElement().getName()
                            .equals(XMLSecurityConstants.TAG_xenc_EncryptedData))
            && keyInfoCount == 0));

    xmlSecEvents.push(XMLSecEventFactory.createXmlSecEndElement(XMLSecurityConstants.TAG_xenc_CipherValue));
    xmlSecEvents.push(XMLSecEventFactory.createXmlSecEndElement(XMLSecurityConstants.TAG_xenc_CipherData));
    xmlSecEvents.push(XMLSecEventFactory.createXmlSecEndElement(XMLSecurityConstants.TAG_xenc_EncryptedData));

    EncryptedDataType encryptedDataType;

    try {
        Unmarshaller unmarshaller = XMLSecurityConstants
                .getJaxbUnmarshaller(getSecurityProperties().isDisableSchemaValidation());
        @SuppressWarnings("unchecked")
        JAXBElement<EncryptedDataType> encryptedDataTypeJAXBElement = (JAXBElement<EncryptedDataType>) unmarshaller
                .unmarshal(new XMLSecurityEventReader(xmlSecEvents, 0));
        encryptedDataType = encryptedDataTypeJAXBElement.getValue();

    } catch (JAXBException e) {
        throw new XMLSecurityException(e);
    }
    return encryptedDataType;
}