Example usage for javax.xml.parsers SAXParserFactory newSAXParser

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

Introduction

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

Prototype


public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;

Source Link

Document

Creates a new instance of a SAXParser using the currently configured factory parameters.

Usage

From source file:com.npower.cp.xmlinventory.OTAInventoryImpl.java

/**
 * Create Digester to parsing Template index file.
 * @return/*  www . ja  v  a 2  s . c  om*/
 * @throws SAXException 
 * @throws ParserConfigurationException 
 */
private Digester createDigester() throws ParserConfigurationException, SAXException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    //spf.setNamespaceAware(true);
    //spf.setXIncludeAware(true);

    // Initialize the digester
    Digester currentDigester = new Digester(spf.newSAXParser());
    currentDigester.setValidating(false);

    // Parsing template
    currentDigester.addSetProperties("ota-templates/import", "filename", "include");

    // Parsing manufacturer
    currentDigester.addObjectCreate("ota-templates/manufacturer", ManufacturerItem.class);
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/id", "ID");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/name", "name");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/description", "description");
    currentDigester.addSetNext("ota-templates/manufacturer", "add");

    // Parsing model
    currentDigester.addObjectCreate("ota-templates/manufacturer/model", ModelItem.class);
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/id", "ID");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/name", "name");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/description", "description");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/compatible", "compatible");
    currentDigester.addSetNext("ota-templates/manufacturer/model", "addModel");

    // Parsing template
    currentDigester.addObjectCreate("ota-templates/manufacturer/model/template", OTATemplateItem.class);
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/template/id", "externalID");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/template/name", "name");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/template/description",
            "description");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/template/content", "contentString");
    currentDigester.addBeanPropertySetter("ota-templates/manufacturer/model/template/category",
            "categoryByName");
    currentDigester.addSetProperties("ota-templates/manufacturer/model/template/content", "filename",
            "filename");
    currentDigester.addSetNext("ota-templates/manufacturer/model/template", "addTemplate");

    return currentDigester;
}

From source file:com.dgwave.osrs.OsrsClient.java

private void initJaxb() throws OsrsException {
    if (jc != null && oj != null)
        return;//ww w .  j ava  2 s . c o  m
    try {
        this.jc = JAXBContext.newInstance("com.dgwave.osrs.jaxb");
        this.oj = new ObjectFactory();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        spf.setNamespaceAware(true);
        spf.setValidating(false);
        xmlReader = spf.newSAXParser().getXMLReader();
        xmlReader.setEntityResolver(new EntityResolver() {
            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                logger.debug("Ignoring DTD");
                return new InputSource(new StringReader(""));
            }
        });
    } catch (Exception e) {
        throw new OsrsException("JAXB Error", e);
    }
}

From source file:se.lu.nateko.edca.svc.DescribeFeatureType.java

/**
 * Parses an XML response from a DescribeFeatureType request and stores the layer
 * attribute names and their data types in a GeographyLayer object.
 * @param xmlResponse A reader wrapped around an InputStream containing the XML response from a DescribeFeatureType request.
 *///  w  w  w . j  ava  2 s  . co  m
protected boolean parseXMLResponse(Reader xmlResponse) {
    //      Log.d(TAG, "parseXMLResponse(Reader) called.");

    try {
        SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Make a SAXParser factory.
        spfactory.setValidating(false); // Tell the factory not to make validating parsers.
        SAXParser saxParser = spfactory.newSAXParser(); // Use the factory to make a SAXParser.
        XMLReader xmlReader = saxParser.getXMLReader(); // Get an XML reader from the parser, which will send event calls to its specified event handler.
        XMLEventHandler xmlEventHandler = new XMLEventHandler();
        xmlReader.setContentHandler(xmlEventHandler); // Set which event handler to use.
        xmlReader.setErrorHandler(xmlEventHandler); // Also set where to send error calls.
        InputSource source = new InputSource(xmlResponse); // Make an InputSource from the XML input to give to the reader.
        xmlReader.parse(source); // Start parsing the XML.
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        return false;
    }
    return true;
}

From source file:edu.psu.citeseerx.updates.external.metadata.DBLPMetadataUpdater.java

