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.fop.fo.extensions.svg.SVGElementMapping.java

/**
 * Returns the fully qualified classname of an XML parser for
 * Batik classes that apparently need it (error messages, perhaps)
 * @return an XML parser classname//  w  ww. j a va2  s  . c  o m
 */
private String getAParserClassName() {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        return factory.newSAXParser().getXMLReader().getClass().getName();
    } catch (Exception e) {
        return null;
    }
}

From source file:org.apache.fop.fotreetest.FOTreeTestCase.java

/**
 * Runs a test./* w  ww .ja  v  a 2s  .c  o  m*/
 * @throws Exception if a test or FOP itself fails
 */
@Test
public void runTest() throws Exception {
    try {
        ResultCollector collector = ResultCollector.getInstance();
        collector.reset();

        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        spf.setValidating(false);
        SAXParser parser = spf.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        // Resetting values modified by processing instructions
        fopFactory.setBreakIndentInheritanceOnReferenceAreaBoundary(
                FopFactoryConfigurator.DEFAULT_BREAK_INDENT_INHERITANCE);
        fopFactory.setSourceResolution(FopFactoryConfigurator.DEFAULT_SOURCE_RESOLUTION);

        FOUserAgent ua = fopFactory.newFOUserAgent();
        ua.setBaseURL(testFile.getParentFile().toURI().toURL().toString());
        ua.setFOEventHandlerOverride(new DummyFOEventHandler(ua));
        ua.getEventBroadcaster().addEventListener(new ConsoleEventListenerForTests(testFile.getName()));

        // Used to set values in the user agent through processing instructions
        reader = new PIListener(reader, ua);

        Fop fop = fopFactory.newFop(ua);

        reader.setContentHandler(fop.getDefaultHandler());
        reader.setDTDHandler(fop.getDefaultHandler());
        reader.setErrorHandler(fop.getDefaultHandler());
        reader.setEntityResolver(fop.getDefaultHandler());
        try {
            reader.parse(testFile.toURI().toURL().toExternalForm());
        } catch (Exception e) {
            collector.notifyError(e.getLocalizedMessage());
            throw e;
        }

        List<String> results = collector.getResults();
        if (results.size() > 0) {
            for (int i = 0; i < results.size(); i++) {
                System.out.println((String) results.get(i));
            }
            throw new IllegalStateException((String) results.get(0));
        }
    } catch (Exception e) {
        org.apache.commons.logging.LogFactory.getLog(this.getClass()).info("Error on " + testFile.getName());
        throw e;
    }
}

From source file:org.apache.fop.image.loader.batik.PreloaderSVG.java

/**
 * Returns the fully qualified classname of an XML parser for
 * Batik classes that apparently need it (error messages, perhaps)
 * @return an XML parser classname/*from  w  w w .jav a 2  s .com*/
 */
public static String getParserName() {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        return factory.newSAXParser().getXMLReader().getClass().getName();
    } catch (Exception e) {
        return null;
    }
}

From source file:org.apache.geode.internal.cache.xmlcache.CacheXmlParser.java

/**
 * Parses XML data and from it creates an instance of <code>CacheXmlParser</code> that can be used
 * to {@link #create}the {@link Cache}, etc.
 *
 * @param is the <code>InputStream</code> of XML to be parsed
 *
 * @return a <code>CacheXmlParser</code>, typically used to create a cache from the parsed XML
 *
 * @throws CacheXmlException Something went wrong while parsing the XML
 *
 * @since GemFire 4.0//  www .  j ava  2  s  .  c  o m
 *
 */
