Example usage for org.xml.sax XMLReader setErrorHandler

List of usage examples for org.xml.sax XMLReader setErrorHandler

Introduction

In this page you can find the example usage for org.xml.sax XMLReader setErrorHandler.

Prototype

public void setErrorHandler(ErrorHandler handler);

Source Link

Document

Allow an application to register an error event handler.

Usage

From source file:org.apache.axis.utils.XMLUtils.java

/** Return a SAX parser for reuse.
 * @param parser A SAX parser that is available for reuse
 *//* www  .  j  a v  a2s  . co m*/
public static void releaseSAXParser(SAXParser parser) {
    if (!tryReset || !enableParserReuse)
        return;

    //Free up possible ref. held by past contenthandler.
    try {
        XMLReader xmlReader = parser.getXMLReader();
        if (null != xmlReader) {
            xmlReader.setContentHandler(doNothingContentHandler);
            xmlReader.setDTDHandler(doNothingContentHandler);
            try {
                xmlReader.setEntityResolver(doNothingContentHandler);
            } catch (Throwable t) {
                log.debug("Failed to set EntityResolver on DocumentBuilder", t);
            }
            try {
                xmlReader.setErrorHandler(doNothingContentHandler);
            } catch (Throwable t) {
                log.debug("Failed to set ErrorHandler on DocumentBuilder", t);
            }

            synchronized (XMLUtils.class) {
                saxParsers.push(parser);
            }
        } else {
            tryReset = false;
        }
    } catch (org.xml.sax.SAXException e) {
        tryReset = false;
    }
}

From source file:org.apache.camel.component.validator.jing.JingValidator.java

public void process(Exchange exchange) throws Exception {
    Jaxp11XMLReaderCreator xmlCreator = new Jaxp11XMLReaderCreator();
    DefaultValidationErrorHandler errorHandler = new DefaultValidationErrorHandler();

    PropertyMapBuilder mapBuilder = new PropertyMapBuilder();
    mapBuilder.put(ValidateProperty.XML_READER_CREATOR, xmlCreator);
    mapBuilder.put(ValidateProperty.ERROR_HANDLER, errorHandler);
    PropertyMap propertyMap = mapBuilder.toPropertyMap();

    Validator validator = getSchema().createValidator(propertyMap);

    Message in = exchange.getIn();/*from   w ww.  j  a  va 2 s  . com*/
    SAXSource saxSource = in.getBody(SAXSource.class);
    if (saxSource == null) {
        Source source = ExchangeHelper.getMandatoryInBody(exchange, Source.class);
        saxSource = ExchangeHelper.convertToMandatoryType(exchange, SAXSource.class, source);
    }
    InputSource bodyInput = saxSource.getInputSource();

    // now lets parse the body using the validator
    XMLReader reader = xmlCreator.createXMLReader();
    reader.setContentHandler(validator.getContentHandler());
    reader.setDTDHandler(validator.getDTDHandler());
    reader.setErrorHandler(errorHandler);
    reader.parse(bodyInput);

    errorHandler.handleErrors(exchange, schema);
}

From source file:org.apache.cayenne.configuration.XMLDataChannelDescriptorLoader.java

@Override
public ConfigurationTree<DataChannelDescriptor> load(Resource configurationResource)
        throws ConfigurationException {

    if (configurationResource == null) {
        throw new NullPointerException("Null configurationResource");
    }//from w w w .j  av a 2  s.c  o  m

    URL configurationURL = configurationResource.getURL();

    logger.info("Loading XML configuration resource from " + configurationURL);

    DataChannelDescriptor descriptor = new DataChannelDescriptor();
    descriptor.setConfigurationSource(configurationResource);
    descriptor.setName(nameMapper.configurationNodeName(DataChannelDescriptor.class, configurationResource));

    DataChannelHandler rootHandler;

    InputStream in = null;

    try {
        in = configurationURL.openStream();
        XMLReader parser = Util.createXmlReader();

        rootHandler = new DataChannelHandler(descriptor, parser);
        parser.setContentHandler(rootHandler);
        parser.setErrorHandler(rootHandler);
        parser.parse(new InputSource(in));
    } catch (Exception e) {
        throw new ConfigurationException("Error loading configuration from %s", e, configurationURL);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ioex) {
            logger.info("failure closing input stream for " + configurationURL + ", ignoring", ioex);
        }
    }

    // TODO: andrus 03/10/2010 - actually provide load failures here...
    return new ConfigurationTree<DataChannelDescriptor>(descriptor, null);
}

From source file:org.apache.cayenne.map.MapLoader.java

/**
 * Loads a DataMap from XML input source.
 *//*  w ww. jav  a 2  s  .c  o  m*/
public synchronized DataMap loadDataMap(InputSource src) throws CayenneRuntimeException {
    if (src == null) {
        throw new NullPointerException("Null InputSource.");
    }

    try {
        String mapName = mapNameFromLocation(src.getSystemId());
        dataMap = new DataMap(mapName);
        XMLReader parser = Util.createXmlReader();

        parser.setContentHandler(this);
        parser.setErrorHandler(this);
        parser.parse(src);
    } catch (SAXException e) {
        dataMap = null;
        throw new CayenneRuntimeException(
                "Wrong DataMap format, last processed tag: " + constructCurrentStateString(),
                Util.unwindException(e));
    } catch (Exception e) {
        dataMap = null;
        throw new CayenneRuntimeException(
                "Error loading DataMap, last processed tag: " + constructCurrentStateString(),
                Util.unwindException(e));
    }
    return dataMap;
}

From source file:org.apache.cayenne.project.upgrade.v6.XMLDataChannelDescriptorLoader_V3_0_0_1.java

