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:org.apache.jackrabbit.jcr2spi.SessionImpl.java

/**
 * @see javax.jcr.Session#importXML(String, java.io.InputStream, int)
 *//*from   ww w  . java2s  .  c o  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.jmeter.protocol.http.proxy.DefaultSamplerCreatorClassifier.java

/**
 * Tries parsing to see if content is xml
 * //from   www .  j a va 2  s  . c  om
 * @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;
    }
}

From source file:org.apache.maven.plugin.cxx.utils.svn.SvnService.java

public static SvnInfo getSvnInfo(File basedir, Credential cred, String uri, Log log, boolean noParsingFailure)
        throws MojoExecutionException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    execSvnCommand(basedir, cred, new String[] { "info", uri, "--xml" }, out, log);

    SvnInfo svnInfo = new SvnInfo();
    try {/*from  www  . j a va 2 s .c o  m*/
        SAXParserFactory sfactory = SAXParserFactory.newInstance();
        SAXParser parser = sfactory.newSAXParser();
        XMLReader xmlparser = parser.getXMLReader();
        xmlparser.setContentHandler(svnInfo);
        xmlparser.parse(new InputSource(new ByteArrayInputStream(out.toByteArray())));
    } catch (Exception e) {
        if (noParsingFailure) {
            log.error("svn info xml parsing failed : " + e);
        } else {
            throw new MojoExecutionException("svn info xml parsing failed.", e);
        }
    }
    return svnInfo;
}

From source file:org.apache.myfaces.custom.skin.config.ConfigParser.java

/**
 *
 *//*from  www.  j av a 2  s  . com*/
static public RequestContextBean parseConfigFile(ExternalContext externalContext) {
    RequestContextBean bean = new RequestContextBean();

    InputStream in = externalContext.getResourceAsStream(_SKINS_CONFIG_FILE);
    if (in == null) {
        in = externalContext.getResourceAsStream(_TRINIDAD_CONFIG_FILE);
    }

    if (in != null) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);

            Digester digester = new Digester(factory.newSAXParser());
            digester.setValidating(false);
            digester.setNamespaceAware(true);
            digester.setUseContextClassLoader(true);
            RequestContextBean.addXmlRules(digester);

            InputSource input = new InputSource();
            input.setByteStream(in);
            input.setPublicId(_SKINS_CONFIG_FILE);
            digester.parse(input);
            bean = (RequestContextBean) digester.getRoot();
        } catch (IOException ioe) {
            _LOG.warning(ioe);
        } catch (ParserConfigurationException pce) {
            _LOG.warning(pce);
        } catch (SAXException saxe) {
            _LOG.warning(saxe);
        } finally {
            try {
                in.close();
            } catch (IOException ioe) {
                // Ignore
                ;
            }
        }
    }

    return bean;
}

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  .  ja v  a2 s  . c  o 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());

}

From source file:org.apache.myfaces.trinidadbuild.plugin.faces.AbstractFacesMojo.java

protected URL[] readIndex(MavenProject project) throws MojoExecutionException {
    try {/* www  .ja v  a2  s .  co  m*/
        // 1. read master faces-config.xml resources
        List masters = getMasterConfigs(project);
        if (masters.isEmpty()) {
            getLog().warn("Master faces-config.xml not found");
            return new URL[0];
        } else {
            List entries = new LinkedList();

            SAXParserFactory spf = SAXParserFactory.newInstance();
            spf.setNamespaceAware(true);
            // requires JAXP 1.3, in JavaSE 5.0
            // spf.setXIncludeAware(false);

            for (Iterator<URL> i = masters.iterator(); i.hasNext();) {
                URL url = i.next();
                Digester digester = new Digester(spf.newSAXParser());
                digester.setNamespaceAware(true);

                // XInclude
                digester.setRuleNamespaceURI(XIncludeFilter.XINCLUDE_NAMESPACE);
                digester.addCallMethod("faces-config/include", "add", 1);
                digester.addFactoryCreate("faces-config/include", URLCreationFactory.class);
                digester.addCallParam("faces-config/include", 0, 0);

                digester.push(url);
                digester.push(entries);
                digester.parse(url.openStream());
            }

            return (URL[]) entries.toArray(new URL[0]);
        }
    } catch (ParserConfigurationException e) {
        throw new MojoExecutionException("Failed to parse master config", e);
    } catch (SAXException e) {
        throw new MojoExecutionException("Failed to parse master config", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to parse master config", e);
    }
}

From source file:org.apache.myfaces.trinidadbuild.plugin.faces.parse.FacesConfigParser.java

static protected Digester createEmptyDigester() throws ParserConfigurationException, SAXException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);/*from  www.ja  v a2s  .c  om*/
    // requires JAXP 1.3, in JavaSE 5.0
    // spf.setXIncludeAware(true);
    Digester digester = new Digester(spf.newSAXParser());
    digester.setNamespaceAware(true);

    return digester;
}

