Example usage for javax.xml.parsers SAXParserFactory newInstance

List of usage examples for javax.xml.parsers SAXParserFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory newInstance.

Prototype


public static SAXParserFactory newInstance() 

Source Link

Document

Obtain a new instance of a SAXParserFactory .

Usage

From source file:org.apache.commons.rdf.impl.sparql.SparqlClient.java

List<Map<String, RdfTerm>> queryResultSet(final String query) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(endpoint);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("query", query));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);

    try {/*from w  ww.j av a  2s  .  c  o  m*/
        HttpEntity entity2 = response2.getEntity();
        InputStream in = entity2.getContent();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler();
        xmlReader.setContentHandler(sparqlsResultsHandler);
        xmlReader.parse(new InputSource(in));
        /*
         for (int ch = in.read(); ch != -1; ch = in.read()) {
         System.out.print((char)ch);
         }
         */
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
        return sparqlsResultsHandler.getResults();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException ex) {
        throw new RuntimeException(ex);
    } finally {
        response2.close();
    }

}

From source file:org.sansdemeure.zenindex.indexer.odt.TestHTMLConverter2.java

@Test
public void test() throws ParserConfigurationException, SAXException, IOException {
    TestAppender testAppender = new TestAppender();
    File testDir = FileUtil.prepareEmptyDirectory(TestHTMLConverter2.class);
    FileUtil.copyFromResources("docs/2016/2016_05_17_DZP.odt", testDir, "2016_05_17_DZP.odt");
    File odt = new File(testDir, "2016_05_17_DZP.odt");
    try (ODTResource odtRessource = new ODTResource(odt)) {
        InputStream in = odtRessource.openContentXML();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        WriterForTest wt = new WriterForTest();
        OdtHTMLConverterHandler htmlConverter = new OdtHTMLConverterHandler();
        saxParser.parse(in, htmlConverter);
        Map<String, Object> model = htmlConverter.getModel();
        String content = (String) model.get("content");
        Assert.assertTrue(content.contains("Il y a beaucoup de"));
        Assert.assertTrue(content.contains("Les dents se touchent"));
    }//  w  w w.  j av a2  s  .c  o m

}

From source file:com.sshtools.common.mru.MRUList.java

/**
 *
 *
 * @param in/*ww  w  .  j a va 2  s  .c o m*/
 *
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws IOException
 */
public void reload(InputStream in) throws SAXException, ParserConfigurationException, IOException {
    try {
        SAXParserFactory saxFactory = SAXParserFactory.newInstance();
        SAXParser saxParser = saxFactory.newSAXParser();
        saxParser.parse(in, new MRUSAXHandler());
    } catch (Throwable e) {
        System.out.println("MRUList.reload: Exception loading most-recently-used list.");
        e.printStackTrace();
    }
}

From source file:com.vionto.vithesaurus.wikipedia.WiktionarySynonymDumper.java

private void run(InputStream is) throws IOException, SAXException, ParserConfigurationException {
    WiktionaryPageHandler handler = new WiktionaryPageHandler();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    saxParser.getXMLReader().setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",
            false);//from  w  w w . ja  v a 2 s .co m
    System.out.println("SET NAMES utf8;");
    System.out.println("DROP TABLE IF EXISTS wiktionary;");
    System.out.println("CREATE TABLE `wiktionary` ( " + "`headword` varchar(255) NOT NULL default '', "
            + "`meanings` text, " + "`synonyms` text, " + "KEY `headword` (`headword`)" + ") ENGINE = MYISAM;");
    saxParser.parse(is, handler);
    System.err.println("Exported: " + handler.exported);
    System.err.println("Skipped: " + handler.skipped);
}

From source file:com.aurel.track.admin.customize.category.filter.tree.io.TreeFilterParser.java

private void parse(String xml) {
    //get a factory
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {/*from ww w.java 2  s. co m*/
        //get a new instance of parser
        SAXParser sp = spf.newSAXParser();
        //parse the file and also register this class for call backs
        InputSource is = new InputSource(new StringReader(xml));
        sp.parse(is, this);
    } catch (SAXException se) {
        LOGGER.warn("Parsing expression: " + xml + " failed with " + se.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(se));
        }
    } catch (ParserConfigurationException pce) {
        LOGGER.warn("Parsing expression: " + xml + " failed with " + pce.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(pce));
        }
    } catch (IOException ie) {
        LOGGER.warn("Reading expression: " + xml + " failed with " + ie.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(ie));
    }
}

