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:net.ontopia.topicmaps.entry.XMLConfigSource.java

private static List<TopicMapSourceIF> readSources(InputSource inp_source, Map<String, String> environ) {
    ConfigHandler handler = new ConfigHandler(environ);

    try {/*from   w w w .j av  a  2s  .  com*/
        XMLReader parser = DefaultXMLReaderFactory.createXMLReader();
        parser.setContentHandler(handler);
        parser.setErrorHandler(new Slf4jSaxErrorHandler(log));
        parser.parse(inp_source);
    } catch (SAXParseException e) {
        String msg = "" + e.getSystemId() + ":" + e.getLineNumber() + ":" + e.getColumnNumber() + ": "
                + e.getMessage();
        throw new OntopiaRuntimeException(msg, e);
    } catch (Exception e) {
        throw new OntopiaRuntimeException(e);
    }
    return handler.sources;
}

From source file:XMLUtilities.java

/**
 * Convenience method for parsing an XML file. This method will
 * wrap the resource in an InputSource and set the source's
 * systemId to "jedit.jar" (so the source should be able to
 * handle any external entities by itself).
 *
 * <p>SAX Errors are caught and are not propagated to the caller;
 * instead, an error message is printed to jEdit's activity
 * log. So, if you need custom error handling, <b>do not use
 * this method</b>.//from w w w . j a va 2 s .com
 *
 * <p>The given stream is closed before the method returns,
 * regardless whether there were errors or not.</p>
 *
 * @return true if any error occured during parsing, false if success.
 */
public static boolean parseXML(InputStream in, DefaultHandler handler) throws IOException {
    try {
        XMLReader parser = XMLReaderFactory.createXMLReader();
        InputSource isrc = new InputSource(new BufferedInputStream(in));
        isrc.setSystemId("jedit.jar");
        parser.setContentHandler(handler);
        parser.setDTDHandler(handler);
        parser.setEntityResolver(handler);
        parser.setErrorHandler(handler);
        parser.parse(isrc);
    } catch (SAXParseException se) {
        int line = se.getLineNumber();
        return true;
    } catch (SAXException e) {
        return true;
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException io) {
        }
    }
    return false;
}

From source file:it.osm.gtfs.input.OSMParser.java

public static List<Relation> readOSMRelations(File file, Map<String, Stop> stopsWithOSMIndex)
        throws ParserConfigurationException, SAXException, IOException {
    NodeParser nodeParser;//from   ww w  .jav a  2s  .  co  m
    {
        XMLReader xr = XMLReaderFactory.createXMLReader();
        nodeParser = new NodeParser();
        xr.setContentHandler(nodeParser);
        xr.setErrorHandler(nodeParser);
        xr.parse(new InputSource(new FileReader(file)));
    }

    WayParser wayParser;
    {
        XMLReader xr = XMLReaderFactory.createXMLReader();
        wayParser = new WayParser(nodeParser.result);
        xr.setContentHandler(wayParser);
        xr.setErrorHandler(wayParser);
        xr.parse(new InputSource(new FileReader(file)));
    }

    RelationParser relationParser;
    {
        XMLReader xr = XMLReaderFactory.createXMLReader();
        relationParser = new RelationParser(stopsWithOSMIndex, wayParser.result);
        xr.setContentHandler(relationParser);
        xr.setErrorHandler(relationParser);
        xr.parse(new InputSource(new FileReader(file)));
    }

    if (relationParser.missingNodes.size() > 0 || relationParser.failedRelationIds.size() > 0) {
        System.err.println("Failed to parse some relations. Relations id: "
                + StringUtils.join(relationParser.failedRelationIds, ", "));
        System.err.println("Failed to parse some relations. Missing nodes: "
                + StringUtils.join(relationParser.missingNodes, ", "));
    }

    return relationParser.result;
}

From source file:de.mpg.mpdl.inge.citationmanager.utils.XsltHelper.java

/**
 * Reads all CONE-entries with a citation-style field filled in. Generates a Map with citation
 * styles and idValue-Type-Pairs./* www . j a v  a 2s.c o  m*/
 * 
 * @throws Exception
 */