From source file:org.apache.myfaces.trinidadbuild.plugin.tagdoc.TagdocReport.java

protected URL[] readIndex(MavenProject project) throws MavenReportException {
    try {/*  w  ww . j  av a  2 s .  co m*/
        // 1. read master faces-config.xml resources
        List masters = getMasterConfigs(project);
        if (masters.isEmpty()) {
            getLog().warn("Master faces-config.xml not found");
            return new URL[0];
        } else {
            List entries = new LinkedList();

            SAXParserFactory spf = SAXParserFactory.newInstance();
            spf.setNamespaceAware(true);
            // requires JAXP 1.3, in JavaSE 5.0
            // spf.setXIncludeAware(false);

            for (Iterator<URL> i = masters.iterator(); i.hasNext();) {
                URL url = i.next();
                Digester digester = new Digester(spf.newSAXParser());
                digester.setNamespaceAware(true);

                // XInclude
                digester.setRuleNamespaceURI(XIncludeFilter.XINCLUDE_NAMESPACE);
                digester.addCallMethod("faces-config/include", "add", 1);
                digester.addFactoryCreate("faces-config/include", URLCreationFactory.class);
                digester.addCallParam("faces-config/include", 0, 0);

                digester.push(url);
                digester.push(entries);
                digester.parse(url.openStream());
            }

            return (URL[]) entries.toArray(new URL[0]);
        }
    } catch (ParserConfigurationException e) {
        throw new MavenReportException("Failed to parse master config", e);
    } catch (SAXException e) {
        throw new MavenReportException("Failed to parse master config", e);
    } catch (IOException e) {
        throw new MavenReportException("Failed to parse master config", e);
    }
}

From source file:org.apache.nutch.tools.DmozParser.java

/**
 * Iterate through all the items in this structured DMOZ file.
 * Add each URL to the web db./*w  ww . j ava 2  s  .  c  o  m*/
 */
public void parseDmozFile(File dmozFile, int subsetDenom, boolean includeAdult, int skew, Pattern topicPattern)

        throws IOException, SAXException, ParserConfigurationException {

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

    // Create our own processor to receive SAX events
    RDFProcessor rp = new RDFProcessor(reader, subsetDenom, includeAdult, skew, topicPattern);
    reader.setContentHandler(rp);
    reader.setErrorHandler(rp);
    LOG.info("skew = " + rp.hashSkew);

    //
    // Open filtered text stream.  The TextFilter makes sure that
    // only appropriate XML-approved Text characters are received.
    // Any non-conforming characters are silently skipped.
    //
    XMLCharFilter in = new XMLCharFilter(new BufferedReader(
            new InputStreamReader(new BufferedInputStream(new FileInputStream(dmozFile)), "UTF-8")));
    try {
        InputSource is = new InputSource(in);
        reader.parse(is);
    } catch (Exception e) {
        if (LOG.isFatalEnabled()) {
            LOG.fatal(e.toString());
            e.printStackTrace(LogUtil.getFatalStream(LOG));
        }
        System.exit(0);
    } finally {
        in.close();
    }
}

From source file:org.apache.ojb.broker.metadata.RepositoryPersistor.java

/**
 * Read metadata by populating an instance of the target class
 * using SAXParser.//from w  w w .j a v a 2 s  . c  o  m
 */
private Object readMetadataFromXML(InputSource source, Class target)
        throws MalformedURLException, ParserConfigurationException, SAXException, IOException {
    // TODO: make this configurable
    boolean validate = false;

    // get a xml reader instance:
    SAXParserFactory factory = SAXParserFactory.newInstance();
    log.info("RepositoryPersistor using SAXParserFactory : " + factory.getClass().getName());
    if (validate) {
        factory.setValidating(true);
    }
    SAXParser p = factory.newSAXParser();
    XMLReader reader = p.getXMLReader();
    if (validate) {
        reader.setErrorHandler(new OJBErrorHandler());
    }

    Object result;
    if (DescriptorRepository.class.equals(target)) {
        // create an empty repository:
        DescriptorRepository repository = new DescriptorRepository();
        // create handler for building the repository structure
        ContentHandler handler = new RepositoryXmlHandler(repository);
        // tell parser to use our handler:
        reader.setContentHandler(handler);
        reader.parse(source);
        result = repository;
    } else if (ConnectionRepository.class.equals(target)) {
        // create an empty repository:
        ConnectionRepository repository = new ConnectionRepository();
        // create handler for building the repository structure
        ContentHandler handler = new ConnectionDescriptorXmlHandler(repository);
        // tell parser to use our handler:
        reader.setContentHandler(handler);
        reader.parse(source);
        //LoggerFactory.getBootLogger().info("loading XML took " + (stop - start) + " msecs");
        result = repository;
    } else
        throw new MetadataException(
                "Could not build a repository instance for '" + target + "', using source " + source);
    return result;
}