From source file:info.unyttig.helladroid.newzbin.NewzBinController.java

/**
 * Fetches a report from Newzbin based on a given id.
 * However if the report is already cached, its just fetched from the hashmap.
 * @param id//from www  . j av a  2s. c o  m
 */
public static NewzBinReport getReportInfo(int id) {
    if (detailedReports.containsKey(id))
        return detailedReports.get(id);

    String url = NBAPIURL + "reportinfo/";
    HashMap<String, String> searchOptions = new HashMap<String, String>();
    searchOptions.put("id", "" + id);
    try {
        HttpResponse response = doPost(url, searchOptions);
        checkReturnCode(response.getStatusLine().getStatusCode(), false);
        InputStream is = response.getEntity().getContent();

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        NewzBinDRHandler handler = new NewzBinDRHandler();
        if (reports.containsKey(id))
            handler.nbdr = reports.get(id);
        xr.setContentHandler(handler);
        xr.parse(new InputSource(is));
        detailedReports.put(id, handler.getParsedData());
        // Temp
        ArrayList<NewzBinReportComment> comments = handler.nbdr.getComments();
        Log.i(LOG_NAME, "Comments size: " + comments.size());
        Iterator<NewzBinReportComment> sd = comments.iterator();
        while (sd.hasNext()) {
            NewzBinReportComment nrc = sd.next();
            Log.i(LOG_NAME, nrc.toString());
        }
        return handler.getParsedData();
    } catch (ClientProtocolException e) {
        Log.e(LOG_NAME, "ClientProtocol thrown: ", e);
    } catch (IOException e) {
        Log.e(LOG_NAME, "IOException thrown: ", e);
    } catch (NewzBinPostReturnCodeException e) {
        Log.e(LOG_NAME, "POST ReturnCode error: " + e.toString());
    } catch (ParserConfigurationException e) {
        Log.e(LOG_NAME, "ParserError thrown: ", e);
    } catch (SAXException e) {
        Log.e(LOG_NAME, "SAXError thrown: ", e);
    }
    return null;
}

From source file:com.onehippo.gogreen.importer.NonWorkflowWikiImporterComponent.java

@Override
public void doAction(HstRequest request, HstResponse response) throws HstComponentException {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser;/* www .j a  v  a2 s . com*/
    String numberStr = request.getParameter("number");
    int numberOfWikiDocs;
    try {
        numberOfWikiDocs = Integer.parseInt(numberStr);
    } catch (NumberFormatException e) {
        response.setRenderParameter("message", "number must be a number but was '" + numberStr + "'");
        return;
    }

    if (numberOfWikiDocs <= 0) {
        response.setRenderParameter("message",
                "number must be a number larger than 0 but was '" + numberStr + "'");
        return;
    }

    String offsetStr = request.getParameter("offset");
    int offset = 0;
    if (StringUtils.isNotBlank(offsetStr)) {
        try {
            offset = Integer.parseInt(offsetStr);
            if (offset < 0) {
                offset = 0;
            }
        } catch (NumberFormatException e) {
            offset = 0;
        }
    }

    String wikiContentFileSystem = request.getParameter("filesystemLocation");

    if (StringUtils.isEmpty(wikiContentFileSystem)) {
        throw new IllegalArgumentException("filesystemLocation should be correct");
    }

    String type = request.getParameter("type");
    if (type == null || !(type.equals("news") || type.equals("products"))) {
        response.setRenderParameter("message",
                "Invalid type. Must be 'news' or 'products' but was '" + type + "'");
        throw new IllegalArgumentException("type should be set");
    }

    try {
        parser = factory.newSAXParser();
        File f = new File(wikiContentFileSystem);
        WikiPediaToJCRHandler handler = null;
        long start = System.currentTimeMillis();
        try {

            Session writableSession = this.getPersistableSession(request);
            Node baseNode = writableSession
                    .getNode(request.getRequestContext().getSiteContentBaseBean().getPath());

            Node wikiFolder;

            if (!baseNode.hasNode(type)) {
                wikiFolder = baseNode.addNode(type, "hippostd:folder");
                wikiFolder.addMixin("mix:referenceable");
            } else {
                wikiFolder = baseNode.getNode(type);
            }
            handler = new WikiPediaToJCRHandler(wikiFolder, numberOfWikiDocs, offset, type);
            parser.parse(f, handler);

        } catch (ForcedStopException e) {
            // succesfull handler quits after numberOfWikiDocs has been achieved
        } catch (Exception e) {
            log.warn("Exception during importing wikipedia docs", e);
            response.setRenderParameter("message",
                    "An exception happened. Did not import wiki docs. " + e.toString());
        }
        response.setRenderParameter("message", "Successfully imported '" + handler.count
                + "' wikipedia documents in '" + (System.currentTimeMillis() - start) + "' ms.");
    } catch (ParserConfigurationException | SAXException e) {
        response.setRenderParameter("message", "Did not import wiki: " + e.toString());
    }

}