public static void getJournalsXML() throws Exception {
    HttpClient client = new HttpClient();

    String coneQuery =
            // JUS-Testserver CoNE
            // "http://193.174.132.114/cone/journals/query?format=rdf&escidoc:citation-style=*&m=full&n=0";
            PropertyReader.getProperty("escidoc.cone.service.url")
                    + "journals/query?format=rdf&escidoc:citation-style=*&m=full&n=0";
    logger.info("cone query:" + coneQuery);
    GetMethod getMethod = new GetMethod(coneQuery);

    ProxyHelper.executeMethod(client, getMethod);

    XMLReader xr;

    xr = XMLReaderFactory.createXMLReader();
    JusXmlHandler handler = new JusXmlHandler();
    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);

    Reader r = new InputStreamReader(getMethod.getResponseBodyAsStream());
    xr.parse(new InputSource(r));

    citationMap = handler.getCitationStyleMap();

}

From source file:jproxy.DefaultSamplerCreator.java

/**
 * Tries parsing to see if content is xml
 * @param postData String//w  w  w. j a va 2  s  . c o  m
 * @return boolean
 */
private static 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:de.mpg.escidoc.services.citationmanager.utils.XsltHelper.java

/**
 * Reads all CONE-entries with a citation-style field filled in. 
 * Generates a Map with citation styles and idValue-Type-Pairs. 
 * @throws Exception// ww  w  .ja v  a2s  .  c o m
 */
public static void getJournalsXML() throws Exception {
    HttpClient client = new HttpClient();

    String coneQuery =
            // JUS-Testserver CoNE
            //   "http://193.174.132.114/cone/journals/query?format=rdf&escidoc:citation-style=*&m=full&n=0";
            PropertyReader.getProperty("escidoc.cone.service.url")
                    + "journals/query?format=rdf&escidoc:citation-style=*&m=full&n=0";
    logger.info("cone query:" + coneQuery);
    GetMethod getMethod = new GetMethod(coneQuery);

    ProxyHelper.executeMethod(client, getMethod);

    XMLReader xr;

    xr = XMLReaderFactory.createXMLReader();
    JusXmlHandler handler = new JusXmlHandler();
    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);

    Reader r = new InputStreamReader(getMethod.getResponseBodyAsStream());
    xr.parse(new InputSource(r));

    citationMap = handler.getCitationStyleMap();

}

From source file:architecture.common.model.factory.ModelTypeFactory.java

private static List<ModelList> parseLegacyXmlFile(List<ModelList> list) throws Exception {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> enumeration = cl.getResources(IF_PLUGIN_PATH);
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);/*  www . j a  v a2 s . c  om*/
    XMLReader xmlreader = factory.newSAXParser().getXMLReader();
    ImplFactoryParsingHandler handler = new ImplFactoryParsingHandler();
    xmlreader.setContentHandler(handler);
    xmlreader.setDTDHandler(handler);
    xmlreader.setEntityResolver(handler);
    xmlreader.setErrorHandler(handler);
    System.out.println("Model Enum:");
    do {
        if (!enumeration.hasMoreElements())
            break;
        URL url = (URL) enumeration.nextElement();
        System.out.println(" - " + url);
        try {
            xmlreader.parse(new InputSource(url.openStream()));
            ModelList factorylist = new ModelList();
            factorylist.rank = handler.rank;
            factorylist.modelTypes.addAll(handler.getModels());
            list.add(factorylist);
        } catch (Exception exception) {
        }
    } while (true);

    return list;
}

From source file:com.granule.json.utils.XML.java

/**
 * Method to do the transform from an XML input stream to a JSON stream.
 * Neither input nor output streams are closed.  Closure is left up to the caller.
 *
 * @param XMLStream The XML stream to convert to JSON
 * @param JSONStream The stream to write out JSON to.  The contents written to this stream are always in UTF-8 format.
 * @param verbose Flag to denote whether or not to render the JSON text in verbose (indented easy to read), or compact (not so easy to read, but smaller), format.
 *
 * @throws SAXException Thrown if a parse error occurs.
 * @throws IOException Thrown if an IO error occurs.
 *//*from  w ww.  j  a va2s.c o m*/
