Example usage for javax.xml.parsers SAXParser parse

List of usage examples for javax.xml.parsers SAXParser parse

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParser parse.

Prototype

public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException 

Source Link

Document

Parse the content given org.xml.sax.InputSource as XML using the specified org.xml.sax.helpers.DefaultHandler .

Usage

From source file:org.sofun.platform.opta.parser.AbstractOptaParser.java

public void parseXmlFile() {
    SAXParserFactory factory = SAXParserFactory.newInstance();

    try {// ww  w.jav a 2  s.  c  o m
        SAXParser parser = factory.newSAXParser();
        if (f != null) {
            parser.parse(f, this);
        } else {
            log.error("File is null. Cannot parse.");
        }
    } catch (SAXException se) {
        se.printStackTrace();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (IOException ie) {
        ie.printStackTrace();
    }
}

From source file:org.sonar.plugins.xml.parsers.DetectSchemaParser.java

/**
 * Find the Doctype (DTD or schema)./*from   w w w . j ava  2 s.c  om*/
 */
public Doctype findDoctype(InputStream input) {
    Handler handler = new Handler();

    try {
        SAXParser parser = newSaxParser();
        XMLReader xmlReader = parser.getXMLReader();
        xmlReader.setFeature(Constants.XERCES_FEATURE_PREFIX + "continue-after-fatal-error", true);
        xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
        parser.parse(input, handler);
        return handler.doctype;
    } catch (IOException e) {
        throw new SonarException(e);
    } catch (StopParserException e) {
        return handler.doctype;
    } catch (SAXException e) {
        throw new SonarException(e);
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:org.sonar.plugins.xml.parsers.LineCountParser.java

private void processCommentLines(File file) throws SAXException, IOException {
    SAXParser parser = newSaxParser(false);
    XMLReader xmlReader = parser.getXMLReader();
    commentHandler = new CommentHandler();
    xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", commentHandler);
    parser.parse(FileUtils.openInputStream(file), commentHandler);
}

From source file:org.tonguetied.datatransfer.importing.ResourceImporter.java

@Override
protected void doImport(final byte[] input, final TranslationState state) throws ImportException {
    if (logger.isDebugEnabled())
        logger.debug("attempting import");
    ByteArrayInputStream bais = null;
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);/*from   w  w  w.  ja  v  a 2  s .c o  m*/
    factory.setNamespaceAware(true);
    try {
        //            validate(bais);
        //            XMLReader reader = XMLReaderFactory.createXMLReader();
        //            reader.setContentHandler(new ResourceHandler(
        //                    getBundle(), getCountry(), getLanguage(), state, getKeywordService()));
        //            // Request validation
        //            reader.setFeature("http://xml.org/sax/features/validation", true);
        //            InputSource is = new InputSource(bais);
        //            reader.parse(is);

        SAXParser parser = factory.newSAXParser();

        bais = new ByteArrayInputStream(input);
        parser.parse(bais,
                new ResourceHandler(getBundle(), getCountry(), getLanguage(), state, getKeywordService()));
    } catch (SAXException saxe) {
        throw new ImportException(saxe);
    } catch (ParserConfigurationException pce) {
        throw new ImportException(pce);
    } catch (IOException ioe) {
        throw new ImportException(ioe);
    } finally {
        IOUtils.closeQuietly(bais);
    }
}

From source file:org.walkmod.util.DomHelper.java

/**
 * Creates a W3C Document that remembers the location of each element in the
 * source file. The location of element nodes can then be retrieved using
 * the {@link #getLocationObject(Element)} method.
 *
 * @param inputSource/*from w  w  w .j ava2  s. c  om*/
 *            the inputSource to read the document from
 * @param dtdMappings
 *            a map of DTD names and public ids
 * @return Document
 */
public static Document parse(InputSource inputSource, Map<String, String> dtdMappings) {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating((dtdMappings != null));
    factory.setNamespaceAware(true);
    SAXParser parser = null;
    try {
        parser = factory.newSAXParser();
    } catch (Exception ex) {
        throw new WalkModException("Unable to create SAX parser", ex);
    }
    DOMBuilder builder = new DOMBuilder();
    ContentHandler locationHandler = new LocationAttributes.Pipe(builder);
    try {
        parser.parse(inputSource, new StartHandler(locationHandler, dtdMappings));
    } catch (Exception ex) {
        throw new WalkModException(ex);
    }
    return builder.getDocument();
}

From source file:org.wso2.carbon.sample.tfl.traffic.TrafficPollingTask.java

public void run() {
    try {//from w w  w  . j av a 2 s  . com
        URL obj = new URL(streamURL);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        ArrayList<Disruption> disruptionsList = new ArrayList<Disruption>();
        try {
            // optional default is GET
            con.setRequestMethod("GET");
            int responseCode = con.getResponseCode();
            log.info("Sending 'GET' request to URL : " + streamURL);
            log.info("Response Code : " + responseCode);

            double t = System.currentTimeMillis();
            // Get SAX Parser Factory
            SAXParserFactory factory = SAXParserFactory.newInstance();
            // Turn on validation, and turn off namespaces
            factory.setValidating(true);
            factory.setNamespaceAware(false);
            SAXParser parser = factory.newSAXParser();
            parser.parse(con.getInputStream(), new TrafficXMLHandler(disruptionsList));
            log.info("Number of Disruptions added to the list: " + disruptionsList.size());
            log.info("Time taken for parsing: " + (System.currentTimeMillis() - t));
        } catch (ParserConfigurationException e) {
            log.info("The underlying parser does not support " + " the requested features.");
        } catch (FactoryConfigurationError e) {
            log.info("Error occurred obtaining SAX Parser Factory.");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            con.disconnect();
        }

        ArrayList<String> list = new ArrayList<String>();
        int count = 0;
        for (Disruption disruption : disruptionsList) {
            if (disruption.getState().contains("Active")) {
                list.add(disruption.toJson());
            }
            count++;
        }
        TflStream.writeToFile("tfl-traffic-data.out", list, true);
    } catch (IOException e) {
        log.error("Error occurred while getting traffic data: " + e.getMessage(), e);
    }

}

From source file:org.wso2.carbon.transport.http.netty.internal.NettyTransportActivator.java

/**
 * Parse the  netty-transports.xml config file & create the Netty transport instances
 * @return Netty transport instances/*from w  w w. jav  a2  s.  c  o m*/
 */
private Set<NettyListener> createNettyServices() {
    final Set<NettyListener> listeners = new HashSet<>();
    DefaultHandler handler = new DefaultHandler() {

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            super.startElement(uri, localName, qName, attributes);
            if (qName.equals("listener")) {
                String id = attributes.getValue("id");
                String host = attributes.getValue("host");
                String port = attributes.getValue("port");
                String bossThreadPoolSize = attributes.getValue("bossThreadPoolSize");
                String workerThreadPoolSize = attributes.getValue("workerThreadPoolSize");
                String execHandlerThreadPoolSize = attributes.getValue("execHandlerThreadPoolSize");

                String scheme = attributes.getValue("scheme");
                String keystoreFile = attributes.getValue("keystoreFile");
                String keystorePass = attributes.getValue("keystorePass");
                String certPass = attributes.getValue("certPass");
                String trustStoreFile = attributes.getValue("trustStoreFile");
                String trustStorePass = attributes.getValue("trustStorePass");

                NettyListener.Config nettyConfig = new NettyListener.Config(id);
                if (host != null) {
                    nettyConfig.setHost(host);
                }
                if (port != null) {
                    nettyConfig.setPort(Integer.parseInt(port));
                }
                if (bossThreadPoolSize != null) {
                    nettyConfig.setBossThreads(Integer.parseInt(bossThreadPoolSize));
                }
                if (workerThreadPoolSize != null) {
                    nettyConfig.setWorkerThreads(Integer.parseInt(workerThreadPoolSize));
                }
                if (execHandlerThreadPoolSize != null) {
                    nettyConfig.setExecThreads(Integer.parseInt(execHandlerThreadPoolSize));
                }

                if (scheme != null && scheme.equalsIgnoreCase("https")) {
                    if (certPass == null) {
                        certPass = keystorePass;
                    }
                    if (keystoreFile == null || keystorePass == null) {
                        throw new IllegalArgumentException(
                                "keyStoreFile or keyStorePass not defined for HTTPS scheme");
                    }
                    File keyStore = new File(keystoreFile);
                    if (!keyStore.exists()) {
                        throw new IllegalArgumentException("KeyStore File " + keystoreFile + " not found");
                    }
                    SSLConfig sslConfig = new SSLConfig(keyStore, keystorePass).setCertPass(certPass);
                    if (trustStoreFile != null) {
                        File trustStore = new File(trustStoreFile);
                        if (!trustStore.exists()) {
                            throw new IllegalArgumentException(
                                    "trustStore File " + trustStoreFile + " not found");
                        }
                        if (trustStorePass == null) {
                            throw new IllegalArgumentException(
                                    "trustStorePass is not defined for HTTPS scheme");
                        }
                        sslConfig.setTrustStore(trustStore).setTrustStorePass(trustStorePass);
                    }
                    nettyConfig.enableSsl(sslConfig);
                }
                listeners.add(new NettyListener(nettyConfig));
            }
        }
    };

    String nettyTransportsXML = "repository" + File.separator + "conf" + File.separator + "transports"
            + File.separator + "netty-transports.xml";
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(nettyTransportsXML, handler);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        log.error("Cannot parse " + nettyTransportsXML, e);
    }
    return listeners;
}

