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.jasig.schedassist.impl.caldav.xml.ReportResponseHandlerImpl.java

/**
 * Extracts a {@link List} of {@link Calendar}s from the {@link InputStream}, if present.
 * /* w  w w .j  av a  2 s .  co  m*/
 * @param inputStream
 * @return a never null, but possibly empty {@link List} of {@link Calendar}s from the {@link InputStream}
 * @throws XmlParsingException in the event the stream could not be properly parsed
 */
public List<CalendarWithURI> extractCalendars(InputStream inputStream) {
    List<CalendarWithURI> results = new ArrayList<CalendarWithURI>();
    ByteArrayOutputStream capturedContent = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        InputStream localReference = inputStream;
        if (log.isDebugEnabled()) {
            capturedContent = new ByteArrayOutputStream();
            localReference = new TeeInputStream(inputStream, capturedContent);
        }
        BufferedInputStream buffered = new BufferedInputStream(localReference);
        buffered.mark(1);
        int firstbyte = buffered.read();
        if (-1 == firstbyte) {
            // short circuit on empty stream
            return results;
        }
        buffered.reset();
        XMLStreamReader parser = factory.createXMLStreamReader(buffered);

        String currentUri = null;
        String currentEtag = null;
        for (int eventType = parser.next(); eventType != XMLStreamConstants.END_DOCUMENT; eventType = parser
                .next()) {
            switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
                QName name = parser.getName();
                if (isWebdavHrefElement(name)) {
                    currentUri = parser.getElementText();
                } else if (isWebdavEtagElement(name)) {
                    currentEtag = parser.getElementText();
                } else if (isCalendarDataElement(name)) {
                    Calendar cal = extractCalendar(parser.getElementText());
                    if (cal != null) {
                        CalendarWithURI withUri = new CalendarWithURI(cal, currentUri, currentEtag);
                        results.add(withUri);
                    } else if (log.isDebugEnabled()) {
                        log.debug("extractCalendar returned null for " + currentUri + ", skipping");
                    }
                }
                break;
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("extracted " + results.size() + " calendar from " + capturedContent.toString());
        }

    } catch (XMLStreamException e) {
        if (capturedContent != null) {
            log.error("caught XMLStreamException in extractCalendars, captured content: "
                    + capturedContent.toString(), e);
        } else {
            log.error("caught XMLStreamException in extractCalendars, no captured content available", e);
        }
        throw new XmlParsingException("caught XMLStreamException in extractCalendars", e);
    } catch (IOException e) {
        log.error("caught IOException in extractCalendars", e);
        throw new XmlParsingException("caught IOException in extractCalendars", e);
    }

    return results;
}

From source file:org.jboss.datavirt.commons.auth.jboss7.SAMLBearerTokenLoginModule.java

/**
 * @see org.jboss.security.auth.spi.AbstractServerLoginModule#login()
 *///w  w  w  .j  a v  a 2  s. co m