public static void toJson(InputStream XMLStream, OutputStream JSONStream, boolean verbose)
        throws SAXException, IOException {
    if (logger.isLoggable(Level.FINER)) {
        logger.entering(className, "toJson(InputStream, OutputStream)");
    }

    if (XMLStream == null) {
        throw new NullPointerException("XMLStream cannot be null");
    } else if (JSONStream == null) {
        throw new NullPointerException("JSONStream cannot be null");
    } else {

        if (logger.isLoggable(Level.FINEST)) {
            logger.logp(Level.FINEST, className, "transform",
                    "Fetching a SAX parser for use with JSONSAXHandler");
        }

        try {
            /**
             * Get a parser.
             */
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            SAXParser sParser = factory.newSAXParser();
            XMLReader parser = sParser.getXMLReader();
            JSONSAXHandler jsonHandler = new JSONSAXHandler(JSONStream, verbose);
            parser.setContentHandler(jsonHandler);
            parser.setErrorHandler(jsonHandler);
            InputSource source = new InputSource(new BufferedInputStream(XMLStream));

            if (logger.isLoggable(Level.FINEST)) {
                logger.logp(Level.FINEST, className, "transform", "Parsing the XML content to JSON");
            }

            /** 
             * Parse it.
             */
            source.setEncoding("UTF-8");
            parser.parse(source);
            jsonHandler.flushBuffer();
        } catch (javax.xml.parsers.ParserConfigurationException pce) {
            throw new SAXException("Could not get a parser: " + pce.toString());
        }
    }

    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toJson(InputStream, OutputStream)");
    }
}

From source file:io.onedecision.engine.decisions.model.dmn.validators.SchemaValidator.java

public void validate(InputStream obj, Errors errors) {
    InputStream is = (InputStream) obj;

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new LocalResourceResolver());

    try {//from w w  w. j a v a 2  s.c om
        schemaFactory.newSchema(new StreamSource(getResourceAsStreamWrapper("schema/dmn.xsd")));
    } catch (SAXException e1) {
        errors.reject("Cannot find / read schema", "Exception: " + e1.getMessage());
    }

    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    // parserFactory.setValidating(true);
    parserFactory.setNamespaceAware(true);
    // parserFactory.setSchema(schema);

    SAXParser parser = null;
    try {
        parser = parserFactory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setErrorHandler(this);

        try {
            parser.parse(new InputSource(is), (DefaultHandler) null);
        } catch (Exception e) {
            String msg = "Schema validation failed";
            LOGGER.error(msg, e);
            errors.reject(msg, "Exception: " + e.getMessage());
        }
        if (this.errors.size() > 0) {
            errors.reject("Schema validation failed", this.errors.toString());
        }
    } catch (ParserConfigurationException e1) {
        errors.reject("Cannot create parser", "Exception: " + e1.getMessage());
    } catch (SAXException e1) {
        errors.reject("Parser cannot be created", "Exception: " + e1.getMessage());
    }
}

From source file:org.solmix.runtime.support.spring.TunedDocumentLoader.java

@Override
public Document loadDocument(InputSource inputSource, EntityResolver entityResolver, ErrorHandler errorHandler,
        int validationMode, boolean namespaceAware) throws Exception {
    if (validationMode == XmlBeanDefinitionReader.VALIDATION_NONE) {
        SAXParserFactory parserFactory = namespaceAware ? nsasaxParserFactory : saxParserFactory;
        SAXParser parser = parserFactory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setEntityResolver(entityResolver);
        reader.setErrorHandler(errorHandler);
        //            SAXSource saxSource = new SAXSource(reader, inputSource);
        //            W3CDOMStreamWriter writer = new W3CDOMStreaXMLStreamWriterImplmWriter();
        //            StaxUtils.copy(saxSource, writer);
        //            return writer.getDocument();
        return null;
    } else {//from  w  w  w.ja v a 2s. co  m
        return super.loadDocument(inputSource, entityResolver, errorHandler, validationMode, namespaceAware);
    }
}