Example usage for javax.xml.stream XMLInputFactory newInstance

List of usage examples for javax.xml.stream XMLInputFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.stream XMLInputFactory newInstance.

Prototype

public static XMLInputFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

From source file:org.overlord.commons.auth.jboss7.SAMLBearerTokenLoginModule.java

/**
 * @see org.jboss.security.auth.spi.AbstractServerLoginModule#login()
 *//* w  w  w  .  j a v a  2s .  co m*/
@Override
public boolean login() throws LoginException {
    try {
        HttpServletRequest request = getCurrentRequest();
        String authorization = request.getHeader("Authorization"); //$NON-NLS-1$
        if (authorization != null && authorization.startsWith("Basic")) { //$NON-NLS-1$
            String b64Data = authorization.substring(6);
            byte[] dataBytes = Base64.decodeBase64(b64Data);
            String data = new String(dataBytes, "UTF-8"); //$NON-NLS-1$
            if (data.startsWith("SAML-BEARER-TOKEN:")) { //$NON-NLS-1$
                String assertionData = data.substring(18);
                Document samlAssertion = DocumentUtil.getDocument(assertionData);
                SAMLAssertionParser parser = new SAMLAssertionParser();
                DOMSource source = new DOMSource(samlAssertion);
                XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(source);
                Object parsed = parser.parse(xmlEventReader);
                AssertionType assertion = (AssertionType) parsed;
                SAMLBearerTokenUtil.validateAssertion(assertion, request, allowedIssuers);
                if ("true".equals(signatureRequired)) { //$NON-NLS-1$
                    KeyPair keyPair = getKeyPair(assertion);
                    if (!SAMLBearerTokenUtil.isSAMLAssertionSignatureValid(samlAssertion, keyPair)) {
                        throw new LoginException(
                                Messages.getString("SAMLBearerTokenLoginModule.InvalidSignature")); //$NON-NLS-1$
                    }
                }
                consumeAssertion(assertion);
                loginOk = true;
                return true;
            }
        }
    } catch (LoginException le) {
        throw le;
    } catch (Exception e) {
        e.printStackTrace();
        loginOk = false;
        return false;
    }
    return super.login();
}

From source file:org.overlord.commons.auth.tomcat7.SAMLBearerTokenAuthenticator.java

/**
 * @see org.apache.catalina.authenticator.BasicAuthenticator#authenticate(org.apache.catalina.connector.Request, javax.servlet.http.HttpServletResponse, org.apache.catalina.deploy.LoginConfig)
 *///from  w  w w . j  ava 2s .  c om
