List of usage examples for org.xml.sax ErrorHandler ErrorHandler
ErrorHandler
From source file:net.sourceforge.pmd.testframework.RuleTst.java
public RuleTst() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema;/*from www. j av a2s .co m*/ try { schema = schemaFactory.newSchema(RuleTst.class.getResource("/rule-tests_1_0_0.xsd")); dbf.setSchema(schema); dbf.setNamespaceAware(true); DocumentBuilder builder = dbf.newDocumentBuilder(); builder.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { throw exception; } @Override public void fatalError(SAXParseException exception) throws SAXException { throw exception; } @Override public void error(SAXParseException exception) throws SAXException { throw exception; } }); documentBuilder = builder; } catch (SAXException | ParserConfigurationException e) { throw new RuntimeException(e); } }
From source file:org.apache.beehive.netui.util.config.internal.catalog.CatalogParser.java
public CatalogConfig parse(final String resourcePath, final InputStream inputStream) { CatalogConfig catalogConfig = null;//from ww w . j av a2 s . c om InputStream xmlInputStream = null; InputStream xsdInputStream = null; try { xmlInputStream = inputStream; xsdInputStream = getClass().getClassLoader().getResourceAsStream(CONFIG_SCHEMA); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(true); dbf.setNamespaceAware(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); dbf.setAttribute(JAXP_SCHEMA_SOURCE, xsdInputStream); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) { LOG.info("Validation warning validating config file \"" + resourcePath + "\" against XML Schema \"" + CONFIG_SCHEMA); } public void error(SAXParseException exception) { throw new RuntimeException("Validation errors occurred parsing the config file \"" + resourcePath + "\". Cause: " + exception, exception); } public void fatalError(SAXParseException exception) { throw new RuntimeException("Validation errors occurred parsing the config file \"" + resourcePath + "\". Cause: " + exception, exception); } }); db.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) { if (systemId.endsWith("/catalog-config.xsd")) { InputStream inputStream = getClass().getClassLoader().getResourceAsStream(CONFIG_SCHEMA); return new InputSource(inputStream); } else return null; } }); Document document = db.parse(xmlInputStream); Element catalogElement = document.getDocumentElement(); catalogConfig = parse(catalogElement); } catch (ParserConfigurationException e) { throw new RuntimeException("Error occurred parsing the config file \"" + resourcePath + "\"", e); } catch (IOException e) { throw new RuntimeException("Error occurred parsing the config file \"" + resourcePath + "\"", e); } catch (SAXException e) { throw new RuntimeException("Error occurred parsing the config file \"" + resourcePath + "\"", e); } finally { try { if (xsdInputStream != null) xsdInputStream.close(); } catch (IOException e) { } } return catalogConfig; }
From source file:org.apache.felix.karaf.deployer.blueprint.BlueprintDeploymentListener.java
protected Document parse(File artifact) throws Exception { if (dbf == null) { dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);//from www. j a v a 2 s . c o m } DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { } public void error(SAXParseException exception) throws SAXException { } public void fatalError(SAXParseException exception) throws SAXException { throw exception; } }); return db.parse(artifact); }
From source file:org.apache.nifi.fingerprint.FingerprintFactoryTest.java
private DocumentBuilder getValidatingDocumentBuilder() { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema; try {/*from w w w . jav a2 s . c o m*/ schema = schemaFactory.newSchema(FingerprintFactory.class.getResource(FLOW_CONFIG_XSD)); } catch (final Exception e) { throw new RuntimeException("Failed to parse schema for file flow configuration.", e); } try { documentBuilderFactory.setSchema(schema); DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder(); docBuilder.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException e) throws SAXException { throw e; } @Override public void error(SAXParseException e) throws SAXException { throw e; } @Override public void fatalError(SAXParseException e) throws SAXException { throw e; } }); return docBuilder; } catch (final Exception e) { throw new RuntimeException("Failed to create document builder for flow configuration.", e); } }
From source file:org.apache.servicemix.jbi.deployer.descriptor.DescriptorFactory.java
/** * Build a jbi descriptor from the specified binary data. * The descriptor is validated against the schema, but no * semantic validation is performed./* w ww . jav a 2s . c om*/ * * @param bytes hold the content of the JBI descriptor xml document * @return the Descriptor object */ public static Descriptor buildDescriptor(final byte[] bytes) { try { // Validate descriptor SchemaFactory schemaFactory = SchemaFactory.newInstance(XSD_SCHEMA_LANGUAGE); Schema schema = schemaFactory.newSchema(DescriptorFactory.class.getResource(JBI_DESCRIPTOR_XSD)); Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { //log.debug("Validation warning on " + url + ": " + exception); } public void error(SAXParseException exception) throws SAXException { //log.info("Validation error on " + url + ": " + exception); } public void fatalError(SAXParseException exception) throws SAXException { throw exception; } }); validator.validate(new StreamSource(new ByteArrayInputStream(bytes))); // Parse descriptor DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.parse(new ByteArrayInputStream(bytes)); Element jbi = doc.getDocumentElement(); Descriptor desc = new Descriptor(); desc.setVersion(Double.parseDouble(getAttribute(jbi, VERSION))); Element child = getFirstChildElement(jbi); if (COMPONENT.equals(child.getLocalName())) { ComponentDesc component = new ComponentDesc(); component.setType(child.getAttribute(TYPE)); component.setComponentClassLoaderDelegation(getAttribute(child, COMPONENT_CLASS_LOADER_DELEGATION)); component.setBootstrapClassLoaderDelegation(getAttribute(child, BOOTSTRAP_CLASS_LOADER_DELEGATION)); List<SharedLibraryList> sls = new ArrayList<SharedLibraryList>(); DocumentFragment ext = null; for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (IDENTIFICATION.equals(e.getLocalName())) { component.setIdentification(readIdentification(e)); } else if (COMPONENT_CLASS_NAME.equals(e.getLocalName())) { component.setComponentClassName(getText(e)); component.setDescription(getAttribute(e, DESCRIPTION)); } else if (COMPONENT_CLASS_PATH.equals(e.getLocalName())) { ClassPath componentClassPath = new ClassPath(); ArrayList<String> l = new ArrayList<String>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (PATH_ELEMENT.equals(e2.getLocalName())) { l.add(getText(e2)); } } componentClassPath.setPathList(l); component.setComponentClassPath(componentClassPath); } else if (BOOTSTRAP_CLASS_NAME.equals(e.getLocalName())) { component.setBootstrapClassName(getText(e)); } else if (BOOTSTRAP_CLASS_PATH.equals(e.getLocalName())) { ClassPath bootstrapClassPath = new ClassPath(); ArrayList<String> l = new ArrayList<String>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (PATH_ELEMENT.equals(e2.getLocalName())) { l.add(getText(e2)); } } bootstrapClassPath.setPathList(l); component.setBootstrapClassPath(bootstrapClassPath); } else if (SHARED_LIBRARY.equals(e.getLocalName())) { SharedLibraryList sl = new SharedLibraryList(); sl.setName(getText(e)); sl.setVersion(getAttribute(e, VERSION)); sls.add(sl); } else { if (ext == null) { ext = doc.createDocumentFragment(); } ext.appendChild(e); } } component.setSharedLibraries(sls.toArray(new SharedLibraryList[sls.size()])); if (ext != null) { InstallationDescriptorExtension descriptorExtension = new InstallationDescriptorExtension(); descriptorExtension.setDescriptorExtension(ext); component.setDescriptorExtension(descriptorExtension); } desc.setComponent(component); } else if (SHARED_LIBRARY.equals(child.getLocalName())) { SharedLibraryDesc sharedLibrary = new SharedLibraryDesc(); sharedLibrary.setClassLoaderDelegation(getAttribute(child, CLASS_LOADER_DELEGATION)); sharedLibrary.setVersion(getAttribute(child, VERSION)); for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (IDENTIFICATION.equals(e.getLocalName())) { sharedLibrary.setIdentification(readIdentification(e)); } else if (SHARED_LIBRARY_CLASS_PATH.equals(e.getLocalName())) { ClassPath sharedLibraryClassPath = new ClassPath(); ArrayList<String> l = new ArrayList<String>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (PATH_ELEMENT.equals(e2.getLocalName())) { l.add(getText(e2)); } } sharedLibraryClassPath.setPathList(l); sharedLibrary.setSharedLibraryClassPath(sharedLibraryClassPath); } } desc.setSharedLibrary(sharedLibrary); } else if (SERVICE_ASSEMBLY.equals(child.getLocalName())) { ServiceAssemblyDesc serviceAssembly = new ServiceAssemblyDesc(); ArrayList<ServiceUnitDesc> sus = new ArrayList<ServiceUnitDesc>(); for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (IDENTIFICATION.equals(e.getLocalName())) { serviceAssembly.setIdentification(readIdentification(e)); } else if (SERVICE_UNIT.equals(e.getLocalName())) { ServiceUnitDesc su = new ServiceUnitDesc(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (IDENTIFICATION.equals(e2.getLocalName())) { su.setIdentification(readIdentification(e2)); } else if (TARGET.equals(e2.getLocalName())) { Target target = new Target(); for (Element e3 = getFirstChildElement(e2); e3 != null; e3 = getNextSiblingElement( e3)) { if (ARTIFACTS_ZIP.equals(e3.getLocalName())) { target.setArtifactsZip(getText(e3)); } else if (COMPONENT_NAME.equals(e3.getLocalName())) { target.setComponentName(getText(e3)); } } su.setTarget(target); } } sus.add(su); } else if (CONNECTIONS.equals(e.getLocalName())) { Connections connections = new Connections(); ArrayList<Connection> cns = new ArrayList<Connection>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (CONNECTION.equals(e2.getLocalName())) { Connection cn = new Connection(); for (Element e3 = getFirstChildElement(e2); e3 != null; e3 = getNextSiblingElement( e3)) { if (CONSUMER.equals(e3.getLocalName())) { Consumer consumer = new Consumer(); consumer.setInterfaceName(readAttributeQName(e3, INTERFACE_NAME)); consumer.setServiceName(readAttributeQName(e3, SERVICE_NAME)); consumer.setEndpointName(getAttribute(e3, ENDPOINT_NAME)); cn.setConsumer(consumer); } else if (PROVIDER.equals(e3.getLocalName())) { Provider provider = new Provider(); provider.setServiceName(readAttributeQName(e3, SERVICE_NAME)); provider.setEndpointName(getAttribute(e3, ENDPOINT_NAME)); cn.setProvider(provider); } } cns.add(cn); } } connections.setConnections(cns.toArray(new Connection[cns.size()])); serviceAssembly.setConnections(connections); } } serviceAssembly.setServiceUnits(sus.toArray(new ServiceUnitDesc[sus.size()])); desc.setServiceAssembly(serviceAssembly); } else if (SERVICES.equals(child.getLocalName())) { Services services = new Services(); services.setBindingComponent( Boolean.valueOf(getAttribute(child, BINDING_COMPONENT)).booleanValue()); ArrayList<Provides> provides = new ArrayList<Provides>(); ArrayList<Consumes> consumes = new ArrayList<Consumes>(); for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (PROVIDES.equals(e.getLocalName())) { Provides p = new Provides(); p.setInterfaceName(readAttributeQName(e, INTERFACE_NAME)); p.setServiceName(readAttributeQName(e, SERVICE_NAME)); p.setEndpointName(getAttribute(e, ENDPOINT_NAME)); provides.add(p); } else if (CONSUMES.equals(e.getLocalName())) { Consumes c = new Consumes(); c.setInterfaceName(readAttributeQName(e, INTERFACE_NAME)); c.setServiceName(readAttributeQName(e, SERVICE_NAME)); c.setEndpointName(getAttribute(e, ENDPOINT_NAME)); c.setLinkType(getAttribute(e, LINK_TYPE)); consumes.add(c); } } services.setProvides(provides.toArray(new Provides[provides.size()])); services.setConsumes(consumes.toArray(new Consumes[consumes.size()])); desc.setServices(services); } checkDescriptor(desc); return desc; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.synapse.format.syslog.SyslogMessageBuilderTest.java
private SyslogMessage test(String message) throws Exception { MessageContext msgContext = new MessageContext(); ByteArrayInputStream in = new ByteArrayInputStream(message.getBytes("us-ascii")); OMElement element = new SyslogMessageBuilder().processDocument(in, null, msgContext); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema( new StreamSource(SyslogMessageBuilderTest.class.getResource("schema.xsd").toExternalForm())); Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandler() { public void error(SAXParseException exception) throws SAXException { throw exception; }/*from w ww . j a va 2 s . c o m*/ public void fatalError(SAXParseException exception) throws SAXException { throw exception; } public void warning(SAXParseException exception) throws SAXException { throw exception; } }); validator.validate(new OMSource(element)); String pidString = element.getAttributeValue(new QName(SyslogConstants.PID)); return new SyslogMessage(element.getAttributeValue(new QName(SyslogConstants.FACILITY)), element.getAttributeValue(new QName(SyslogConstants.SEVERITY)), element.getAttributeValue(new QName(SyslogConstants.TAG)), pidString == null ? -1 : Integer.parseInt(pidString), element.getText()); }
From source file:org.bibsonomy.importer.bookmark.service.DeliciousImporter.java
/** * Method opens a connection and parses the retrieved InputStream with a JAXP parser. * @return The from the parse call returned Document Object * @throws IOException/* w w w . ja va 2s .c om*/ */ private Document getDocument() throws IOException { final URLConnection connection = apiURL.openConnection(); connection.setRequestProperty(HEADER_USER_AGENT, userAgent); connection.setRequestProperty(HEADER_AUTHORIZATION, encodeForAuthorization()); final InputStream inputStream = connection.getInputStream(); // Get a JAXP parser factory object final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // Tell the factory what kind of parser we want dbf.setValidating(false); // Use the factory to get a JAXP parser object final DocumentBuilder parser; try { parser = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IOException(e); } // Tell the parser how to handle errors. Note that in the JAXP API, // DOM parsers rely on the SAX API for error handling parser.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException e) { log.warn(e); } public void error(SAXParseException e) { log.error(e); } public void fatalError(SAXParseException e) throws SAXException { log.fatal(e); throw e; // re-throw the error } }); // Finally, use the JAXP parser to parse the file. // This call returns a Document object. final Document document; try { document = parser.parse(inputStream); } catch (SAXException e) { throw new IOException(e); } inputStream.close(); return document; }
From source file:org.bibsonomy.importer.bookmark.service.DeliciousV2Importer.java
/** * Method opens a connection and parses the retrieved InputStream with a JAXP parser. * @return The from the parse call returned Document Object * @throws IOException//from ww w. ja v a 2s . c o m */ private static Document getDocument(final InputStream inputStream) throws IOException { /* * TODO: this is copied code */ // Get a JAXP parser factory object final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // Tell the factory what kind of parser we want dbf.setValidating(false); // Use the factory to get a JAXP parser object final DocumentBuilder parser; try { parser = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IOException(e); } // Tell the parser how to handle errors. Note that in the JAXP API, // DOM parsers rely on the SAX API for error handling parser.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException e) { log.warn(e); } public void error(SAXParseException e) { log.error(e); } public void fatalError(SAXParseException e) throws SAXException { log.fatal(e); throw e; // re-throw the error } }); // Finally, use the JAXP parser to parse the file. // This call returns a Document object. final Document document; try { document = parser.parse(inputStream); } catch (SAXException e) { throw new IOException(e); } inputStream.close(); return document; }
From source file:org.bungeni.editor.system.ValidateConfiguration.java
public List<SAXParseException> validate(File xmlFile, ConfigInfo config) { final List<SAXParseException> exceptions = new LinkedList<SAXParseException>(); try {//from ww w . j a v a 2 s.c o m String pathToXSD = config.getXsdPath(); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver(new ResourceResolver()); Schema schema = factory.newSchema(new StreamSource(config.getXsdInputStream())); Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { exceptions.add(exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { exceptions.add(exception); } @Override public void error(SAXParseException exception) throws SAXException { exceptions.add(exception); } }); StreamSource streamXML = new StreamSource(xmlFile); validator.validate(streamXML); } catch (SAXException ex) { log.error("Error during validation", ex); } catch (IOException ex) { log.error("Error during validation", ex); } finally { } return exceptions; }
From source file:org.datacleaner.cli.MainTest.java
public void testWriteHtmlToFile() throws Throwable { String filename = "target/test_write_html_to_file.html"; Main.main(// w w w . j av a 2 s . c o m ("-conf src/test/resources/cli-examples/conf.xml -job src/test/resources/cli-examples/employees_job.xml -of " + filename + " -ot HTML").split(" ")); File file = new File(filename); assertTrue(file.exists()); { String result = FileHelper.readFileAsString(file); String[] lines = result.split("\n"); assertEquals("<html>", lines[1]); } InputStream in = FileHelper.getInputStream(file); try { // parse it with validator.nu for HTML correctness final HtmlParser htmlParser = new HtmlParser(XmlViolationPolicy.FATAL); final AtomicInteger elementCounter = new AtomicInteger(); htmlParser.setContentHandler(new DefaultHandler() { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { elementCounter.incrementAndGet(); } }); final List<Exception> warningsAndErrors = new ArrayList<Exception>(); htmlParser.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { System.err.println("Warning: " + exception.getMessage()); warningsAndErrors.add(exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { System.out.println("Fatal error: " + exception.getMessage()); throw exception; } @Override public void error(SAXParseException exception) throws SAXException { System.err.println("Error: " + exception.getMessage()); warningsAndErrors.add(exception); } }); htmlParser.parse(new InputSource(in)); // the output has approx 3600 XML elements int elementCount = elementCounter.get(); assertTrue("Element count: " + elementCount, elementCount > 3000); assertTrue("Element count: " + elementCount, elementCount < 5000); if (!warningsAndErrors.isEmpty()) { for (Exception error : warningsAndErrors) { String message = error.getMessage(); if (message.startsWith("No explicit character encoding declaration has been seen yet") || message.startsWith("The character encoding of the document was not declared.")) { // ignore/accept this one continue; } error.printStackTrace(); fail("Got " + warningsAndErrors.size() + " warnings and errors, see log for details"); } } } finally { in.close(); } }