public static CacheXmlParser parse(InputStream is) {

    /**
     * The API doc http://java.sun.com/javase/6/docs/api/org/xml/sax/InputSource.html for the SAX
     * InputSource says: "... standard processing of both byte and character streams is to close
     * them on as part of end-of-parse cleanup, so applications should not attempt to re-use such
     * streams after they have been handed to a parser."
     *
     * In order to block the parser from closing the stream, we wrap the InputStream in a filter,
     * i.e., UnclosableInputStream, whose close() function does nothing.
     * 
     */
    class UnclosableInputStream extends BufferedInputStream {
        public UnclosableInputStream(InputStream stream) {
            super(stream);
        }

        @Override
        public void close() {
        }
    }

    CacheXmlParser handler = new CacheXmlParser();
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setFeature(DISALLOW_DOCTYPE_DECL_FEATURE, true);
        factory.setValidating(true);
        factory.setNamespaceAware(true);
        UnclosableInputStream bis = new UnclosableInputStream(is);
        try {
            SAXParser parser = factory.newSAXParser();
            // Parser always reads one buffer plus a little extra worth before
            // determining that the DTD is there. Setting mark twice the parser
            // buffer size.
            bis.mark((Integer) parser.getProperty(BUFFER_SIZE) * 2);
            parser.setProperty(JAXP_SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
            parser.parse(bis, new DefaultHandlerDelegate(handler));
        } catch (CacheXmlException e) {
            if (null != e.getCause() && e.getCause().getMessage().contains(DISALLOW_DOCTYPE_DECL_FEATURE)) {
                // Not schema based document, try dtd.
                bis.reset();
                factory.setFeature(DISALLOW_DOCTYPE_DECL_FEATURE, false);
                SAXParser parser = factory.newSAXParser();
                parser.parse(bis, new DefaultHandlerDelegate(handler));
            } else {
                throw e;
            }
        }
        return handler;
    } catch (Exception ex) {
        if (ex instanceof CacheXmlException) {
            while (true /* ex instanceof CacheXmlException */) {
                Throwable cause = ex.getCause();
                if (!(cause instanceof CacheXmlException)) {
                    break;
                } else {
                    ex = (CacheXmlException) cause;
                }
            }
            throw (CacheXmlException) ex;
        } else if (ex instanceof SAXException) {
            // Silly JDK 1.4.2 XML parser wraps RunTime exceptions in a
            // SAXException. Pshaw!
            SAXException sax = (SAXException) ex;
            Exception cause = sax.getException();
            if (cause instanceof CacheXmlException) {
                while (true /* cause instanceof CacheXmlException */) {
                    Throwable cause2 = cause.getCause();
                    if (!(cause2 instanceof CacheXmlException)) {
                        break;
                    } else {
                        cause = (CacheXmlException) cause2;
                    }
                }
                throw (CacheXmlException) cause;
            }
        }
        throw new CacheXmlException(LocalizedStrings.CacheXmlParser_WHILE_PARSING_XML.toLocalizedString(), ex);
    }
}

From source file:org.apache.hadoop.cli.CLITestHelper.java

/**
 * Read the test config file - testConf.xml
 *///from ww  w  .  j a  v  a 2  s.c om
protected void readTestConfigFile() {
    String testConfigFile = getTestFile();
    if (testsFromConfigFile == null) {
        boolean success = false;
        testConfigFile = TEST_CACHE_DATA_DIR + File.separator + testConfigFile;
        try {
            SAXParser p = (SAXParserFactory.newInstance()).newSAXParser();
            p.parse(testConfigFile, getConfigParser());
            success = true;
        } catch (Exception e) {
            LOG.info("File: " + testConfigFile + " not found");
            success = false;
        }
        assertTrue("Error reading test config file", success);
    }
}

From source file:org.apache.hadoop.cli.TestCLI.java

/**
 * Read the test config file - testConfig.xml
 *//*from  www  .  j a  v  a  2s  . c o  m*/
private void readTestConfigFile() {

    if (testsFromConfigFile == null) {
        boolean success = false;
        testConfigFile = TEST_CACHE_DATA_DIR + File.separator + testConfigFile;
        try {
            SAXParser p = (SAXParserFactory.newInstance()).newSAXParser();
            p.parse(testConfigFile, new TestConfigFileParser());
            success = true;
        } catch (Exception e) {
            LOG.info("File: " + testConfigFile + " not found");
            success = false;
        }
        assertTrue("Error reading test config file", success);
    }
}

From source file:org.apache.hadoop.hbase.rest.TestTableScan.java

/**
 * An example to scan using listener in unmarshaller for XML.
 * @throws Exception the exception//  w  w  w.ja  va2 s.co m
 */