@Override
public boolean login() throws LoginException {
    try {
        HttpServletRequest request = getCurrentRequest();
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Basic")) {
            String b64Data = authorization.substring(6);
            byte[] dataBytes = Base64.decodeBase64(b64Data);
            String data = new String(dataBytes, "UTF-8");
            if (data.startsWith("SAML-BEARER-TOKEN:")) {
                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)) {
                    KeyPair keyPair = getKeyPair(assertion);
                    if (!SAMLBearerTokenUtil.isSAMLAssertionSignatureValid(samlAssertion, keyPair)) {
                        throw new LoginException("Invalid signature found on SAML assertion!");
                    }
                }
                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.jboss.rusheye.parser.Parser.java

private void parseFile(File file, boolean tmpfile) {
    VisualSuite visualSuite = null;/*  w ww. jav a 2s  .  c om*/
    try {
        XMLValidationSchemaFactory schemaFactory = XMLValidationSchemaFactory
                .newInstance(XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA);
        URL schemaURL = getClass().getClassLoader().getResource("org/jboss/rusheye/visual-suite.xsd");
        XMLValidationSchema schema = schemaFactory.createSchema(schemaURL);

        XMLInputFactory2 factory = (XMLInputFactory2) XMLInputFactory.newInstance();

        StreamFilter filter = new StreamFilter() {
            @Override
            public boolean accept(XMLStreamReader reader) {
                return reader.isStartElement();
            }
        };

        XMLStreamReader2 reader = factory.createXMLStreamReader(file);
        XMLStreamReader2 filteredReader = new Stax2FilteredStreamReader(reader, filter);

        reader.validateAgainst(schema);

        // EventFilter filter = new EventFilter() {
        // @Override
        // public boolean accept(XMLEvent reader) {
        // return reader.isStartElement();
        // }
        // };
        //
        // XMLEventReader reader = factory.createXMLEventReader(file);
        // XMLEventReader filteredReader = factory.createFilteredReader(reader, filter);

        JAXBContext ctx = JAXBContext.newInstance(VisualSuite.class.getPackage().getName());
        Unmarshaller um = ctx.createUnmarshaller();

        UnmarshallerMultiListener listener = new UnmarshallerMultiListener();
        um.setListener(listener);

        // skip parsing of the first element - visual-suite
        filteredReader.nextTag();

        visualSuite = new VisualSuite();
        handler.setVisualSuite(visualSuite);
        handler.getContext().invokeListeners().onSuiteStarted(visualSuite);

        listener.registerListener(new UniqueIdentityChecker(handler.getContext()));

        while (filteredReader.hasNext()) {
            try {
                // go on the start of the next tag
                filteredReader.nextTag();

                Object o = um.unmarshal(reader);
                if (o instanceof GlobalConfiguration) {
                    GlobalConfiguration globalConfiguration = (GlobalConfiguration) o;
                    handler.getContext().setCurrentConfiguration(globalConfiguration);
                    visualSuite.setGlobalConfiguration(globalConfiguration);
                    handler.getContext().invokeListeners().onConfigurationReady(visualSuite);

                    RetriverInjector retriverInjector = new RetriverInjector(this);
                    for (Mask mask : globalConfiguration.getMasks()) {
                        retriverInjector.afterUnmarshal(mask, null);
                    }
                    listener.registerListener(retriverInjector);
                }
                if (o instanceof Test) {
                    Test test = (Test) o;
                    handler.getContext().setCurrentConfiguration(test);
                    handler.getContext().setCurrentTest(test);
                    for (Pattern pattern : test.getPatterns()) {
                        handler.getContext().invokeListeners().onPatternReady(test, pattern);
                    }
                    Test testWrapped = ConfigurationCompiler.wrap(test, visualSuite.getGlobalConfiguration());
                    handler.getContext().invokeListeners().onTestReady(testWrapped);
                }
            } catch (WstxParsingException e) {
                // intentionally blank - wrong end of document detection
            }

        }
    } catch (XMLStreamException e) {
        throw handleParsingException(e, e);
    } catch (JAXBException e) {
        throw handleParsingException(e, e.getLinkedException());
    } finally {
        if (visualSuite != null && handler.getContext() != null) {
            handler.getContext().invokeListeners().onSuiteReady(visualSuite);
        }
        if (tmpfile) {
            FileUtils.deleteQuietly(file);
        }
    }
}

From source file:org.jbpm.designer.web.profile.impl.JbpmProfileImpl.java

private void initializeLocalPlugins(ServletContext context) {
    Map<String, IDiagramPlugin> registry = PluginServiceImpl.getLocalPluginsRegistry(context);
    FileInputStream fileStream = null;
    try {//from ww w  .  j a  v  a 2s.  c  o m
        try {
            fileStream = new FileInputStream(new StringBuilder(context.getRealPath("/")).append("/")
                    .append(ConfigurationProvider.getInstance().getDesignerContext()).append("profiles")
                    .append("/").append("jbpm.xml").toString());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = factory.createXMLStreamReader(fileStream, "UTF-8");
        while (reader.hasNext()) {
            if (reader.next() == XMLStreamReader.START_ELEMENT) {
                if ("profile".equals(reader.getLocalName())) {
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("stencilset".equals(reader.getAttributeLocalName(i))) {
                            _stencilSet = reader.getAttributeValue(i);
                        }
                    }
                } else if ("plugin".equals(reader.getLocalName())) {
                    String name = null;
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("name".equals(reader.getAttributeLocalName(i))) {
                            name = reader.getAttributeValue(i);
                        }
                    }
                    _plugins.put(name, registry.get(name));
                } else if ("localhistory".equals(reader.getLocalName())) {
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("enabled".equals(reader.getAttributeLocalName(i))) {
                            String localhistoryenabled = reader.getAttributeValue(i);
                            if (!isEmpty(localhistoryenabled)) {
                                _localHistoryEnabled = localhistoryenabled;
                            } else {
                                _logger.info("Invalid local history enabled");
                            }
                        }
                        if ("timeout".equals(reader.getAttributeLocalName(i))) {
                            String localhistorytimeout = reader.getAttributeValue(i);
                            if (!isEmpty(localhistorytimeout)) {
                                _localHistoryTimeout = localhistorytimeout;
                            } else {
                                _logger.info("Invalid local history timeout");
                            }
                        }
                    }
                } else if ("storesvgonsave".equals(reader.getLocalName())) {
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("enabled".equals(reader.getAttributeLocalName(i))) {
                            String storesvgonsaveenabled = reader.getAttributeValue(i);
                            if (!isEmpty(storesvgonsaveenabled)) {
                                _storeSVGonSaveOption = storesvgonsaveenabled;
                            } else {
                                _logger.info("Invalid store svg on save enabled");
                            }
                        }
                    }
                }
            }
        }
    } catch (XMLStreamException e) {
        _logger.error(e.getMessage(), e);
        throw new RuntimeException(e); // stop initialization
    } finally {
        if (fileStream != null) {
            try {
                fileStream.close();
            } catch (IOException e) {
            }
        }
        ;
    }
}