From source file:com.bluecloud.ioc.parse.KernelXMLParser.java

public CompositeMetadata parse() throws KernelXMLParserException {
    KernelXMLParserHandler parserHandler = new KernelXMLParserHandler();
    if (validatedXML != null) {
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        try {/*from  www  . ja  v  a2 s .co m*/
            SAXParser parser = parserFactory.newSAXParser();
            for (URL url : validatedXML) {
                InputStream is = url.openStream();
                parser.parse(is, parserHandler);
                is.close();
            }
        } catch (Exception e) {
            throw new KernelXMLParserException(e);
        }
    }
    return parserHandler.getCompositeMetadata();
}

From source file:com.chitek.util.XMLConfigParser.java

/**
 * Parses the given XML and uses reflection to apply the configuration.<br />
 * 'setting' uses the set... methods in the configuration for all found settings.
 *  Supported types are boolean, int and String.<br />
 * 'config' creates a new instance of the given type and uses the add... method
 * in the configuration class to add new elements. The type of the new class is
 * determined by the parameter type of the add... method. 
 * //from   www.ja  v  a  2s  .c  o  m
 * @param clazz
 *            The Class to return
 * @param typeName
 *            The name of the XML-Element with the configuration
 * @param configXML
 *            The XML configuration to parse
 * @return A new instance of clazz
 * @throws Exception
 */
public Object parseXML(Class<?> clazz, String typeName, String configXML) throws Exception {
    Object config = clazz.newInstance();

    try {
        XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
        reader.setContentHandler(new ContentHandler(config, typeName));
        reader.parse(new InputSource(new StringReader(configXML)));
    } catch (Exception e) {
        throw e;
    }
    return config;
}

From source file:net.sf.jabref.importer.fileformat.BibTeXMLImporter.java

@Override
public ParserResult importDatabase(BufferedReader reader) throws IOException {
    Objects.requireNonNull(reader);

    List<BibEntry> bibItems = new ArrayList<>();

    // Obtain a factory object for creating SAX parsers
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    // Configure the factory object to specify attributes of the parsers it
    // creates//from w w  w . j  a va2  s .  c  o  m
    // parserFactory.setValidating(true);
    parserFactory.setNamespaceAware(true);
    // Now create a SAXParser object

    try {
        SAXParser parser = parserFactory.newSAXParser(); //May throw exceptions
        BibTeXMLHandler handler = new BibTeXMLHandler();
        // Start the parser. It reads the file and calls methods of the handler.
        parser.parse(new InputSource(reader), handler);
        // When you're done, report the results stored by your handler object
        bibItems.addAll(handler.getItems());

    } catch (javax.xml.parsers.ParserConfigurationException e) {
        LOGGER.error("Error with XML parser configuration", e);
        return ParserResult.fromErrorMessage(e.getLocalizedMessage());
    } catch (org.xml.sax.SAXException e) {
        LOGGER.error("Error during XML parsing", e);
        return ParserResult.fromErrorMessage(e.getLocalizedMessage());
    } catch (IOException e) {
        LOGGER.error("Error during file import", e);
        return ParserResult.fromErrorMessage(e.getLocalizedMessage());
    }
    return new ParserResult(bibItems);
}