@Test
public void testScanUsingListenerUnmarshallerXML() throws Exception {
    StringBuilder builder = new StringBuilder();
    builder.append("/*");
    builder.append("?");
    builder.append(Constants.SCAN_COLUMN + "=" + COLUMN_1);
    builder.append("&");
    builder.append(Constants.SCAN_LIMIT + "=10");
    Response response = client.get("/" + TABLE + builder.toString(), Constants.MIMETYPE_XML);
    assertEquals(200, response.getCode());
    assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
    JAXBContext context = JAXBContext.newInstance(ClientSideCellSetModel.class, RowModel.class,
            CellModel.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();

    final ClientSideCellSetModel.Listener listener = new ClientSideCellSetModel.Listener() {
        @Override
        public void handleRowModel(ClientSideCellSetModel helper, RowModel row) {
            assertTrue(row.getKey() != null);
            assertTrue(row.getCells().size() > 0);
        }
    };

    // install the callback on all ClientSideCellSetModel instances
    unmarshaller.setListener(new Unmarshaller.Listener() {
        public void beforeUnmarshal(Object target, Object parent) {
            if (target instanceof ClientSideCellSetModel) {
                ((ClientSideCellSetModel) target).setCellSetModelListener(listener);
            }
        }

        public void afterUnmarshal(Object target, Object parent) {
            if (target instanceof ClientSideCellSetModel) {
                ((ClientSideCellSetModel) target).setCellSetModelListener(null);
            }
        }
    });

    // create a new XML parser
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    XMLReader reader = factory.newSAXParser().getXMLReader();
    reader.setContentHandler(unmarshaller.getUnmarshallerHandler());
    assertFalse(ClientSideCellSetModel.listenerInvoked);
    reader.parse(new InputSource(response.getStream()));
    assertTrue(ClientSideCellSetModel.listenerInvoked);

}

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.TestOfflineImageViewerForAcl.java

@Test
public void testPBImageXmlWriterForAcl() throws Exception {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PrintStream o = new PrintStream(output);
    PBImageXmlWriter v = new PBImageXmlWriter(new Configuration(), o);
    v.visit(new RandomAccessFile(originalFsimage, "r"));
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser parser = spf.newSAXParser();
    final String xml = output.toString();
    parser.parse(new InputSource(new StringReader(xml)), new DefaultHandler());
}

From source file:org.apache.jackrabbit.jcr2spi.SessionImpl.java

/**
 * @see javax.jcr.Session#importXML(String, java.io.InputStream, int)
 *//* w w  w.  j  av  a2s . c  om*/
@Override
public void importXML(String parentAbsPath, InputStream in, int uuidBehavior)
        throws IOException, PathNotFoundException, ItemExistsException, ConstraintViolationException,
        VersionException, InvalidSerializedDataException, LockException, RepositoryException {
    // NOTE: checks are performed by 'getImportContentHandler'
    ImportHandler handler = (ImportHandler) getImportContentHandler(parentAbsPath, uuidBehavior);
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setFeature("http://xml.org/sax/features/namespace-prefixes", false);

        SAXParser parser = factory.newSAXParser();
        parser.parse(new InputSource(in), handler);
    } catch (SAXException se) {
        // check for wrapped repository exception
        Exception e = se.getException();
        if (e != null && e instanceof RepositoryException) {
            throw (RepositoryException) e;
        } else {
            String msg = "failed to parse XML stream";
            log.debug(msg);
            throw new InvalidSerializedDataException(msg, se);
        }
    } catch (ParserConfigurationException e) {
        throw new RepositoryException("SAX parser configuration error", e);
    } finally {
        in.close(); // JCR-2903
    }
}

From source file:org.apache.jmeter.protocol.http.proxy.DefaultSamplerCreatorClassifier.java

/**
 * Tries parsing to see if content is xml
 * /*from www  .  j  a va2  s .  c  o m*/
 * @param postData
 *            String
 * @return boolean
 */
private static final boolean isPotentialXml(String postData) {
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser saxParser = spf.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        ErrorDetectionHandler detectionHandler = new ErrorDetectionHandler();
        xmlReader.setContentHandler(detectionHandler);
        xmlReader.setErrorHandler(detectionHandler);
        xmlReader.parse(new InputSource(new StringReader(postData)));
        return !detectionHandler.isErrorDetected();
    } catch (ParserConfigurationException e) {
        return false;
    } catch (SAXException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
}