From source file:org.jbpm.designer.web.server.ProcessDiffServiceServlet.java

private List<String> getAssetVersions(String packageName, String assetName, String uuid,
        IDiagramProfile profile) {/*from   w ww  .ja  v  a2 s .co m*/
    try {
        String assetVersionURL = RepositoryInfo.getRepositoryProtocol(profile) + "://"
                + RepositoryInfo.getRepositoryHost(profile) + "/"
                + RepositoryInfo.getRepositorySubdomain(profile).substring(0,
                        RepositoryInfo.getRepositorySubdomain(profile).indexOf("/"))
                + "/rest/packages/" + URLEncoder.encode(packageName, "UTF-8") + "/assets/" + assetName
                + "/versions/";
        List<String> versionList = new ArrayList<String>();

        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = factory.createXMLStreamReader(
                ServletUtil.getInputStreamForURL(assetVersionURL, "GET", profile), "UTF-8");
        boolean isFirstTitle = true;
        String title = "";
        while (reader.hasNext()) {
            int next = reader.next();
            if (next == XMLStreamReader.START_ELEMENT) {
                if ("title".equals(reader.getLocalName())) {
                    if (isFirstTitle) {
                        isFirstTitle = false;
                    } else {
                        versionList.add(reader.getElementText());
                    }
                }
            }
        }
        return versionList;
    } catch (Exception e) {
        _logger.error(e.getMessage());
        return null;
    }
}

From source file:org.jmecsoftware.plugins.tests.utils.StaxParser.java

/**
 * Stax parser for a given stream handler and iso control chars set awarness to on.
 * The iso control chars in the xml file will be replaced by simple spaces, usefull for
 * potentially bogus XML files to parse, this has a small perfs overhead so use it only when necessary
 *
 * @param streamHandler              the xml stream handler
 * @param isoControlCharsAwareParser true or false
 *//*from   w w w.j  ava 2  s  .  co m*/
