List of usage examples for org.xml.sax XMLReader setErrorHandler
public void setErrorHandler(ErrorHandler handler);
From source file:org.eclipse.rdf4j.rio.trix.TriXParser.java
private void parse(InputSource inputStreamOrReader) throws IOException, RDFParseException, RDFHandlerException { clear();/*from w w w . j av a2s .co m*/ try { if (rdfHandler != null) { rdfHandler.startRDF(); } XMLReader xmlReader; if (getParserConfig().isSet(XMLParserSettings.CUSTOM_XML_READER)) { xmlReader = getParserConfig().get(XMLParserSettings.CUSTOM_XML_READER); } else { xmlReader = XMLReaderFactory.createXMLReader(); } xmlReader.setErrorHandler(this); saxParser = new SimpleSAXParser(xmlReader); saxParser.setPreserveWhitespace(true); saxParser.setListener(new TriXSAXHandler()); saxParser.parse(inputStreamOrReader); } 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 { clear(); } if (rdfHandler != null) { rdfHandler.endRDF(); } }
From source file:org.everit.authentication.cas.CasAuthentication.java
/** * Returns the value of an XML element. This method is used to process the XMLs sent by the CAS * server./*ww w . ja va 2 s. co m*/ * * @param xmlAsString * the XML string to process * @param elementName * the name of the queried element * @return the value assigned to the queried element name * @throws RuntimeException * if any error occurs during the parsing of the XML string */ private String getTextForElement(final String xmlAsString, final String elementName) { XMLReader xmlReader; try { xmlReader = saxParserFactory.newSAXParser().getXMLReader(); xmlReader.setFeature("http://xml.org/sax/features/namespaces", true); xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } catch (SAXException | ParserConfigurationException e) { throw new RuntimeException("Unable to create XMLReader", e); } StringBuilder builder = new StringBuilder(); DefaultHandler handler = new DefaultHandlerExt(builder, elementName); xmlReader.setContentHandler(handler); xmlReader.setErrorHandler(handler); try { xmlReader.parse(new InputSource(new StringReader(xmlAsString))); } catch (Exception e) { throw new RuntimeException(e); } return builder.toString(); }
From source file:org.everit.osgi.authentication.cas.internal.CasAuthenticationComponent.java
/** * Returns the value of an XML element. This method is used to process the XMLs sent by the CAS server. * * @param xmlAsString/*from w w w.ja v a2 s .c om*/ * the XML string to process * @param elementName * the name of the queried element * @return the value assigned to the queried element name * @throws RuntimeException * if any error occurs during the parsing of the XML string */ private String getTextForElement(final String xmlAsString, final String elementName) { XMLReader xmlReader; try { xmlReader = saxParserFactory.newSAXParser().getXMLReader(); xmlReader.setFeature("http://xml.org/sax/features/namespaces", true); xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } catch (final Exception e) { throw new RuntimeException("Unable to create XMLReader", e); } StringBuilder builder = new StringBuilder(); DefaultHandler handler = new DefaultHandler() { private boolean foundElement = false; @Override public void characters(final char[] ch, final int start, final int length) throws SAXException { if (foundElement) { builder.append(ch, start, length); } } @Override public void endElement(final String uri, final String localName, final String qName) throws SAXException { if (localName.equals(elementName)) { foundElement = false; } } @Override public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { if (localName.equals(elementName)) { foundElement = true; } } }; xmlReader.setContentHandler(handler); xmlReader.setErrorHandler(handler); try { xmlReader.parse(new InputSource(new StringReader(xmlAsString))); } catch (Exception e) { throw new RuntimeException(e); } return builder.toString(); }
From source file:org.exist.mongodb.xquery.gridfs.Get.java
/** * Parse an byte-array containing (compressed) XML data into an eXist-db * document.// w w w.j av a 2s . c o m * * @param data Byte array containing the XML data. * @return Sequence containing the XML as DocumentImpl * * @throws XPathException Something bad happened. */ private Sequence processXML(XQueryContext xqueryContext, InputStream is) throws XPathException { Sequence content = null; try { final ValidationReport validationReport = new ValidationReport(); final SAXAdapter adapter = new SAXAdapter(xqueryContext); final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); final InputSource src = new InputSource(is); final SAXParser parser = factory.newSAXParser(); XMLReader xr = parser.getXMLReader(); xr.setErrorHandler(validationReport); xr.setContentHandler(adapter); xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter); xr.parse(src); // Cleanup IOUtils.closeQuietly(is); if (validationReport.isValid()) { content = (DocumentImpl) adapter.getDocument(); } else { String txt = String.format("Received document is not valid: %s", validationReport.toString()); LOG.debug(txt); throw new XPathException(txt); } } catch (SAXException | ParserConfigurationException | IOException ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(ex.getMessage()); } return content; }
From source file:org.exist.util.XMLReaderPool.java
public synchronized void returnXMLReader(XMLReader reader) { if (reader == null) { return;/* w ww. j a va 2s. c om*/ } try { reader.setContentHandler(DUMMY_HANDLER); reader.setErrorHandler(DUMMY_HANDLER); reader.setProperty(Namespaces.SAX_LEXICAL_HANDLER, DUMMY_HANDLER); // DIZZZ; workaround Xerces bug. Cached DTDs cause for problems during validation parsing. final GrammarPool grammarPool = (GrammarPool) getReaderProperty(reader, XMLReaderObjectFactory.APACHE_PROPERTIES_INTERNAL_GRAMMARPOOL); if (grammarPool != null) { grammarPool.clearDTDs(); } super.returnObject(reader); } catch (final Exception e) { throw new IllegalStateException("error while returning XMLReader: " + e.getMessage(), e); } }
From source file:org.h2gis.drivers.osm.OSMParser.java
/** * Read the OSM file and create its corresponding tables. * * @param inputFile// ww w . ja v a 2 s .co m * @param tableName * @param connection * @param progress * @return * @throws SQLException */ public boolean read(Connection connection, String tableName, File inputFile, ProgressVisitor progress) throws SQLException { this.progress = progress.subProcess(100); // Initialisation final boolean isH2 = JDBCUtilities.isH2DataBase(connection.getMetaData()); boolean success = false; TableLocation requestedTable = TableLocation.parse(tableName, isH2); String osmTableName = requestedTable.getTable(); checkOSMTables(connection, isH2, requestedTable, osmTableName); createOSMDatabaseModel(connection, isH2, requestedTable, osmTableName); FileInputStream fs = null; try { fs = new FileInputStream(inputFile); this.fc = fs.getChannel(); this.fileSize = fc.size(); // Given the file size and an average node file size. // Skip how many nodes in order to update progression at a step of 1% readFileSizeEachNode = Math.max(1, (this.fileSize / AVERAGE_NODE_SIZE) / 100); nodeCountProgress = 0; XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setErrorHandler(this); parser.setContentHandler(this); if (inputFile.getName().endsWith(".osm")) { parser.parse(new InputSource(fs)); } else if (inputFile.getName().endsWith(".osm.gz")) { parser.parse(new InputSource(new GZIPInputStream(fs))); } else if (inputFile.getName().endsWith(".osm.bz2")) { parser.parse(new InputSource(new BZip2CompressorInputStream(fs))); } success = true; } catch (SAXException ex) { throw new SQLException(ex); } catch (IOException ex) { throw new SQLException("Cannot parse the file " + inputFile.getAbsolutePath(), ex); } finally { try { if (fs != null) { fs.close(); } } catch (IOException ex) { throw new SQLException("Cannot close the file " + inputFile.getAbsolutePath(), ex); } // When the reading ends, close() method has to be called if (nodePreparedStmt != null) { nodePreparedStmt.close(); } if (nodeTagPreparedStmt != null) { nodeTagPreparedStmt.close(); } if (wayPreparedStmt != null) { wayPreparedStmt.close(); } if (wayTagPreparedStmt != null) { wayTagPreparedStmt.close(); } if (wayNodePreparedStmt != null) { wayNodePreparedStmt.close(); } if (relationPreparedStmt != null) { relationPreparedStmt.close(); } if (relationTagPreparedStmt != null) { relationTagPreparedStmt.close(); } if (nodeMemberPreparedStmt != null) { nodeMemberPreparedStmt.close(); } if (wayMemberPreparedStmt != null) { wayMemberPreparedStmt.close(); } if (relationMemberPreparedStmt != null) { relationMemberPreparedStmt.close(); } if (tagPreparedStmt != null) { tagPreparedStmt.close(); } } return success; }
From source file:org.h2gis.functions.io.osm.OSMParser.java
/** * Read the OSM file and create its corresponding tables. * * @param inputFile//from w ww . j ava 2s . c om * @param tableName * @param connection * @param progress * @return * @throws SQLException */ public boolean read(Connection connection, String tableName, File inputFile, ProgressVisitor progress) throws SQLException { this.progress = progress.subProcess(100); // Initialisation final boolean isH2 = JDBCUtilities.isH2DataBase(connection.getMetaData()); boolean success = false; TableLocation requestedTable = TableLocation.parse(tableName, isH2); String osmTableName = requestedTable.getTable(); checkOSMTables(connection, isH2, requestedTable, osmTableName); createOSMDatabaseModel(connection, isH2, requestedTable, osmTableName); FileInputStream fs = null; try { fs = new FileInputStream(inputFile); this.fc = fs.getChannel(); this.fileSize = fc.size(); // Given the file size and an average node file size. // Skip how many nodes in order to update progression at a step of 1% readFileSizeEachNode = Math.max(1, (this.fileSize / AVERAGE_NODE_SIZE) / 100); nodeCountProgress = 0; XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setErrorHandler(this); parser.setContentHandler(this); if (inputFile.getName().endsWith(".osm")) { parser.parse(new InputSource(fs)); } else if (inputFile.getName().endsWith(".osm.gz")) { parser.parse(new InputSource(new GZIPInputStream(fs))); } else if (inputFile.getName().endsWith(".osm.bz2")) { parser.parse(new InputSource(new BZip2CompressorInputStream(fs))); } else { throw new SQLException("Supported formats are .osm, .osm.gz, .osm.bz2"); } success = true; } catch (SAXException ex) { throw new SQLException(ex); } catch (IOException ex) { throw new SQLException("Cannot parse the file " + inputFile.getAbsolutePath(), ex); } finally { try { if (fs != null) { fs.close(); } } catch (IOException ex) { throw new SQLException("Cannot close the file " + inputFile.getAbsolutePath(), ex); } // When the reading ends, close() method has to be called if (nodePreparedStmt != null) { nodePreparedStmt.close(); } if (nodeTagPreparedStmt != null) { nodeTagPreparedStmt.close(); } if (wayPreparedStmt != null) { wayPreparedStmt.close(); } if (wayTagPreparedStmt != null) { wayTagPreparedStmt.close(); } if (wayNodePreparedStmt != null) { wayNodePreparedStmt.close(); } if (relationPreparedStmt != null) { relationPreparedStmt.close(); } if (relationTagPreparedStmt != null) { relationTagPreparedStmt.close(); } if (nodeMemberPreparedStmt != null) { nodeMemberPreparedStmt.close(); } if (wayMemberPreparedStmt != null) { wayMemberPreparedStmt.close(); } if (relationMemberPreparedStmt != null) { relationMemberPreparedStmt.close(); } if (tagPreparedStmt != null) { tagPreparedStmt.close(); } } return success; }
From source file:org.itracker.web.util.ImportExportUtilities.java
/** * Takes an XML file matching the ITracker import/export DTD and returns an array * of AbstractBean objects. The array will contain all of the projects, components * versions, users, custom fields, and issues contained in the XML. * * @param xmlReader an xml reader to import * @throws ImportExportException thrown if the xml can not be parsed into the appropriate objects *///from w w w . j a v a 2s . com public static AbstractEntity[] importIssues(Reader xmlReader) throws ImportExportException { AbstractEntity[] abstractBeans; try { logger.debug("Starting XML data import."); XMLReader reader = XMLReaderFactory.createXMLReader(); ImportHandler handler = new ImportHandler(); reader.setContentHandler(handler); reader.setErrorHandler(handler); reader.parse(new InputSource(xmlReader)); abstractBeans = handler.getModels(); logger.debug("Imported a total of " + abstractBeans.length + " beans."); } catch (Exception e) { logger.error("Exception.", e); throw new ImportExportException(e.getMessage()); } return abstractBeans; }
From source file:org.jasig.cas.client.util.XmlUtils.java
/** * Retrieve the text for a group of elements. Each text element is an entry * in a list.// w w w. ja v a2 s . c om * <p>This method is currently optimized for the use case of two elements in a list. * * @param xmlAsString the xml response * @param element the element to look for * @return the list of text from the elements. */ public static List getTextForElements(final String xmlAsString, final String element) { final List elements = new ArrayList(2); final XMLReader reader = getXmlReader(); final DefaultHandler handler = new DefaultHandler() { private boolean foundElement = false; private StringBuffer buffer = new StringBuffer(); public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { if (localName.equals(element)) { this.foundElement = true; } } public void endElement(final String uri, final String localName, final String qName) throws SAXException { if (localName.equals(element)) { this.foundElement = false; elements.add(this.buffer.toString()); this.buffer = new StringBuffer(); } } public void characters(char[] ch, int start, int length) throws SAXException { if (this.foundElement) { this.buffer.append(ch, start, length); } } }; reader.setContentHandler(handler); reader.setErrorHandler(handler); try { reader.parse(new InputSource(new StringReader(xmlAsString))); } catch (final Exception e) { LOG.error(e, e); return null; } return elements; }
From source file:org.jasig.cas.client.util.XmlUtils.java
/** * Retrieve the text for a specific element (when we know there is only * one).//ww w .j ava 2 s. c om * * @param xmlAsString the xml response * @param element the element to look for * @return the text value of the element. */ public static String getTextForElement(final String xmlAsString, final String element) { final XMLReader reader = getXmlReader(); final StringBuffer buffer = new StringBuffer(); final DefaultHandler handler = new DefaultHandler() { private boolean foundElement = false; public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { if (localName.equals(element)) { this.foundElement = true; } } public void endElement(final String uri, final String localName, final String qName) throws SAXException { if (localName.equals(element)) { this.foundElement = false; } } public void characters(char[] ch, int start, int length) throws SAXException { if (this.foundElement) { buffer.append(ch, start, length); } } }; reader.setContentHandler(handler); reader.setErrorHandler(handler); try { reader.parse(new InputSource(new StringReader(xmlAsString))); } catch (final Exception e) { LOG.error(e, e); return null; } return buffer.toString(); }