From source file:org.xulux.dataprovider.DictionaryHandler.java

/**
 * Read the dictionary from an inputstream
 * @param stream the stream with the dictionary xml
 *//*w  w w .  ja va  2s .c o m*/
public void read(InputStream stream) {
    SAXParser saxParser = null;
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    try {
        saxParser = factory.newSAXParser();
        try {
            saxParser.parse(stream, this);
        } catch (SAXException se) {
            se.printStackTrace(System.err);
            se.getException().printStackTrace(System.err);
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
    // and clean up..
    saxParser = null;
    factory = null;
}

From source file:org.xulux.guidriver.XuluxGuiDriver.java

/**
 * Start processing the xml/*w  ww  . ja v a 2  s .  co  m*/
 * @param stream the stream containing the xml
 */
public void read(InputStream stream) {
    if (factory == null) {
        factory = SAXParserFactory.newInstance();
        factory.setValidating(false);
    }
    try {
        SAXParser saxParser = factory.newSAXParser();
        try {
            saxParser.parse(stream, this);
            stream.close();
        } catch (SAXException se) {
            if (log.isFatalEnabled()) {
                log.fatal("Exception during parsing of part xml", se);
                log.fatal("Exception during parsing of part xml", se.getException());
            }
        } finally {
            // and clean up..
            saxParser = null;
        }
    } catch (Exception e) {
        if (log.isFatalEnabled()) {
            log.fatal("Exception during parsing of part xml", e);
        }
    }
}

From source file:oscar.util.Doc2PDF.java

public static String GetPDFBin(HttpServletResponse response, String docText) {
    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 36, 36, 36, 36);
    // Document document = new Document(PageSize.A4.rotate());

    try {/*from www . j  a  v a2 s . c o m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);

        // step 3: we create a parser and set the document handler
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

        // step 4: we parse the document
        // use input stream  
        parser.parse(new ByteArrayInputStream(docText.getBytes()), new SAXmyHtmlHandler(document));

        document.close();

        return (new String(Base64.encodeBase64(baos.toByteArray())));
    }

    catch (Exception e) {
        logger.error("Unexpected error", e);
    }
    return null;

}