List of usage examples for org.xml.sax XMLReader setErrorHandler
public void setErrorHandler(ErrorHandler handler);
From source file:org.jboss.confluence.plugin.docbook_tools.docbookimport.DocbookImporter.java
/** * Process XSLT transformation.//from w w w . j av a 2 s .com * * @param xsltTemplate input stream with XSLT template file used to transform (closed inside this method) * @param xmlToTransform input stream with XML file to transform (closed inside this method) * @param xmlToTransformURL URL of <code>xmlToTransform</code> file (may be <code>file://</code> too). We need it to * correctly evaluate relative paths. * @param output stream to write transformed output to * @throws javax.xml.transform.TransformerException */ protected void processXslt(final InputStream xsltTemplate, final InputStream xmlToTransform, final String xmlToTransformURL, final OutputStream output) throws Exception { final XSLTErrorListener errorListener = new XSLTErrorListener(); final SAXErrorHandler eh = new SAXErrorHandler(); Thread th = new Thread(new Runnable() { public void run() { try { org.xml.sax.InputSource xmlSource = new org.xml.sax.InputSource(xmlToTransform); xmlSource.setSystemId(xmlToTransformURL); javax.xml.transform.Source xsltSource = new javax.xml.transform.stream.StreamSource( xsltTemplate); javax.xml.transform.Result result = new javax.xml.transform.stream.StreamResult(output); // prepare XInclude aware parser which resolves necessary entities correctly XMLReader reader = new ParserAdapter(saxParserFactory.newSAXParser().getParser()); reader.setEntityResolver(new JDGEntityResolver(reader.getEntityResolver())); reader.setErrorHandler(eh); SAXSource xmlSAXSource = new SAXSource(reader, xmlSource); javax.xml.transform.Transformer trans = transformerFact.newTransformer(xsltSource); trans.setErrorListener(errorListener); trans.transform(xmlSAXSource, result); } catch (Exception e) { if (e instanceof TransformerException) { errorListener.setException((TransformerException) e); } else { errorListener.setException(new TransformerException(e)); } } finally { FileUtils.closeInputStream(xmlToTransform); FileUtils.closeInputStream(xsltTemplate); } } }); th.setName("DocbookImporter XSLT transformation thread"); th.setDaemon(true); th.setContextClassLoader(DocbookImporter.class.getClassLoader()); th.start(); th.join(); if (eh.getException() != null) { throw eh.getException(); } if (errorListener.getException() != null) { throw errorListener.getException(); } }
From source file:org.jbuiltDemo.managed.view.Xhtml2Jbuilt.java
public Xhtml2Jbuilt() throws Exception { factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true);/*from w w w.jav a 2 s. c o m*/ factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true); factory.setFeature("http://xml.org/sax/features/validation", false); factory.setValidating(false); parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setDTDHandler(this); reader.setContentHandler(this); reader.setProperty("http://xml.org/sax/properties/lexical-handler", this); reader.setErrorHandler(this); reader.setEntityResolver(this); }
From source file:org.lnicholls.galleon.apps.iTunes.PlaylistParser.java
public PlaylistParser(String path) { try {// w ww . j av a2 s . c o m //path = "D:/galleon/iTunes Music Library.xml"; ArrayList currentPlaylists = new ArrayList(); // Read all tracks XMLReader trackReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); TrackParser trackParser = new TrackParser(); trackReader.setContentHandler(trackParser); trackReader.setErrorHandler(trackParser); trackReader.setFeature("http://xml.org/sax/features/validation", false); File file = new File(path); if (file.exists()) { InputStream inputStream = Tools.getInputStream(file); trackReader.parse(new InputSource(inputStream)); inputStream.close(); } // Read all playlists XMLReader listReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); ListParser listParser = new ListParser(currentPlaylists); listReader.setContentHandler(listParser); listReader.setErrorHandler(listParser); listReader.setFeature("http://xml.org/sax/features/validation", false); file = new File(path); if (file.exists()) { InputStream inputStream = Tools.getInputStream(file); listReader.parse(new InputSource(inputStream)); inputStream.close(); } // Remove old playlists List list = PlaylistsManager.listAll(); if (list != null && list.size() > 0) { Iterator playlistIterator = list.iterator(); while (playlistIterator.hasNext()) { Playlists playlist = (Playlists) playlistIterator.next(); boolean found = false; Iterator iterator = currentPlaylists.iterator(); while (iterator.hasNext()) { String externalId = (String) iterator.next(); if (externalId.equals(playlist.getExternalId())) { found = true; break; } } if (!found) { PlaylistsManager.deletePlaylistsTracks(playlist); PlaylistsManager.deletePlaylists(playlist); log.debug("Removed playlist: " + playlist.getTitle()); } } list.clear(); } currentPlaylists.clear(); } catch (IOException ex) { Tools.logException(PlaylistParser.class, ex); } catch (SAXException ex) { Tools.logException(PlaylistParser.class, ex); } catch (Exception ex) { Tools.logException(PlaylistParser.class, ex); } }
From source file:org.olat.ims.qti.qpool.ItemFileResourceValidator.java
private boolean validateDocument(Document in) { try {/*from w w w. j a va 2 s . c o m*/ SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); factory.setNamespaceAware(true); SimpleErrorHandler errorHandler = new SimpleErrorHandler(); ItemContentHandler contentHandler = new ItemContentHandler(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setEntityResolver(new IMSEntityResolver()); reader.setErrorHandler(errorHandler); reader.setContentHandler(contentHandler); SAXValidator validator = new SAXValidator(reader); validator.validate(in); return errorHandler.isValid() && contentHandler.isItem(); } catch (ParserConfigurationException e) { return false; } catch (SAXException e) { return false; } catch (Exception e) { return false; } }
From source file:org.openbravo.test.webservice.BaseWSTest.java
/** * Validates the xml against the generated schema. * // w ww .j av a 2 s.c om * @param xml * the xml to validate */ protected void validateXML(String xml) { final Reader schemaReader = new StringReader(getXMLSchema()); final Reader xmlReader = new StringReader(xml); try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource(schemaReader) })); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(new SimpleErrorHandler()); reader.parse(new InputSource(xmlReader)); } catch (Exception e) { throw new OBException(e); } }
From source file:org.opencms.xml.CmsXmlUtils.java
/** * Validates the structure of a XML document contained in a byte array * with the DTD or XML schema used by the document.<p> * // w w w . jav a 2s. c om * @param xmlStream a source providing a XML document that should be validated * @param resolver the XML entity resolver to use * * @throws CmsXmlException if the validation fails */ public static void validateXmlStructure(InputStream xmlStream, EntityResolver resolver) throws CmsXmlException { XMLReader reader; try { reader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); } catch (SAXException e) { // xerces parser not available - no schema validation possible if (LOG.isWarnEnabled()) { LOG.warn(Messages.get().getBundle().key(Messages.LOG_VALIDATION_INIT_XERXES_SAX_READER_FAILED_0), e); } // no validation of the content is possible return; } // turn on validation try { reader.setFeature("http://xml.org/sax/features/validation", true); // turn on schema validation reader.setFeature("http://apache.org/xml/features/validation/schema", true); // configure namespace support reader.setFeature("http://xml.org/sax/features/namespaces", true); reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); } catch (SAXNotRecognizedException e) { // should not happen as Xerces 2 support this feature if (LOG.isWarnEnabled()) { LOG.warn(Messages.get().getBundle().key(Messages.LOG_SAX_READER_FEATURE_NOT_RECOGNIZED_0), e); } // no validation of the content is possible return; } catch (SAXNotSupportedException e) { // should not happen as Xerces 2 support this feature if (LOG.isWarnEnabled()) { LOG.warn(Messages.get().getBundle().key(Messages.LOG_SAX_READER_FEATURE_NOT_SUPPORTED_0), e); } // no validation of the content is possible return; } // add an error handler which turns any errors into XML CmsXmlValidationErrorHandler errorHandler = new CmsXmlValidationErrorHandler(); reader.setErrorHandler(errorHandler); if (resolver != null) { // set the resolver for the "opencms://" URIs reader.setEntityResolver(resolver); } try { reader.parse(new InputSource(xmlStream)); } catch (IOException e) { // should not happen since we read form a byte array if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_READ_XML_FROM_BYTE_ARR_FAILED_0), e); } return; } catch (SAXException e) { // should not happen since all errors are handled in the XML error handler if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_PARSE_SAX_EXC_0), e); } return; } if (errorHandler.getErrors().elements().size() > 0) { // there was at last one validation error, so throw an exception StringWriter out = new StringWriter(256); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(out, format); try { writer.write(errorHandler.getErrors()); writer.write(errorHandler.getWarnings()); writer.close(); } catch (IOException e) { // should not happen since we write to a StringWriter if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_STRINGWRITER_IO_EXC_0), e); } } // generate String from XML for display of document in error message throw new CmsXmlException(Messages.get().container(Messages.ERR_XML_VALIDATION_1, out.toString())); } }
From source file:org.openrdf.rio.rdfxml.RDFXMLParser.java
private void parse(InputSource inputSource) throws IOException, RDFParseException, RDFHandlerException { try {/*from ww w.ja v a 2 s . c o m*/ 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(); } }
From source file:org.pentaho.reporting.libraries.xmlns.parser.AbstractXmlResourceFactory.java
/** * Creates a resource by interpreting the data given in the resource-data object. If additional datastreams need to be * parsed, the provided resource manager should be used. This method parses the given resource-data as XML stream. * * @param manager the resource manager used for all resource loading. * @param data the resource-data from where the binary data is read. * @param context the resource context used to resolve relative resource paths. * @return the parsed result, never null. * @throws ResourceCreationException if the resource could not be parsed due to syntaxctial or logical errors in the * data. * @throws ResourceLoadingException if the resource could not be accessed from the physical storage. *//*w w w. j av a 2 s .c o m*/ public Resource create(final ResourceManager manager, final ResourceData data, final ResourceKey context) throws ResourceCreationException, ResourceLoadingException { try { final SAXParser parser = getParser(); final XMLReader reader = parser.getXMLReader(); final XmlFactoryModule[] rootHandlers = getModules(); if (rootHandlers.length == 0) { throw new ResourceCreationException( "There are no root-handlers registered for the factory for type " + getFactoryType()); } final ResourceDataInputSource input = new ResourceDataInputSource(data, manager); final ResourceKey contextKey; final long version; final ResourceKey targetKey = data.getKey(); if (context == null) { contextKey = targetKey; version = data.getVersion(manager); } else { contextKey = context; version = -1; } final RootXmlReadHandler handler = createRootHandler(manager, targetKey, rootHandlers, contextKey, version); final DefaultConfiguration parserConfiguration = handler.getParserConfiguration(); final URL value = manager.toURL(contextKey); if (value != null) { parserConfiguration.setConfigProperty(CONTENTBASE_KEY, value.toExternalForm()); } configureReader(reader, handler); reader.setContentHandler(handler); reader.setDTDHandler(handler); reader.setEntityResolver(handler.getEntityResolver()); reader.setErrorHandler(getErrorHandler()); final Map parameters = targetKey.getFactoryParameters(); final Iterator it = parameters.keySet().iterator(); while (it.hasNext()) { final Object o = it.next(); if (o instanceof FactoryParameterKey) { final FactoryParameterKey fpk = (FactoryParameterKey) o; handler.setHelperObject(fpk.getName(), parameters.get(fpk)); } } reader.parse(input); final Object createdProduct = finishResult(handler.getResult(), manager, data, contextKey); handler.getDependencyCollector().add(targetKey, data.getVersion(manager)); return createResource(targetKey, handler, createdProduct, getFactoryType()); } catch (ParserConfigurationException e) { throw new ResourceCreationException("Unable to initialize the XML-Parser", e); } catch (SAXException e) { throw new ResourceCreationException("Unable to parse the document: " + data.getKey(), e); } catch (IOException e) { throw new ResourceLoadingException("Unable to read the stream from document: " + data.getKey(), e); } }
From source file:org.pentaho.reporting.libraries.xmlns.parser.AbstractXmlResourceFactory.java
/** * A method to allow to invoke the parsing without accessing the LibLoader layer. The data to be parsed is held in the * given InputSource object./* ww w . j a v a 2s .c om*/ * * @param manager the resource manager used for all resource loading. * @param input the raw-data given as SAX-InputSource. * @param context the resource context used to resolve relative resource paths. * @param parameters the parse parameters. * @return the parsed result, never null. * @throws ResourceCreationException if the resource could not be parsed due to syntaxctial or logical errors in * the data. * @throws ResourceLoadingException if the resource could not be accessed from the physical storage. * @throws ResourceKeyCreationException if creating the context key failed. */ public Object parseDirectly(final ResourceManager manager, final InputSource input, final ResourceKey context, final Map parameters) throws ResourceKeyCreationException, ResourceCreationException, ResourceLoadingException { try { final SAXParser parser = getParser(); final XMLReader reader = parser.getXMLReader(); final ResourceKey targetKey = manager.createKey(EMPTY_DATA); final ResourceKey contextKey; if (context == null) { contextKey = targetKey; } else { contextKey = context; } final XmlFactoryModule[] rootHandlers = getModules(); final RootXmlReadHandler handler = createRootHandler(manager, targetKey, rootHandlers, contextKey, -1); final DefaultConfiguration parserConfiguration = handler.getParserConfiguration(); final URL value = manager.toURL(contextKey); if (value != null) { parserConfiguration.setConfigProperty(CONTENTBASE_KEY, value.toExternalForm()); } configureReader(reader, handler); reader.setContentHandler(handler); reader.setDTDHandler(handler); reader.setEntityResolver(handler.getEntityResolver()); reader.setErrorHandler(getErrorHandler()); final Iterator it = parameters.keySet().iterator(); while (it.hasNext()) { final Object o = it.next(); if (o instanceof FactoryParameterKey) { final FactoryParameterKey fpk = (FactoryParameterKey) o; handler.setHelperObject(fpk.getName(), parameters.get(fpk)); } } reader.parse(input); return finishResult(handler.getResult(), manager, new RawResourceData(targetKey), contextKey); } catch (ParserConfigurationException e) { throw new ResourceCreationException("Unable to initialize the XML-Parser", e); } catch (SAXException e) { throw new ResourceCreationException("Unable to parse the document", e); } catch (IOException e) { throw new ResourceLoadingException("Unable to read the stream", e); } }
From source file:org.plasma.sdo.helper.PlasmaXMLHelper.java
private void validateSAX(InputStream inputStream, String locationURI, XMLOptions options) throws IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true);// w ww .j av a 2 s . com factory.setNamespaceAware(true); SAXParser parser; try { factory.setFeature("http://xml.org/sax/features/validation", true); factory.setFeature("http://apache.org/xml/features/validation/schema", true); factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); parser = factory.newSAXParser(); try { parser.setProperty(XMLConstants.JAXP_SCHEMA_LANGUAGE, SchemaConstants.XMLSCHEMA_NAMESPACE_URI); } catch (SAXNotRecognizedException e) { log.warn("parses does not support JAXP 1.2"); } if (locationURI != null) { parser.setProperty(XMLConstants.JAXP_NO_NAMESPACE_SCHEMA_SOURCE, locationURI); } XMLReader xmlReader = parser.getXMLReader(); //xmlReader.setEntityResolver(new SchemaLoader()); if (options.getErrorHandler() == null) xmlReader.setErrorHandler(new DefaultErrorHandler(options)); else xmlReader.setErrorHandler(options.getErrorHandler()); if (log.isDebugEnabled()) log.debug("validating..."); xmlReader.parse(new InputSource(inputStream)); } catch (SAXNotRecognizedException e) { throw new PlasmaDataObjectException(e); } catch (SAXNotSupportedException e) { throw new PlasmaDataObjectException(e); } catch (ParserConfigurationException e) { throw new PlasmaDataObjectException(e); } catch (SAXException e) { throw new PlasmaDataObjectException(e); } }