@Override
public boolean authenticate(Request request, HttpServletResponse response, LoginConfig config)
        throws IOException {
    Principal principal = request.getUserPrincipal();
    if (principal == null) {
        MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("authorization"); //$NON-NLS-1$
        if (authorization != null) {
            authorization.toBytes();
            ByteChunk authorizationBC = authorization.getByteChunk();
            if (authorizationBC.startsWithIgnoreCase("basic ", 0)) { //$NON-NLS-1$
                authorizationBC.setOffset(authorizationBC.getOffset() + 6);
                String b64Data = new String(authorizationBC.getBuffer(), authorizationBC.getOffset(),
                        authorizationBC.getLength());
                byte[] decoded = Base64.decodeBase64(b64Data);
                String data = new String(decoded, "UTF-8"); //$NON-NLS-1$
                if (data.startsWith("SAML-BEARER-TOKEN:")) { //$NON-NLS-1$
                    try {
                        String assertionData = data.substring(18);
                        Document samlAssertion = DocumentUtil.getDocument(assertionData);
                        SAMLAssertionParser parser = new SAMLAssertionParser();
                        XMLEventReader xmlEventReader = XMLInputFactory.newInstance()
                                .createXMLEventReader(new StringReader(assertionData));
                        Object parsed = parser.parse(xmlEventReader);
                        AssertionType assertion = (AssertionType) parsed;
                        SAMLBearerTokenUtil.validateAssertion(assertion, request, allowedIssuers);
                        if (signatureRequired) {
                            KeyPair keyPair = getKeyPair(assertion);
                            if (!SAMLBearerTokenUtil.isSAMLAssertionSignatureValid(samlAssertion, keyPair)) {
                                throw new IOException(
                                        Messages.getString("SAMLBearerTokenAuthenticator.InvalidSignature")); //$NON-NLS-1$
                            }
                        }
                        principal = consumeAssertion(assertion);
                        if (principal != null) {
                            register(request, response, principal, HttpServletRequest.BASIC_AUTH,
                                    principal.getName(), null);
                            return true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        return false;
                    }
                }
            }
            authorizationBC.setOffset(authorizationBC.getOffset() - 6);
        }
    }
    return super.authenticate(request, response, config);
}

From source file:org.overlord.security.eval.jaxrs.auth.SAMLBearerTokenLoginModule.java

/**
 * @see org.jboss.security.auth.spi.AbstractServerLoginModule#login()
 *///ww  w  .  j a v  a2  s .c o m
@Override
public boolean login() throws LoginException {
    System.out.println("LOGIN called: " + getClass().getSimpleName());
    InputStream is = null;
    try {
        HttpServletRequest request = (HttpServletRequest) PolicyContext
                .getContext("javax.servlet.http.HttpServletRequest");
        System.out.println("Request: " + request);
        String authorization = request.getHeader("Authorization");
        System.out.println("Authorization Header: " + authorization);
        if (authorization != null && authorization.startsWith("Basic")) {
            String b64Data = authorization.substring(6);
            byte[] dataBytes = Base64.decodeBase64(b64Data);
            String data = new String(dataBytes, "UTF-8");
            System.out.println("DATA: " + data);
            if (data.startsWith("SAML-BEARER-TOKEN:")) {
                String assertionData = data.substring(18);
                System.out.println("Assertion DATA: " + assertionData);
                SAMLAssertionParser parser = new SAMLAssertionParser();
                is = new ByteArrayInputStream(assertionData.getBytes("UTF-8"));
                XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(is);
                Object parsed = parser.parse(xmlEventReader);
                System.out.println("Parsed Object: " + parsed.getClass());
                AssertionType assertion = (AssertionType) parsed;
                if (validateAssertion(assertion, request) && consumeAssertion(assertion)) {
                    System.out.println("SAML assertion login passed, setting loginOk = true");
                    loginOk = true;
                    return true;
                }
            }
        }
    } catch (LoginException le) {
        throw le;
    } catch (Exception e) {
        e.printStackTrace();
        loginOk = false;
        return false;
    } finally {
        IOUtils.closeQuietly(is);
    }
    return super.login();
}

From source file:org.pentaho.di.trans.steps.excelinput.staxpoi.StaxPoiSheet.java

public StaxPoiSheet(XSSFReader reader, String sheetName, String sheetID)
        throws InvalidFormatException, IOException, XMLStreamException {
    this.sheetName = sheetName;
    xssfReader = reader;//from   w w w  .j  a  v  a2 s  .  c o  m
    sheetId = sheetID;
    sst = reader.getSharedStringsTable();
    styles = reader.getStylesTable();
    sheetStream = reader.getSheet(sheetID);
    XMLInputFactory factory = XMLInputFactory.newInstance();
    sheetReader = factory.createXMLStreamReader(sheetStream);
    headerRow = new ArrayList<String>();
    while (sheetReader.hasNext()) {
        int event = sheetReader.next();
        if (event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals("dimension")) {
            String dim = sheetReader.getAttributeValue(null, "ref");
            // empty sheets have dimension with no range
            if (StringUtils.contains(dim, ':')) {
                dim = dim.split(":")[1];
                numRows = StaxUtil.extractRowNumber(dim);
                numCols = StaxUtil.extractColumnNumber(dim);
            }
        }
        if (event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals("row")) {
            currentRow = Integer.parseInt(sheetReader.getAttributeValue(null, "r"));
            firstRow = currentRow;

            // calculate the number of columns in the header row
            while (sheetReader.hasNext()) {
                event = sheetReader.next();
                if (event == XMLStreamConstants.END_ELEMENT && sheetReader.getLocalName().equals("row")) {
                    // if the row has ended, break the inner while loop
                    break;
                }
                if (event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals("c")) {
                    String attributeValue = sheetReader.getAttributeValue(null, "t");
                    if (attributeValue != null && attributeValue.equals("s")) {
                        // only if the type of the cell is string, we continue
                        while (sheetReader.hasNext()) {
                            event = sheetReader.next();
                            if (event == XMLStreamConstants.START_ELEMENT
                                    && sheetReader.getLocalName().equals("v")) {
                                int idx = Integer.parseInt(sheetReader.getElementText());
                                String content = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
                                headerRow.add(content);
                                break;
                            }
                        }
                    } else {
                        break;
                    }
                }
            }
            // we have parsed the header row
            break;
        }
    }
}

From source file:org.pentaho.di.trans.steps.excelinput.staxpoi.StaxPoiSheet.java

private void resetSheetReader() throws IOException, XMLStreamException, InvalidFormatException {
    sheetReader.close();//from   w  w  w .  j  a  v  a  2 s  . c  o m
    sheetStream.close();
    sheetStream = xssfReader.getSheet(sheetId);
    XMLInputFactory factory = XMLInputFactory.newInstance();
    sheetReader = factory.createXMLStreamReader(sheetStream);
}

From source file:org.pentaho.di.trans.steps.webservices.WebService.java

private void compatibleProcessRows(InputStream anXml, Object[] rowData, RowMetaInterface rowMeta,
        boolean ignoreNamespacePrefix, String encoding) throws KettleException {

    // First we should get the complete string
    // The problem is that the string can contain XML or any other format such as HTML saying the service is no longer
    // available.
    // We're talking about a WEB service here.
    // As such, to keep the original parsing scheme, we first read the content.
    // Then we create an input stream from the content again.
    // It's elaborate, but that way we can report on the failure more correctly.
    ////from   ww w .  j  a va  2 s.  com
    String response = readStringFromInputStream(anXml, encoding);

    // Create a new reader to feed into the XML Input Factory below...
    //
    StringReader stringReader = new StringReader(response.toString());

    // TODO Very empirical : see if we can do something better here
    try {
        XMLInputFactory vFactory = XMLInputFactory.newInstance();
        XMLStreamReader vReader = vFactory.createXMLStreamReader(stringReader);

        Object[] outputRowData = RowDataUtil.allocateRowData(data.outputRowMeta.size());
        int outputIndex = 0;

        boolean processing = false;
        boolean oneValueRowProcessing = false;
        for (int event = vReader.next(); vReader.hasNext(); event = vReader.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:

                // Start new code
                // START_ELEMENT= 1
                //
                if (log.isRowLevel()) {
                    logRowlevel("START_ELEMENT / " + vReader.getAttributeCount() + " / "
                            + vReader.getNamespaceCount());
                }

                // If we start the xml element named like the return type,
                // we start a new row
                //
                if (log.isRowLevel()) {
                    logRowlevel("vReader.getLocalName = " + vReader.getLocalName());
                }
                if (Const.isEmpty(meta.getOutFieldArgumentName())) {
                    // getOutFieldArgumentName() == null
                    if (oneValueRowProcessing) {
                        WebServiceField field = meta.getFieldOutFromWsName(vReader.getLocalName(),
                                ignoreNamespacePrefix);
                        if (field != null) {
                            outputRowData[outputIndex++] = getValue(vReader.getElementText(), field);
                            putRow(data.outputRowMeta, outputRowData);
                            oneValueRowProcessing = false;
                        } else {
                            if (meta.getOutFieldContainerName().equals(vReader.getLocalName())) {
                                // meta.getOutFieldContainerName() = vReader.getLocalName()
                                if (log.isRowLevel()) {
                                    logRowlevel("OutFieldContainerName = " + meta.getOutFieldContainerName());
                                }
                                oneValueRowProcessing = true;
                            }
                        }
                    }
                } else {
                    // getOutFieldArgumentName() != null
                    if (log.isRowLevel()) {
                        logRowlevel("OutFieldArgumentName = " + meta.getOutFieldArgumentName());
                    }
                    if (meta.getOutFieldArgumentName().equals(vReader.getLocalName())) {
                        if (log.isRowLevel()) {
                            logRowlevel("vReader.getLocalName = " + vReader.getLocalName());
                        }
                        if (log.isRowLevel()) {
                            logRowlevel("OutFieldArgumentName = ");
                        }
                        if (processing) {
                            WebServiceField field = meta.getFieldOutFromWsName(vReader.getLocalName(),
                                    ignoreNamespacePrefix);
                            if (field != null) {
                                int index = data.outputRowMeta.indexOfValue(field.getName());
                                if (index >= 0) {
                                    outputRowData[index] = getValue(vReader.getElementText(), field);
                                }
                            }
                            processing = false;
                        } else {
                            WebServiceField field = meta.getFieldOutFromWsName(vReader.getLocalName(),
                                    ignoreNamespacePrefix);
                            if (meta.getFieldsOut().size() == 1 && field != null) {
                                // This can be either a simple return element, or a complex type...
                                //
                                try {
                                    if (meta.isPassingInputData()) {
                                        for (int i = 0; i < rowMeta.getValueMetaList().size(); i++) {
                                            ValueMetaInterface valueMeta = getInputRowMeta().getValueMeta(i);
                                            outputRowData[outputIndex++] = valueMeta.cloneValueData(rowData[i]);

                                        }
                                    }

                                    outputRowData[outputIndex++] = getValue(vReader.getElementText(), field);
                                    putRow(data.outputRowMeta, outputRowData);
                                } catch (WstxParsingException e) {
                                    throw new KettleStepException("Unable to get value for field ["
                                            + field.getName()
                                            + "].  Verify that this is not a complex data type by looking at the response XML.",
                                            e);
                                }
                            } else {
                                for (WebServiceField curField : meta.getFieldsOut()) {
                                    if (!Const.isEmpty(curField.getName())) {
                                        outputRowData[outputIndex++] = getValue(vReader.getElementText(),
                                                curField);
                                    }
                                }
                                processing = true;
                            }
                        }

                    } else {
                        if (log.isRowLevel()) {
                            logRowlevel("vReader.getLocalName = " + vReader.getLocalName());
                        }
                        if (log.isRowLevel()) {
                            logRowlevel("OutFieldArgumentName = " + meta.getOutFieldArgumentName());
                        }
                    }
                }
                break;

            case XMLStreamConstants.END_ELEMENT:
                // END_ELEMENT= 2
                if (log.isRowLevel()) {
                    logRowlevel("END_ELEMENT");
                }
                // If we end the xml element named as the return type, we
                // finish a row
                if ((meta.getOutFieldArgumentName() == null
                        && meta.getOperationName().equals(vReader.getLocalName()))) {
                    oneValueRowProcessing = false;
                } else if (meta.getOutFieldArgumentName() != null
                        && meta.getOutFieldArgumentName().equals(vReader.getLocalName())) {
                    putRow(data.outputRowMeta, outputRowData);
                    processing = false;
                }
                break;
            case XMLStreamConstants.PROCESSING_INSTRUCTION:
                // PROCESSING_INSTRUCTION= 3
                if (log.isRowLevel()) {
                    logRowlevel("PROCESSING_INSTRUCTION");
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                // CHARACTERS= 4
                if (log.isRowLevel()) {
                    logRowlevel("CHARACTERS");
                }
                break;
            case XMLStreamConstants.COMMENT:
                // COMMENT= 5
                if (log.isRowLevel()) {
                    logRowlevel("COMMENT");
                }
                break;
            case XMLStreamConstants.SPACE:
                // PROCESSING_INSTRUCTION= 6
                if (log.isRowLevel()) {
                    logRowlevel("PROCESSING_INSTRUCTION");
                }
                break;
            case XMLStreamConstants.START_DOCUMENT:
                // START_DOCUMENT= 7
                if (log.isRowLevel()) {
                    logRowlevel("START_DOCUMENT");
                }
                if (log.isRowLevel()) {
                    logRowlevel(vReader.getText());
                }
                break;
            case XMLStreamConstants.END_DOCUMENT:
                // END_DOCUMENT= 8
                if (log.isRowLevel()) {
                    logRowlevel("END_DOCUMENT");
                }
                break;
            case XMLStreamConstants.ENTITY_REFERENCE:
                // ENTITY_REFERENCE= 9
                if (log.isRowLevel()) {
                    logRowlevel("ENTITY_REFERENCE");
                }
                break;
            case XMLStreamConstants.ATTRIBUTE:
                // ATTRIBUTE= 10
                if (log.isRowLevel()) {
                    logRowlevel("ATTRIBUTE");
                }
                break;
            case XMLStreamConstants.DTD:
                // DTD= 11
                if (log.isRowLevel()) {
                    logRowlevel("DTD");
                }
                break;
            case XMLStreamConstants.CDATA:
                // CDATA= 12
                if (log.isRowLevel()) {
                    logRowlevel("CDATA");
                }
                break;
            case XMLStreamConstants.NAMESPACE:
                // NAMESPACE= 13
                if (log.isRowLevel()) {
                    logRowlevel("NAMESPACE");
                }
                break;
            case XMLStreamConstants.NOTATION_DECLARATION:
                // NOTATION_DECLARATION= 14
                if (log.isRowLevel()) {
                    logRowlevel("NOTATION_DECLARATION");
                }
                break;
            case XMLStreamConstants.ENTITY_DECLARATION:
                // ENTITY_DECLARATION= 15
                if (log.isRowLevel()) {
                    logRowlevel("ENTITY_DECLARATION");
                }
                break;
            default:
                break;
            }
        }
    } catch (Exception e) {
        throw new KettleStepException(
                BaseMessages.getString(PKG, "WebServices.ERROR0010.OutputParsingError", response.toString()),
                e);
    }
}

From source file:org.pentaho.di.trans.steps.xmlinputstream.XMLInputStream.java

@Override
public boolean init(StepMetaInterface smi, StepDataInterface sdi) {
    meta = (XMLInputStreamMeta) smi;//from  w  w w.  j  a v a  2  s  .c  om
    data = (XMLInputStreamData) sdi;

    if (super.init(smi, sdi)) {
        data.staxInstance = XMLInputFactory.newInstance(); // could select the parser later on
        data.filenr = 0;
        if (getTransMeta().findNrPrevSteps(getStepMeta()) == 0 && !meta.sourceFromInput) {
            String filename = environmentSubstitute(meta.getFilename());
            if (Utils.isEmpty(filename)) {
                logError(BaseMessages.getString(PKG, "XMLInputStream.MissingFilename.Message"));
                return false;
            }

            data.filenames = new String[] { filename, };
        } else {
            data.filenames = null;
        }

        data.nrRowsToSkip = Const.toLong(this.environmentSubstitute(meta.getNrRowsToSkip()), 0);
        data.rowLimit = Const.toLong(this.environmentSubstitute(meta.getRowLimit()), 0);
        data.encoding = this.environmentSubstitute(meta.getEncoding());

        data.outputRowMeta = new RowMeta();
        meta.getFields(data.outputRowMeta, getStepname(), null, null, this, repository, metaStore);

        // get and save field positions
        data.pos_xml_filename = data.outputRowMeta.indexOfValue(meta.getFilenameField());
        data.pos_xml_row_number = data.outputRowMeta.indexOfValue(meta.getRowNumberField());
        data.pos_xml_data_type_numeric = data.outputRowMeta.indexOfValue(meta.getXmlDataTypeNumericField());
        data.pos_xml_data_type_description = data.outputRowMeta
                .indexOfValue(meta.getXmlDataTypeDescriptionField());
        data.pos_xml_location_line = data.outputRowMeta.indexOfValue(meta.getXmlLocationLineField());
        data.pos_xml_location_column = data.outputRowMeta.indexOfValue(meta.getXmlLocationColumnField());
        data.pos_xml_element_id = data.outputRowMeta.indexOfValue(meta.getXmlElementIDField());
        data.pos_xml_parent_element_id = data.outputRowMeta.indexOfValue(meta.getXmlParentElementIDField());
        data.pos_xml_element_level = data.outputRowMeta.indexOfValue(meta.getXmlElementLevelField());
        data.pos_xml_path = data.outputRowMeta.indexOfValue(meta.getXmlPathField());
        data.pos_xml_parent_path = data.outputRowMeta.indexOfValue(meta.getXmlParentPathField());
        data.pos_xml_data_name = data.outputRowMeta.indexOfValue(meta.getXmlDataNameField());
        data.pos_xml_data_value = data.outputRowMeta.indexOfValue(meta.getXmlDataValueField());
        return true;
    }
    return false;
}

From source file:org.pentaho.platform.dataaccess.client.ConnectionServiceClient.java

protected Object[] getResponseObjects(Object[] types, Element rootNode) throws XMLStreamException, AxisFault {
    ByteArrayInputStream in = new ByteArrayInputStream(rootNode.asXML().getBytes());
    XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(in);

    StAXOMBuilder builder = new StAXOMBuilder(parser);
    //get the root element (in this case the envelope)
    OMElement omElement = builder.getDocumentElement();
    OMElement bodyElement = omElement.getFirstElement();
    OMElement responseElement = bodyElement.getFirstElement();
    Object results[] = BeanUtil.deserialize(responseElement, types, this);
    return results;
}

From source file:org.pentaho.platform.dataaccess.client.ConnectionServiceClient.java

public DatabaseConnection deserializeDatabaseConnection(Element rootNode) throws XMLStreamException, AxisFault {

    System.out.println(rootNode.asXML());
    ByteArrayInputStream in = new ByteArrayInputStream(rootNode.asXML().getBytes());
    XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(in);

    StAXOMBuilder builder = new StAXOMBuilder(parser);
    //get the root element (in this case the envelope)
    OMElement omElement = builder.getDocumentElement();
    OMElement bodyElement = omElement.getFirstElement();
    OMElement responseElement = bodyElement.getFirstElement();
    Object types[] = new Object[] { DatabaseConnection.class };
    Object results[] = BeanUtil.deserialize(responseElement, types, this);
    if (results == null || results.length == 0) {
        return null;
    }/*  www  . ja v a 2s  . c  o m*/
    return (DatabaseConnection) results[0];
}

From source file:org.pentaho.platform.dataaccess.datasource.api.AnalysisService.java

private String getSchemaName(String encoding, InputStream inputStream) throws XMLStreamException, IOException {
    String domainId = null;/* w  w  w. ja va  2  s. com*/
    XMLStreamReader reader = null;
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        if (StringUtils.isEmpty(encoding)) {
            reader = factory.createXMLStreamReader(inputStream);
        } else {
            reader = factory.createXMLStreamReader(inputStream, encoding);
        }

        while (reader.next() != XMLStreamReader.END_DOCUMENT) {
            if (reader.getEventType() == XMLStreamReader.START_ELEMENT
                    && reader.getLocalName().equalsIgnoreCase("Schema")) {
                domainId = reader.getAttributeValue("", "name");
                return domainId;
            }
        }
    } finally {
        if (reader != null) {
            reader.close();
        }
        inputStream.reset();
    }

    return domainId;
}