public StaxParser(XmlStreamHandler streamHandler, boolean isoControlCharsAwareParser) {
    this.streamHandler = streamHandler;
    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
    if (xmlFactory instanceof WstxInputFactory) {
        WstxInputFactory wstxInputfactory = (WstxInputFactory) xmlFactory;
        wstxInputfactory.configureForLowMemUsage();
        wstxInputfactory.getConfig().setUndeclaredEntityResolver(new UndeclaredEntitiesXMLResolver());
    }
    xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
    xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
    this.isoControlCharsAwareParser = isoControlCharsAwareParser;
    inf = new SMInputFactory(xmlFactory);
}

From source file:org.jwifisd.eyefi.Main.java

private static void getPhotoStatus(Request request, Response response, final String date)
        throws FactoryConfigurationError, XMLStreamException, IOException {
    String macaddress = null;//from www  .  j a v a2s .c o m
    String credential = null;
    String filename = null;
    String filesize = null;
    String filesignature = null;
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLEventReader eventReader = inputFactory.createXMLEventReader(request.getInputStream());
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();
        if (event.isStartElement()) {
            if (event.asStartElement().getName().getLocalPart().equals("macaddress")) {
                event = eventReader.nextEvent();
                macaddress = event.asCharacters().getData();
                continue;
            }
            if (event.asStartElement().getName().getLocalPart().equals("credential")) {
                event = eventReader.nextEvent();
                credential = event.asCharacters().getData();
                continue;
            }
            if (event.asStartElement().getName().getLocalPart().equals("filename")) {
                event = eventReader.nextEvent();
                filename = event.asCharacters().getData();
                continue;
            }
            if (event.asStartElement().getName().getLocalPart().equals("filesize")) {
                event = eventReader.nextEvent();
                filesize = event.asCharacters().getData();
                continue;
            }
            if (event.asStartElement().getName().getLocalPart().equals("filesignature")) {
                event = eventReader.nextEvent();
                filesignature = event.asCharacters().getData();
                continue;
            }
        }
    }
    System.out.println("macaddress:" + macaddress);
    System.out.println("credential:" + credential);
    System.out.println("filename:" + filename);
    System.out.println("filesize:" + filesize);
    System.out.println("filesignature:" + filesignature);

    response.setHeader("Server", "Eye-Fi Agent/2.0.4.0");
    response.setHeader("Date", date);
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Content-Type", "text/xml; charset=\"utf-8\"");

    String responseText = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //
            "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" + //
            /**/"<SOAP-ENV:Body>\n" + //
            /*  */"<GetPhotoStatusResponse xmlns=\"http://localhost/api/soap/eyefilm\">" + //
            /*    */"<fileid>1</fileid><offset>0</offset>" + //
            /*  */"</GetPhotoStatusResponse>" + //
            /**/"</SOAP-ENV:Body>" + //
            "</SOAP-ENV:Envelope>";

    response.setContentLength(responseText.length());
    response.getWriter().write(responseText);
}

From source file:org.jwifisd.eyefi.Main.java