public void updateDBLP() {
    try {//  w  w w  . j  av  a 2 s.  c o  m
        // Get the SAX factory.
        SAXParserFactory factory = SAXParserFactory.newInstance();

        // Neither we want validation nor namespaces.
        factory.setNamespaceAware(false);
        factory.setValidating(true);

        SAXParser parser = factory.newSAXParser();
        parser.getXMLReader().setEntityResolver(new DBLPEntityResolver(DBLPDTDFile));

        /*xmlReader.setFeature(
            "http://apache.org/xml/features/nonvalidating/load-external-dtd", 
            false);*/

        parser.parse(DBLPDataFile, dblpHandler);
    } catch (ParserConfigurationException e) {
        logger.error("The underlaying parser doesn't support the " + "requested feature", e);
    } catch (SAXException e) {
        logger.error("Error", e);
    } catch (IOException e) {
        logger.error("A parsing error has occurred: " + DBLPDataFile, e);
    }

}

From source file:eionet.gdem.conversion.spreadsheet.DDXMLConverter.java

/**
 * Converts XML file/* w ww. j a  va  2  s.c  om*/
 * @param xmlSchema XML schema
 * @param outStream OutputStream
 * @throws Exception If an error occurs.
 */
protected void doConversion(String xmlSchema, OutputStream outStream) throws Exception {
    String instanceUrl = DataDictUtil.getInstanceUrl(xmlSchema);

    DD_XMLInstance instance = new DD_XMLInstance(instanceUrl);
    DD_XMLInstanceHandler handler = new DD_XMLInstanceHandler(instance);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    XMLReader reader = parser.getXMLReader();

    factory.setValidating(false);
    factory.setNamespaceAware(true);
    reader.setFeature("http://xml.org/sax/features/validation", false);
    reader.setFeature("http://apache.org/xml/features/validation/schema", false);
    reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    reader.setFeature("http://xml.org/sax/features/namespaces", true);

    reader.setContentHandler(handler);
    reader.parse(instanceUrl);

    if (Utils.isNullStr(instance.getEncoding())) {
        String enc_url = Utils.getEncodingFromStream(instanceUrl);
        if (!Utils.isNullStr(enc_url)) {
            instance.setEncoding(enc_url);
        }
    }
    importSheetSchemas(sourcefile, instance, xmlSchema);
    instance.startWritingXml(outStream);
    sourcefile.writeContentToInstance(instance);
    instance.flushXml();
}

From source file:com.wooki.test.unit.ConversionsTest.java

@Test(enabled = true)
public void docbookConversion() {
    String result = "<book>     <bookinfo>       <title>An Example Book</title>              <author>         <firstname>Your first name</firstname>         <surname>Your surname</surname>         <affiliation>           <address><email>foo@example.com</email></address>         </affiliation>       </author>          <copyright>         <year>2000</year>         <holder>Copyright string here</holder>       </copyright>          <abstract>         <para>If your book has an abstract then it should go here.</para>       </abstract>     </bookinfo>        <preface>       <title>Preface</title>          <para>Your book may have a preface, in which case it should be placed         here.</para>     </preface>              <chapter>       <title>My First Chapter</title>          <para>This is the first chapter in my book.</para>          <sect1>         <title>My First Section</title>            <para>This is the first section in my book.</para>       </sect1>     </chapter>   </book>";
    Resource resource = new ByteArrayResource(result.getBytes());
    InputStream xhtml = fromDocbookConvertor.performTransformation(resource);
    File htmlFile = null;/*from w  w  w .j a v a 2  s.  co m*/
    try {
        htmlFile = File.createTempFile("wooki", ".html");
        FileOutputStream fos = new FileOutputStream(htmlFile);
        logger.debug("HTML File is " + htmlFile.getAbsolutePath());
        byte[] content = null;
        int available = 0;
        while ((available = xhtml.available()) > 0) {
            content = new byte[available];
            xhtml.read(content);
            fos.write(content);
        }
        fos.flush();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
        logger.error(e.getLocalizedMessage());
        return;
    }
    logger.debug("Docbook to xhtml ok");
    SAXParserFactory factory = SAXParserFactory.newInstance();

    // cration d'un parseur SAX
    SAXParser parser;
    try {
        parser = factory.newSAXParser();
        parser.parse(new InputSource(new FileInputStream(htmlFile)), htmlParser);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        logger.error(e.getLocalizedMessage());
    } catch (SAXException e) {
        e.printStackTrace();
        logger.error(e.getLocalizedMessage());
    } catch (IOException e) {
        e.printStackTrace();
        logger.error(e.getLocalizedMessage());
    }

    Book book = htmlParser.getBook();
    logger.debug("The book title is " + book.getTitle());

}