List<DataChannelDescriptor> load(Resource configurationSource) throws ConfigurationException {

    if (configurationSource == null) {
        throw new NullPointerException("Null configurationSource");
    }/*  w  ww  .  j  a  v a 2 s .c om*/

    URL configurationURL = configurationSource.getURL();

    List<DataChannelDescriptor> domains = new ArrayList<>();

    try (InputStream in = configurationURL.openStream();) {

        XMLReader parser = Util.createXmlReader();

        DomainsHandler rootHandler = new DomainsHandler(configurationSource, domains, parser);
        parser.setContentHandler(rootHandler);
        parser.setErrorHandler(rootHandler);
        parser.parse(new InputSource(in));
    } catch (Exception e) {
        throw new ConfigurationException("Error loading configuration from %s", e, configurationURL);
    }

    return domains;
}

From source file:org.apache.cayenne.project.upgrade.v6.XMLDataSourceInfoLoader_V3_0_0_1.java

DataSourceInfo load(Resource configurationSource) {
    if (configurationSource == null) {
        throw new NullPointerException("Null configurationSource");
    }//from w  w w. j  a  v a  2  s .  co  m

    URL configurationURL = configurationSource.getURL();

    DataSourceInfo dataSourceInfo = new DataSourceInfo();

    InputStream in = null;

    try {
        in = configurationURL.openStream();
        XMLReader parser = Util.createXmlReader();

        DriverHandler rootHandler = new DriverHandler(parser, dataSourceInfo);
        parser.setContentHandler(rootHandler);
        parser.setErrorHandler(rootHandler);
        parser.parse(new InputSource(in));
    } catch (Exception e) {
        throw new ConfigurationException("Error loading configuration from %s", e, configurationURL);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ioex) {
            logger.info("failure closing input stream for " + configurationURL + ", ignoring", ioex);
        }
    }

    return dataSourceInfo;
}

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

/**
 * Runs a test.//from  w  ww  . j a  va2  s.c om
 * @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.jmeter.protocol.http.proxy.DefaultSamplerCreatorClassifier.java

/**
 * Tries parsing to see if content is xml
 * /*from   w  ww . java2 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;
    }
}

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.//  ww w  . j av a 2s.  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.ode.bpel.compiler.bom.BpelObjectFactory.java

/**
 * Parse a BPEL process found at the input source.
 * @param isrc input source.// ww  w . j a v a2 s  . com
 * @return
 * @throws SAXException
 */
public Process parse(InputSource isrc, URI systemURI) throws IOException, SAXException {
    XMLReader _xr = XMLParserUtils.getXMLReader();
    LocalEntityResolver resolver = new LocalEntityResolver();
    resolver.register(Bpel11QNames.NS_BPEL4WS_2003_03, getClass().getResource("/bpel4ws_1_1-fivesight.xsd"));
    resolver.register(Bpel20QNames.NS_WSBPEL2_0, getClass().getResource("/wsbpel_main-draft-Apr-29-2006.xsd"));
    resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_ABSTRACT,
            getClass().getResource("/ws-bpel_abstract_common_base.xsd"));
    resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_EXEC, getClass().getResource("/ws-bpel_executable.xsd"));
    resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_PLINK, getClass().getResource("/ws-bpel_plnktype.xsd"));
    resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_SERVREF,
            getClass().getResource("/ws-bpel_serviceref.xsd"));
    resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_VARPROP, getClass().getResource("/ws-bpel_varprop.xsd"));
    resolver.register(XML, getClass().getResource("/xml.xsd"));
    resolver.register(WSDL, getClass().getResource("/wsdl.xsd"));
    resolver.register(Bpel20QNames.NS_WSBPEL_PARTNERLINK_2004_03,
            getClass().getResource("/wsbpel_plinkType-draft-Apr-29-2006.xsd"));
    _xr.setEntityResolver(resolver);
    Document doc = DOMUtils.newDocument();
    _xr.setContentHandler(new DOMBuilderContentHandler(doc));
    _xr.setFeature("http://xml.org/sax/features/namespaces", true);
    _xr.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

    _xr.setFeature("http://xml.org/sax/features/validation", true);
    XMLParserUtils.addExternalSchemaURL(_xr, Bpel11QNames.NS_BPEL4WS_2003_03, Bpel11QNames.NS_BPEL4WS_2003_03);
    XMLParserUtils.addExternalSchemaURL(_xr, Bpel20QNames.NS_WSBPEL2_0, Bpel20QNames.NS_WSBPEL2_0);
    XMLParserUtils.addExternalSchemaURL(_xr, Bpel20QNames.NS_WSBPEL2_0_FINAL_EXEC,
            Bpel20QNames.NS_WSBPEL2_0_FINAL_EXEC);
    XMLParserUtils.addExternalSchemaURL(_xr, Bpel20QNames.NS_WSBPEL2_0_FINAL_ABSTRACT,
            Bpel20QNames.NS_WSBPEL2_0_FINAL_ABSTRACT);

    boolean strict = Boolean
            .parseBoolean(System.getProperty("org.apache.ode.compiler.failOnValidationErrors", "false"));
    BOMSAXErrorHandler errorHandler = new BOMSAXErrorHandler(strict);
    _xr.setErrorHandler(errorHandler);
    _xr.parse(isrc);
    if (strict) {
        if (!errorHandler.wasOK()) {
            throw new SAXException("Validation errors during parsing");
        }
    } else {
        if (!errorHandler.wasOK()) {
            __log.warn(
                    "Validation errors during parsing, continuing due to -Dorg.apache.ode.compiler.failOnValidationErrors=false switch");
        }
    }
    return (Process) createBpelObject(doc.getDocumentElement(), systemURI);
}