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.apache.axis.encoding.DeserializationContext.java

/**
 * Create a parser and parse the inputSource
 *//*from  ww  w  .jav a 2s .c o m*/
public void parse() throws SAXException {
    if (inputSource != null) {
        SAXParser parser = XMLUtils.getSAXParser();
        try {
            parser.setProperty("http://xml.org/sax/properties/lexical-handler", this);
            parser.parse(inputSource, this);

            try {
                // cleanup - so that the parser can be reused.
                parser.setProperty("http://xml.org/sax/properties/lexical-handler", nullLexicalHandler);
            } catch (Exception e) {
                // Ignore.
            }

            // only release the parser for reuse if there wasn't an
            // error.  While parsers should be reusable, don't trust
            // parsers that died to clean up appropriately.
            XMLUtils.releaseSAXParser(parser);
        } catch (IOException e) {
            throw new SAXException(e);
        }
        inputSource = null;
    }
}

From source file:org.apache.flex.compiler.internal.config.FileConfigurator.java

/**
 * Load configuration XML file into a {@link ConfigurationBuffer} object.
 * /*from w ww.  j a  v  a  2s .  c o m*/
 * @param buffer result {@link ConfigurationBuffer} object.
 * @param fileSpec configuration XML file.
 * @param context path context used for resolving relative paths in the
 * configuration options.
 * @param rootElement expected root element of the XML DOM tree.
 * @param ignoreUnknownItems if false, unknown option will cause exception.
 * @throws ConfigurationException error.
 */
public static void load(final ConfigurationBuffer buffer, final IFileSpecification fileSpec,
        final String context, final String rootElement, boolean ignoreUnknownItems)
        throws ConfigurationException {
    final String path = fileSpec.getPath();
    final Handler h = new Handler(buffer, path, context, rootElement, ignoreUnknownItems);
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    Reader reader = null;
    try {
        reader = fileSpec.createReader();
        final SAXParser parser = factory.newSAXParser();
        final InputSource source = new InputSource(reader);
        parser.parse(source, h);
    } catch (SAXConfigurationException e) {
        throw e.innerException;
    } catch (SAXParseException e) {
        throw new ConfigurationException.OtherThrowable(e, null, path, e.getLineNumber());
    } catch (Exception e) {
        throw new ConfigurationException.OtherThrowable(e, null, path, -1);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:org.apache.fop.accessibility.AccessibilityPreprocessor.java

/** {@inheritDoc} */
public void endDocument() throws SAXException {
    super.endDocument();
    // do the second transform to struct
    try {//from  w  w  w  . java2s  .  com
        //TODO this must be optimized, no buffering (ex. SAX-based tee-proxy)
        byte[] enrichedFO = enrichedFOBuffer.toByteArray();
        Source src = new StreamSource(new ByteArrayInputStream(enrichedFO));
        DOMResult res = new DOMResult();
        reduceFOTree.transform(src, res);
        StructureTree structureTree = new StructureTree();
        NodeList pageSequences = res.getNode().getFirstChild().getChildNodes();
        for (int i = 0; i < pageSequences.getLength(); i++) {
            structureTree.addPageSequenceStructure(pageSequences.item(i).getChildNodes());
        }
        userAgent.setStructureTree(structureTree);

        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(true);
        saxParserFactory.setValidating(false);
        SAXParser saxParser = saxParserFactory.newSAXParser();
        InputStream in = new ByteArrayInputStream(enrichedFO);
        saxParser.parse(in, fopHandler);
    } catch (Exception e) {
        throw new SAXException(e);
    }
}

From source file:org.apache.fop.complexscripts.fonts.ttx.TTXFile.java

public void parse(File f) {
    assert f != null;
    try {//from  w w  w .jav a2s .c o  m
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        sp.parse(f, new Handler());
    } catch (FactoryConfigurationError e) {
        throw new RuntimeException(e.getMessage());
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e.getMessage());
    } catch (SAXException e) {
        throw new RuntimeException(e.getMessage());
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }
}

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/* w w  w  .  j  a v a 2  s . com*/
 *
 */
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
 *///  ww  w. j a v  a2s .  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  w  ww  .  j  a  va 2s. c  om
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.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  ww.j  a  v  a  2  s  .  co  m*/
@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.myfaces.test.AbstractClassElementTestCase.java

protected void setUp() throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);/*from   w  w  w.  j av  a  2s .co  m*/
    factory.setNamespaceAware(false);

    SAXParser parser = factory.newSAXParser();
    ClassElementHandler handler = new DelegateEntityResolver();

    Iterator iterator = resource.iterator();

    while (iterator.hasNext()) {

        String resourceName = (String) iterator.next();

        InputStream is = getClass().getClassLoader().getResourceAsStream(resourceName);

        if (is == null)
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName);

        if (is == null)
            throw new Exception("Could not locate resource :" + resourceName);

        parser.parse(is, handler);

    }

    className.addAll(handler.getClassName());

}