From source file:cm.aptoide.pt.RemoteInTab.java

private void xmlPass(String srv, boolean type) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {/*from  ww w . j  ava2  s.  c  om*/
        File xml_file = null;
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        if (type) {
            RssHandler handler = new RssHandler(this, srv);
            xr.setContentHandler(handler);
            xml_file = new File(XML_PATH);
        } else {
            ExtrasRssHandler handler = new ExtrasRssHandler(this, srv);
            xr.setContentHandler(handler);
            xml_file = new File(EXTRAS_XML_PATH);
        }

        InputStreamReader isr = new FileReader(xml_file);
        InputSource is = new InputSource(isr);
        xr.parse(is);
        xml_file.delete();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}

From source file:geeshang.nasaimage.MainActivity.java

private void download() {
    new Thread() {
        @Override/*  w  w w.  j av  a  2s.c  o  m*/
        public void run() {
            super.run();
            MyDefaultHandler defaultHandler = new MyDefaultHandler(MainActivity.this);
            try {
                SAXParserFactory factory = SAXParserFactory.newInstance();
                SAXParser parser = factory.newSAXParser();
                InputStream inputStream = downloader.download(NASA_URL);
                if (inputStream != null) {
                    parser.parse(inputStream, defaultHandler);
                }
            } catch (ParserConfigurationException | SAXException | IOException e) {
                e.printStackTrace();
            }
            MainActivity.this.myHandler.post(new Runnable() {
                @Override
                public void run() {
                    resetView();
                }
            });
            getImage();
            setProgressBarGone();
            MainActivity.this.myHandler.post(new Runnable() {
                @Override
                public void run() {
                    resetView();
                }
            });
        }
    }.start();
}

From source file:com.typhoon.newsreader.engine.ChannelRefresh.java

public List<FeedsListItem> parser(String link) {
    if (link.contains("www.24h.com.vn")) {
        try {/* w ww  . j  a v a2 s. c o  m*/
            URL url = new URL(link);
            URLConnection connection = url.openConnection();
            connection.addRequestProperty("http.agent", USER_AGENT);
            InputSource input = new InputSource(url.openStream());
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.setValidating(false);
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            reader.setContentHandler(this);
            reader.parse(input);

            return getFeedsList();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    } else {
        try {
            // URL url= new URL(link);
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(link);
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.setValidating(false);
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();
            reader.setContentHandler(this);
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(EntityUtils.toString(entity)));
            reader.parse(inStream);
            return getFeedsList();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            return null;
        } catch (SAXException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

From source file:com.aionengine.gameserver.dataholders.loadingutils.XmlMerger.java

/**
 * Check for modifications of included files.
 *
 * @return <code>true</code> if at least one of included files has modifications.
 * @throws IOException                  IO Error.
 * @throws SAXException                 Document parsing error.
 * @throws ParserConfigurationException if a SAX parser cannot
 *                                      be created which satisfies the requested configuration.
 *//*from ww  w.  j  a  v a  2 s  .com*/
private boolean checkFileModifications() throws Exception {
    long destFileTime = destFile.lastModified();

    if (sourceFile.lastModified() > destFileTime) {
        logger.debug("Source file was modified ");
        return true;
    }

    Properties metadata = restoreFileModifications(metaDataFile);

    if (metadata == null) // new file or smth else.
        return true;

    SAXParserFactory parserFactory = SAXParserFactory.newInstance();

    SAXParser parser = parserFactory.newSAXParser();

    TimeCheckerHandler handler = new TimeCheckerHandler(baseDir, metadata);

    parser.parse(sourceFile, handler);

    return handler.isModified();
}