private static void startSession(Request request, Response response, final String date)
        throws Exception, IOException {
    String macaddress = null;/*from   ww  w.j  a  v a 2 s .  com*/
    String cnonce = null;
    String transfermode = null;
    String transfermodetimestamp = null;
    System.out.println("connectx");
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLEventReader eventReader = inputFactory.createXMLEventReader(request.getInputStream());
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();
        if (event.isStartElement()) {
            if (event.asStartElement().getName().getLocalPart().equals("macaddress")) {
                event = eventReader.nextEvent();
                macaddress = event.asCharacters().getData();
                continue;
            }
            if (event.asStartElement().getName().getLocalPart().equals("cnonce")) {
                event = eventReader.nextEvent();
                cnonce = event.asCharacters().getData();
                continue;
            }
            if (event.asStartElement().getName().getLocalPart().equals("transfermode")) {
                event = eventReader.nextEvent();
                transfermode = event.asCharacters().getData();
                continue;
            }
            if (event.asStartElement().getName().getLocalPart().equals("transfermodetimestamp")) {
                event = eventReader.nextEvent();
                transfermodetimestamp = event.asCharacters().getData();
                continue;
            }
        }
    }
    System.out.println("macaddress:" + macaddress);
    System.out.println("cnonce:" + cnonce);
    System.out.println("transfermode:" + transfermode);
    System.out.println("transfermodetimestamp:" + transfermodetimestamp);
    byte[] cnonceBytes = Hex.decodeHex(cnonce.toCharArray());
    byte[] uploadKey = Hex.decodeHex("00000000000000000000000000000000".toCharArray());
    byte[] credential = md5(Hex.decodeHex(macaddress.toCharArray()), cnonceBytes, uploadKey);
    String credentialStr = Hex.encodeHexString(credential);

    response.setHeader("Server", "Eye-Fi Agent/2.0.4.0");
    response.setHeader("Date", date);
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Content-Type", "text/xml; charset=\"utf-8\"");

    String responseText = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //
            "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" + //
            /**/"<SOAP-ENV:Body>" + //
            /*  */"<StartSessionResponse xmlns=\"http://localhost/api/soap/eyefilm\">" + //
            /*    */"<credential>" + credentialStr + "</credential>" + //
            /*    */"<snonce>" + cnonce + "</snonce>" + //
            /*    */"<transfermode>2</transfermode>" + //
            /*    */"<transfermodetimestamp>1230268824</transfermodetimestamp>" + //
            /*    */"<upsyncallowed>false</upsyncallowed>" + //
            /*  */"</StartSessionResponse>" + //
            /**/"</SOAP-ENV:Body>" + //
            "</SOAP-ENV:Envelope>";
    System.out.println(responseText);
    response.setContentLength(responseText.length());
    response.getWriter().write(responseText);
}

From source file:org.lib4j.cli.Options.java

public static Options parse(final URL cliURL, final Class<?> mainClass, final String[] args) {
    try {/* w w  w . jav  a  2 s.  com*/
        final Unmarshaller unmarshaller = JAXBContext.newInstance(Cli.class).createUnmarshaller();
        unmarshaller
                .setSchema(
                        Options.schema == null
                                ? Options.schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                                        .newSchema(Thread.currentThread().getContextClassLoader()
                                                .getResource("cli.xsd"))
                                : Options.schema);

        try (final InputStream in = cliURL.openStream()) {
            final JAXBElement<Cli> element = unmarshaller
                    .unmarshal(XMLInputFactory.newInstance().createXMLStreamReader(in), Cli.class);
            return parse(element.getValue(), mainClass, args);
        }
    } catch (final FactoryConfigurationError e) {
        throw new UnsupportedOperationException(e);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    } catch (final JAXBException | SAXException | XMLStreamException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.lib4j.dbcp.DataSources.java

/**
 * Create a <code>BasicDataSource</code> given a dbcp JAXB binding.
 *
 * @param dbcpXml URL of dbcp xml resource.
 * @param driverClassLoader Class loader to be used to load the JDBC driver.
 * @return the <code>BasicDataSource</code> instance.
 * @throws SAXException If a XML validation error occurs.
 * @throws SQLException If a database access error occurs.
 * @throws IOException If an IO exception occurs.
 *///  w ww . ja  va  2s  .  c o  m
public static BasicDataSource createDataSource(final URL dbcpXml, final ClassLoader driverClassLoader)
        throws IOException, SAXException, SQLException {
    try {
        final Unmarshaller unmarshaller = JAXBContext.newInstance(Dbcp.class).createUnmarshaller();
        unmarshaller
                .setSchema(
                        DataSources.schema == null
                                ? DataSources.schema = SchemaFactory
                                        .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                                        .newSchema(Thread.currentThread().getContextClassLoader()
                                                .getResource("dbcp.xsd"))
                                : DataSources.schema);

        try (final InputStream in = dbcpXml.openStream()) {
            final JAXBElement<Dbcp> element = unmarshaller
                    .unmarshal(XMLInputFactory.newInstance().createXMLStreamReader(in), Dbcp.class);
            return createDataSource(element.getValue(), driverClassLoader);
        }
    } catch (final FactoryConfigurationError e) {
        throw new UnsupportedOperationException(e);
    } catch (final JAXBException | XMLStreamException e) {
        throw new SAXException(e);
    }
}