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.ojb.broker.metadata.RepositoryPersistor.java

/**
 * Read metadata by populating an instance of the target class
 * using SAXParser./*from w  ww.j av a 2 s . c  om*/
 */
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;
}

From source file:org.apache.solr.handler.loader.XMLLoader.java

@Override
public void load(SolrQueryRequest req, SolrQueryResponse rsp, ContentStream stream,
        UpdateRequestProcessor processor) throws Exception {
    final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType());

    InputStream is = null;//  www  .  j  av  a2 s. c  o m
    XMLStreamReader parser = null;

    String tr = req.getParams().get(CommonParams.TR, null);
    if (tr != null) {
        final Transformer t = getTransformer(tr, req);
        final DOMResult result = new DOMResult();

        // first step: read XML and build DOM using Transformer (this is no overhead, as XSL always produces
        // an internal result DOM tree, we just access it directly as input for StAX):
        try {
            is = stream.getStream();
            final InputSource isrc = new InputSource(is);
            isrc.setEncoding(charset);
            final XMLReader xmlr = saxFactory.newSAXParser().getXMLReader();
            xmlr.setErrorHandler(xmllog);
            xmlr.setEntityResolver(EmptyEntityResolver.SAX_INSTANCE);
            final SAXSource source = new SAXSource(xmlr, isrc);
            t.transform(source, result);
        } catch (TransformerException te) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, te.getMessage(), te);
        } finally {
            IOUtils.closeQuietly(is);
        }
        // second step: feed the intermediate DOM tree into StAX parser:
        try {
            parser = inputFactory.createXMLStreamReader(new DOMSource(result.getNode()));
            this.processUpdate(req, processor, parser);
        } catch (XMLStreamException e) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e);
        } finally {
            if (parser != null)
                parser.close();
        }
    }
    // Normal XML Loader
    else {
        try {
            is = stream.getStream();
            if (log.isTraceEnabled()) {
                final byte[] body = IOUtils.toByteArray(is);
                // TODO: The charset may be wrong, as the real charset is later
                // determined by the XML parser, the content-type is only used as a hint!
                log.trace("body",
                        new String(body, (charset == null) ? ContentStreamBase.DEFAULT_CHARSET : charset));
                IOUtils.closeQuietly(is);
                is = new ByteArrayInputStream(body);
            }
            parser = (charset == null) ? inputFactory.createXMLStreamReader(is)
                    : inputFactory.createXMLStreamReader(is, charset);
            this.processUpdate(req, processor, parser);
        } catch (XMLStreamException e) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e);
        } finally {
            if (parser != null)
                parser.close();
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:org.apache.synapse.mediators.transform.PayloadFactoryMediator.java

private boolean isWellFormedXML(String value) {
    try {/*from w  ww . j  a v  a2 s .  c  o  m*/
        XMLReader parser = XMLReaderFactory.createXMLReader();
        parser.setErrorHandler(null);
        InputSource source = new InputSource(new ByteArrayInputStream(value.getBytes()));
        parser.parse(source);
    } catch (SAXException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
    return true;
}

From source file:org.betaconceptframework.astroboa.test.util.JAXBValidationUtils.java

public void validateUsingSAX(InputStream is) throws Exception {
    SAXParser saxParser = parserFactory.newSAXParser();

    XMLReader xmlReader = saxParser.getXMLReader();
    xmlReader.setEntityResolver(entityResolver);
    xmlReader.setErrorHandler(errorHandler);

    errorHandler.setIgnoreInvalidElementSequence(false);

    is = encodeURLsFoundInXML(is);//from w w  w. jav a  2s  .co m

    xmlReader.parse(new InputSource(is));
}

From source file:org.deegree.tools.metadata.ISO19139Validator.java

/**
 * @param srcOpt/*  w ww.  j ava 2 s  .  co  m*/
 * @param schemaOpt
 * @param resultOpt
 * @throws IOException
 * @throws SAXException
 */
public void run(String srcOpt, String schemaOpt, String resultOpt) throws IOException, SAXException {
    File src = new File(srcOpt);
    if (!src.exists()) {
        throw new IllegalArgumentException("src does not exist: " + srcOpt + ". Check parameter " + OPT_SRC);
    }
    File result;
    if (resultOpt != null && resultOpt.length() > 0) {
        result = new File(resultOpt);
        if (!result.exists()) {
            result.createNewFile();
        }
    } else {
        result = File.createTempFile(DEFAULT_FILENAME, ".txt");
    }

    SCHEMAVERSION schemaVersion = SCHEMAVERSION.V2007;
    if (schemaOpt != null) {
        try {
            schemaVersion = SCHEMAVERSION.valueOf(schemaOpt);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid argument for " + OPT_SCHEMA_VERSION + ": " + schemaOpt);
        }
    }

    String schema = "/META-INF/SCHEMAS_OPENGIS_NET/iso/19139/20070417/gmd/metadataEntity.xsd";
    if (SCHEMAVERSION.V2006.equals(schemaVersion)) {
        schema = "/META-INF/SCHEMAS_OPENGIS_NET/iso/19139/20060504/gmd/metadataEntity.xsd";
    }
    URL u = ISO19139Validator.class.getResource(schema);
    XMLReader parser = XMLReaderFactory.createXMLReader();
    parser.setFeature("http://xml.org/sax/features/validation", true);
    parser.setFeature("http://apache.org/xml/features/validation/schema", true);
    parser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
            "http://www.isotc211.org/2005/gmd " + u.toExternalForm());

    final FileWriter fw = new FileWriter(result);

    File[] filesToValidate;
    if (src.isDirectory()) {
        filesToValidate = src.listFiles();
        fw.write("validate " + filesToValidate.length + " files from directory " + src);
        fw.write("\n");
    } else {
        filesToValidate = new File[] { src };
    }
    System.out.println("Start validation");
    int noOfValidRecords = 0;
    for (int i = 0; i < filesToValidate.length; i++) {
        FileErrorHandler feh = new FileErrorHandler(fw);
        parser.setErrorHandler(feh);
        if (filesToValidate.length > 1) {
            fw.write("validate record " + i + " of " + filesToValidate.length);
            fw.write("\n");
        }
        File fileToValidate = filesToValidate[i];
        System.out.println(fileToValidate);
        fw.write("validate file " + fileToValidate.getAbsolutePath());
        fw.write("\n");
        try {
            parser.parse(new InputSource(new FileInputStream(fileToValidate)));
        } catch (Exception e) {
            String msg = "Could not validate current occured: " + e.getMessage()
                    + ". Continue with next record";
            System.err.println(msg);
            fw.write(msg);
            fw.write("\n");
            continue;
        }
        fw.flush();
        if (feh.isValid())
            noOfValidRecords++;
    }
    fw.write(noOfValidRecords + " of " + filesToValidate.length + " records are valid.");
    fw.close();
    System.out.println("Validation finished, result file: " + result.getAbsolutePath());
}

From source file:org.dhatim.delivery.AbstractParser.java

private void setHandlers(XMLReader reader) throws SAXException {
    if (saxDriverConfig != null) {
        List<Parameter> handlers;

        handlers = saxDriverConfig.getParameters("sax-handler");
        if (handlers != null) {
            for (Parameter handler : handlers) {
                Object handlerObj = createHandler(handler.getValue());

                if (handlerObj instanceof EntityResolver) {
                    reader.setEntityResolver((EntityResolver) handlerObj);
                }/*from   w  w w .  j  a  va 2 s .  co  m*/
                if (handlerObj instanceof DTDHandler) {
                    reader.setDTDHandler((DTDHandler) handlerObj);
                }
                if (handlerObj instanceof ErrorHandler) {
                    reader.setErrorHandler((ErrorHandler) handlerObj);
                }
            }
        }
    }
}

From source file:org.dspace.content.authority.LCNameAuthority.java

/**
 * Guts of the implementation, returns a complete Choices result, or
 * null for a failure.//from  w w w .  j  av  a2 s  . c om
 */
private Choices queryPerson(String text, int start, int limit) {
    // punt if there is no query text
    if (text == null || text.trim().length() == 0) {
        return new Choices(true);
    }

    // 1. build CQL query
    DCPersonName pn = new DCPersonName(text);
    StringBuilder query = new StringBuilder();
    query.append("local.FirstName = \"").append(pn.getFirstNames()).append("\" and local.FamilyName = \"")
            .append(pn.getLastName()).append("\"");

    // XXX arbitrary default limit - should be configurable?
    if (limit == 0) {
        limit = 50;
    }

    NameValuePair args[] = new NameValuePair[6];
    args[0] = new NameValuePair("operation", "searchRetrieve");
    args[1] = new NameValuePair("version", "1.1");
    args[2] = new NameValuePair("recordSchema", "info:srw/schema/1/marcxml-v1.1");
    args[3] = new NameValuePair("query", query.toString());
    args[4] = new NameValuePair("maximumRecords", String.valueOf(limit));
    args[5] = new NameValuePair("startRecord", String.valueOf(start + 1));
    HttpClient hc = new HttpClient();
    String srUrl = url + "?" + EncodingUtil.formUrlEncode(args, "UTF8");
    GetMethod get = new GetMethod(srUrl);

    log.debug("Trying SRU query, URL=" + srUrl);

    // 2. web request
    try {
        int status = hc.executeMethod(get);
        if (status == 200) {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            SRUHandler handler = new SRUHandler();

            // XXX FIXME: should turn off validation here explicitly, but
            //  it seems to be off by default.
            xr.setFeature("http://xml.org/sax/features/namespaces", true);
            xr.setContentHandler(handler);
            xr.setErrorHandler(handler);
            xr.parse(new InputSource(get.getResponseBodyAsStream()));

            // this probably just means more results available..
            if (handler.hits != handler.result.size()) {
                log.warn("Discrepency in results, result.length=" + handler.result.size()
                        + ", yet expected results=" + handler.hits);
            }
            boolean more = handler.hits > (start + handler.result.size());

            // XXX add non-auth option; perhaps the UI should do this?
            // XXX it's really a policy matter if they allow unauth result.
            // XXX good, stop it.
            // handler.result.add(new Choice("", text, "Non-Authority: \""+text+"\""));

            int confidence;
            if (handler.hits == 0) {
                confidence = Choices.CF_NOTFOUND;
            } else if (handler.hits == 1) {
                confidence = Choices.CF_UNCERTAIN;
            } else {
                confidence = Choices.CF_AMBIGUOUS;
            }
            return new Choices(handler.result.toArray(new Choice[handler.result.size()]), start, handler.hits,
                    confidence, more);
        }
    } catch (HttpException e) {
        log.error("SRU query failed: ", e);
        return new Choices(true);
    } catch (IOException e) {
        log.error("SRU query failed: ", e);
        return new Choices(true);
    } catch (ParserConfigurationException e) {
        log.warn("Failed parsing SRU result: ", e);
        return new Choices(true);
    } catch (SAXException e) {
        log.warn("Failed parsing SRU result: ", e);
        return new Choices(true);
    } finally {
        get.releaseConnection();
    }
    return new Choices(true);
}

From source file:org.dspace.content.authority.SHERPARoMEOProtocol.java

protected Choices query(String result, String label, String authority, NameValuePair[] args, int start,
        int limit) {
    HttpClient hc = new HttpClient();
    String srUrl = url + "?" + EncodingUtil.formUrlEncode(args, "UTF8");
    GetMethod get = new GetMethod(srUrl);

    log.debug("Trying SHERPA/RoMEO Query, URL=" + srUrl);

    try {/*  www  . java  2 s.  c  o m*/
        int status = hc.executeMethod(get);
        if (status == 200) {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            SRHandler handler = new SRHandler(result, label, authority);

            // XXX FIXME: should turn off validation here explicitly, but
            //  it seems to be off by default.
            xr.setFeature("http://xml.org/sax/features/namespaces", true);
            xr.setContentHandler(handler);
            xr.setErrorHandler(handler);
            xr.parse(new InputSource(get.getResponseBodyAsStream()));
            int confidence;
            if (handler.total == 0) {
                confidence = Choices.CF_NOTFOUND;
            } else if (handler.total == 1) {
                confidence = Choices.CF_UNCERTAIN;
            } else {
                confidence = Choices.CF_AMBIGUOUS;
            }
            return new Choices(handler.result, start, handler.total, confidence, false);
        }
    } catch (HttpException e) {
        log.error("SHERPA/RoMEO query failed: ", e);
        return null;
    } catch (IOException e) {
        log.error("SHERPA/RoMEO query failed: ", e);
        return null;
    } catch (ParserConfigurationException e) {
        log.warn("Failed parsing SHERPA/RoMEO result: ", e);
        return null;
    } catch (SAXException e) {
        log.warn("Failed parsing SHERPA/RoMEO result: ", e);
        return null;
    } finally {
        get.releaseConnection();
    }
    return null;
}

From source file:org.dspace.content.authority.SkylightAPIProtocol.java

protected Choices query(String result, String label, String authority, String args, int start, int limit)
        throws UnsupportedEncodingException {
    String encodedArgs = new String(args.getBytes("UTF-8"), "UTF-8");
    HttpClient hc = new HttpClient();
    String srUrl = url + "/search/" + encodedArgs + ".xml?field=" + label;
    GetMethod get = new GetMethod(srUrl);

    log.info("Trying Skylight Query, URL=" + srUrl);

    try {//from  www. j ava 2s  .c om
        int status = hc.executeMethod(get);
        log.info("Status" + status);
        if (status == 200) {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            SRHandler handler = new SRHandler(result, label, authority);

            // XXX FIXME: should turn off validation here explicitly, but
            //  it seems to be off by default.
            xr.setFeature("http://xml.org/sax/features/namespaces", true);
            xr.setContentHandler(handler);
            xr.setErrorHandler(handler);
            InputSource src = new InputSource(get.getResponseBodyAsStream());
            log.info("Source from sklightui :: " + src.toString());
            xr.parse(src);

            int confidence;
            if (handler.total == 0) {
                confidence = Choices.CF_NOTFOUND;
            } else if (handler.total == 1) {
                confidence = Choices.CF_UNCERTAIN;
            } else {
                confidence = Choices.CF_AMBIGUOUS;
            }
            return new Choices(handler.result, start, handler.total, confidence, false);
        }
    } catch (HttpException e) {
        log.error("Skylight query failed: ", e);
        return null;
    } catch (IOException e) {
        log.error("Skylight query failed: ", e);
        return null;
    } catch (ParserConfigurationException e) {
        log.warn("Failed parsing SHERPA/RoMEO result: ", e);
        return null;
    } catch (SAXException e) {
        log.warn("Failed parsing Skylight result: ", e);
        return null;
    } finally {
        get.releaseConnection();
    }
    return null;
}

From source file:org.eclipse.rdf4j.rio.rdfxml.RDFXMLParser.java

private void parse(InputSource inputSource) throws IOException, RDFParseException, RDFHandlerException {
    clear();//from ww w .j  a  v  a 2s.  c  om

    try {
        documentURI = inputSource.getSystemId();

        saxFilter.setParseStandAloneDocuments(
                getParserConfig().get(XMLParserSettings.PARSE_STANDALONE_DOCUMENTS));

        // saxFilter.clear();
        saxFilter.setDocumentURI(documentURI);

        XMLReader xmlReader;

        if (getParserConfig().isSet(XMLParserSettings.CUSTOM_XML_READER)) {
            xmlReader = getParserConfig().get(XMLParserSettings.CUSTOM_XML_READER);
        } else {
            xmlReader = XMLReaderFactory.createXMLReader();
        }

        xmlReader.setContentHandler(saxFilter);
        xmlReader.setErrorHandler(this);

        // Set all compulsory feature settings, using the defaults if they are
        // not explicitly set
        for (RioSetting<Boolean> aSetting : getCompulsoryXmlFeatureSettings()) {
            try {
                xmlReader.setFeature(aSetting.getKey(), getParserConfig().get(aSetting));
            } catch (SAXNotRecognizedException e) {
                reportWarning(String.format("%s is not a recognized SAX feature.", aSetting.getKey()));
            } catch (SAXNotSupportedException e) {
                reportWarning(String.format("%s is not a supported SAX feature.", aSetting.getKey()));
            }
        }

        // Set all compulsory property settings, using the defaults if they are
        // not explicitly set
        for (RioSetting<?> aSetting : getCompulsoryXmlPropertySettings()) {
            try {
                xmlReader.setProperty(aSetting.getKey(), getParserConfig().get(aSetting));
            } catch (SAXNotRecognizedException e) {
                reportWarning(String.format("%s is not a recognized SAX property.", aSetting.getKey()));
            } catch (SAXNotSupportedException e) {
                reportWarning(String.format("%s is not a supported SAX property.", aSetting.getKey()));
            }
        }

        // Check for any optional feature settings that are explicitly set in
        // the parser config
        for (RioSetting<Boolean> aSetting : getOptionalXmlFeatureSettings()) {
            try {
                if (getParserConfig().isSet(aSetting)) {
                    xmlReader.setFeature(aSetting.getKey(), getParserConfig().get(aSetting));
                }
            } catch (SAXNotRecognizedException e) {
                reportWarning(String.format("%s is not a recognized SAX feature.", aSetting.getKey()));
            } catch (SAXNotSupportedException e) {
                reportWarning(String.format("%s is not a supported SAX feature.", aSetting.getKey()));
            }
        }

        // Check for any optional property settings that are explicitly set in
        // the parser config
        for (RioSetting<?> aSetting : getOptionalXmlPropertySettings()) {
            try {
                if (getParserConfig().isSet(aSetting)) {
                    xmlReader.setProperty(aSetting.getKey(), getParserConfig().get(aSetting));
                }
            } catch (SAXNotRecognizedException e) {
                reportWarning(String.format("%s is not a recognized SAX property.", aSetting.getKey()));
            } catch (SAXNotSupportedException e) {
                reportWarning(String.format("%s is not a supported SAX property.", aSetting.getKey()));
            }
        }

        xmlReader.parse(inputSource);
    } catch (SAXParseException e) {
        Exception wrappedExc = e.getException();

        if (wrappedExc == null) {
            reportFatalError(e, e.getLineNumber(), e.getColumnNumber());
        } else {
            reportFatalError(wrappedExc, e.getLineNumber(), e.getColumnNumber());
        }
    } catch (SAXException e) {
        Exception wrappedExc = e.getException();

        if (wrappedExc == null) {
            reportFatalError(e);
        } else if (wrappedExc instanceof RDFParseException) {
            throw (RDFParseException) wrappedExc;
        } else if (wrappedExc instanceof RDFHandlerException) {
            throw (RDFHandlerException) wrappedExc;
        } else {
            reportFatalError(wrappedExc);
        }
    } finally {
        // Clean up
        saxFilter.clear();
        xmlLang = null;
        elementStack.clear();
        usedIDs.clear();
        clear();
    }
}