List of usage examples for org.xml.sax ErrorHandler ErrorHandler
ErrorHandler
From source file:org.dita.dost.platform.Integrator.java
/** * Default Constructor./*from w ww.j av a 2s . c om*/ */ public Integrator(final File ditaDir) { this.ditaDir = ditaDir; pluginTable = new HashMap<>(16); descSet = new HashSet<>(16); loadedPlugin = new HashSet<>(16); featureTable = new Hashtable<>(16); extensionPoints = new HashSet<>(); try { reader = XMLUtils.getXMLReader(); } catch (final Exception e) { throw new RuntimeException("Failed to initialize XML parser: " + e.getMessage(), e); } reader.setErrorHandler(new ErrorHandler() { @Override public void error(final SAXParseException e) throws SAXException { throw e; } @Override public void fatalError(final SAXParseException e) throws SAXException { throw e; } @Override public void warning(final SAXParseException e) throws SAXException { throw e; } }); parser = new PluginParser(ditaDir); try { pluginsDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); } catch (final ParserConfigurationException e) { throw new RuntimeException("Failed to create compound document: " + e.getMessage(), e); } // pluginsDoc.setResult(new StreamResult(new File(ditaDir, RESOURCES_DIR + File.separator + "plugins.xml"))); }
From source file:org.drools.guvnor.server.jaxrs.CategoryResourceIntegrationTest.java
public Map<String, Category> fromXMLToCategoriesMap(String xml) { try {//from w w w .jav a 2s . com DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); final List<String> errors = new ArrayList<String>(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { java.util.logging.Logger.getLogger(Translator.class.getName()).log(Level.WARNING, "Warning parsing categories from Guvnor", exception); } public void error(SAXParseException exception) throws SAXException { java.util.logging.Logger.getLogger(Translator.class.getName()).log(Level.SEVERE, "Error parsing categories from Guvnor", exception); errors.add(exception.getMessage()); } public void fatalError(SAXParseException exception) throws SAXException { java.util.logging.Logger.getLogger(Translator.class.getName()).log(Level.SEVERE, "Error parsing categories from Guvnor", exception); errors.add(exception.getMessage()); } }); org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes())); if (!errors.isEmpty()) { throw new IllegalStateException( "Error parsing categories from guvnor. Check the log for errors' details."); } Map<String, Category> categories = new HashMap<String, Category>(); //convert all catergories and add them to the list NodeList categoriesList = doc.getElementsByTagName("category"); for (int i = 0; i < categoriesList.getLength(); i++) { Element element = (Element) categoriesList.item(i); Category category = new Category(); NodeList pathNodes = element.getElementsByTagName("path"); if (pathNodes.getLength() != 1) { throw new IllegalStateException( "Malformed category. Expected 1 <path> tag, but found " + pathNodes.getLength()); } Node pathNode = pathNodes.item(0); category.setPath(pathNode.getTextContent()); NodeList refLinkNodes = element.getElementsByTagName("refLink"); if (refLinkNodes.getLength() != 1) { throw new IllegalStateException( "Malformed category. Expected 1 <refLink> tag, but found " + refLinkNodes.getLength()); } Node refLinkNode = refLinkNodes.item(0); try { category.setRefLink(new URI(refLinkNode.getTextContent())); } catch (URISyntaxException e) { throw new RuntimeException("Error parsing categories xml", e); } categories.put(category.getPath(), category); } return categories; } catch (SAXException ex) { throw new RuntimeException("Error parsing categories xml", ex); } catch (IOException ex) { throw new RuntimeException("Error parsing categories xml", ex); } catch (ParserConfigurationException ex) { throw new RuntimeException("Error parsing categories xml", ex); } }
From source file:org.easyrec.util.core.Web.java
/** * This procedure extracts the values//from w w w .jav a2 s. c om * of the <name>-Tags of a given Xml file into a list of Strings. * e.g. * <name>hanso</name> * <name>stritzi</name> * <p/> * --> {"hansi","stritzi"} * * @param apiURL String * @param tagName String * @return a list of strings */ @SuppressWarnings({ "UnusedDeclaration" }) public static List<String> getInnerHTMLfromTags(String apiURL, String tagName) { List<String> innerHTMLList = new ArrayList<String>(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; try { db = dbf.newDocumentBuilder(); db.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException e) throws SAXException { } public void error(SAXParseException e) throws SAXException { } public void fatalError(SAXParseException e) throws SAXException { } }); Document doc = db.parse(apiURL.replaceAll(" ", "%20")); NodeList tagNodes = doc.getElementsByTagName(tagName); for (int i = 0; i < tagNodes.getLength(); i++) { innerHTMLList.add(tagNodes.item(i).getTextContent()); } } catch (ParserConfigurationException e1) { logger.warn("An error occurred!", e1); } catch (SAXException e) { logger.warn("An error occurred!", e); } catch (IOException e) { logger.warn("An error occurred!", e); } return innerHTMLList; }
From source file:org.easyrec.utils.Web.java
/** * This procedure extracts the values/*from w w w .j a v a 2s.co m*/ * of the <name>-Tags of a given Xml file into a list of Strings. * e.g. * <name>hanso</name> * <name>stritzi</name> * <p/> * --> {"hansi","stritzi"} * * @param apiURL String * @param tagName String * @return a list of strings */ @SuppressWarnings({ "UnusedDeclaration" }) public static List<String> getInnerHTMLfromTags(String apiURL, String tagName) { List<String> innerHTMLList = new ArrayList<String>(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; try { db = dbf.newDocumentBuilder(); db.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException e) throws SAXException { } public void error(SAXParseException e) throws SAXException { } public void fatalError(SAXParseException e) throws SAXException { } }); Document doc = db.parse(apiURL.replaceAll(" ", "%20")); NodeList tagNodes = doc.getElementsByTagName(tagName); for (int i = 0; i < tagNodes.getLength(); i++) { innerHTMLList.add(tagNodes.item(i).getTextContent()); } } catch (ParserConfigurationException e1) { e1.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return innerHTMLList; }
From source file:org.eobjects.analyzer.cli.MainTest.java
public void testWriteHtmlToFile() throws Throwable { String filename = "target/test_write_html_to_file.html"; Main.main(("-conf examples/conf.xml -job examples/employees_job.xml -of " + filename + " -ot HTML") .split(" ")); File file = new File(filename); assertTrue(file.exists());//from ww w .j a v a 2 s . c o m { 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) { if (error.getMessage() .startsWith("No explicit character encoding declaration has been seen yet")) { // ignore/accept this one continue; } error.printStackTrace(); fail("Got " + warningsAndErrors.size() + " warnings and errors, see log for details"); } } } finally { in.close(); } }
From source file:org.fosstrak.epcis.repository.capture.CaptureOperationsModule.java
/** * Parses the input into a DOM. If a schema is given, the input is also * validated against this schema. The schema may be null. *//* w w w . ja va 2s. c om*/ private Document parseInput(InputStream in, Schema schema) throws InternalBusinessException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); factory.setSchema(schema); try { DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException e) throws SAXException { LOG.warn("warning while parsing XML input: " + e.getMessage()); } public void fatalError(SAXParseException e) throws SAXException { LOG.error("non-recovarable error while parsing XML input: " + e.getMessage()); throw e; } public void error(SAXParseException e) throws SAXException { LOG.error("error while parsing XML input: " + e.getMessage()); throw e; } }); Document document = builder.parse(in); LOG.debug("payload successfully parsed as XML document"); if (LOG.isDebugEnabled()) { logDocument(document); } return document; } catch (ParserConfigurationException e) { throw new InternalBusinessException("unable to configure document builder to parse XML input", e); } }
From source file:org.geoserver.test.GeoServerAbstractTestSupport.java
/** * Given a dom and a schema, checks that the dom validates against the schema * of the validation errors instead// www .j ava 2 s .co m * @param validationErrors * @throws IOException * @throws SAXException */ protected void checkValidationErrors(Document dom, Schema schema) throws SAXException, IOException { final Validator validator = schema.newValidator(); final List<Exception> validationErrors = new ArrayList<Exception>(); validator.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { System.out.println(exception.getMessage()); } public void fatalError(SAXParseException exception) throws SAXException { validationErrors.add(exception); } public void error(SAXParseException exception) throws SAXException { validationErrors.add(exception); } }); validator.validate(new DOMSource(dom)); if (validationErrors != null && validationErrors.size() > 0) { StringBuilder sb = new StringBuilder(); for (Exception ve : validationErrors) { sb.append(ve.getMessage()).append("\n"); } fail(sb.toString()); } }
From source file:org.jboss.cdi.tck.test.shrinkwrap.descriptors.ejb.EjbJarDescriptorBuilderTest.java
@Test public void testDescriptorIsValid() throws ParserConfigurationException, SAXException, DescriptorExportException, IOException { EjbJarDescriptor ejbJarDescriptor = new EjbJarDescriptorBuilder().messageDrivenBeans( newMessageDriven("TestQueue", QueueMessageDrivenBean.class.getName()) .addActivationConfigProperty("acknowledgeMode", "Auto-acknowledge") .addActivationConfigProperty("destinationType", "javax.jms.Queue") .addActivationConfigProperty("destinationLookup", "test_queue"), newMessageDriven("TestTopic", TopicMessageDrivenBean.class.getName()) .addActivationConfigProperty("acknowledgeMode", "Auto-acknowledge") .addActivationConfigProperty("destinationType", "javax.jms.Topic") .addActivationConfigProperty("destinationLookup", "test_topic")) .build();/*from ww w . j av a2 s . c om*/ SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setResourceResolver(new LSResourceResolver() { @Override public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { try { if (systemId.startsWith("http")) { // Ugly workaround for xml.xsd systemId = StringUtils.substringAfterLast(systemId, "/"); } return new Input(publicId, systemId, new FileInputStream(new File("src/test/resources/xsd", systemId))); } catch (FileNotFoundException e) { throw new IllegalStateException(); } } }); schemaFactory.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { } @Override public void fatalError(SAXParseException exception) throws SAXException { throw exception; } @Override public void error(SAXParseException exception) throws SAXException { throw exception; } }); Source schemaFile = new StreamSource( new FileInputStream(new File("src/test/resources/xsd", "ejb-jar_3_1.xsd"))); Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); validator .validate(new StreamSource(new ByteArrayInputStream(ejbJarDescriptor.exportAsString().getBytes()))); }
From source file:org.jboss.dashboard.ui.panel.help.PanelHelpManager.java
/** * Convert given input stream to a Document. * * @param is// w w w . j a va 2 s . c om * @return * @throws org.xml.sax.SAXException * @throws java.io.IOException */ protected Document getDocument(InputStream is) throws SAXException, IOException { URL schemaUrl = getClass().getResource("help.xsd"); if (schemaUrl == null) log.error("Could not find org.jboss.dashboard.ui.panel.help.help.xsd]. Used [" + getClass().getClassLoader() + "] class loader in the search."); else log.debug("URL to org.jboss.dashboard.ui.panel.help.help.xsd is [" + schemaUrl.toString() + "]."); String schema = schemaUrl.toString(); // Create a DOMParser DOMParser parser = new DOMParser(); // Set the validation feature parser.setFeature("http://xml.org/sax/features/validation", true); // Set the schema validation feature parser.setFeature("http://apache.org/xml/features/validation/schema", true); // Set schema full grammar checking parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); // Disable whitespaces parser.setFeature("http://apache.org/xml/features/dom/include-ignorable-whitespace", false); // Set schema location parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", schema); // Set the error handler parser.setErrorHandler(new ErrorHandler() { public void error(SAXParseException exception) throws SAXParseException { throw exception; } public void fatalError(SAXParseException exception) throws SAXParseException { throw exception; } public void warning(SAXParseException exception) { } }); // Parse the XML document parser.parse(new InputSource(is)); return parser.getDocument(); }
From source file:org.jboss.dashboard.workspace.export.structure.ImportResult.java
protected void load(InputStream is) throws IOException, ParserConfigurationException, SAXException, SAXNotRecognizedException { URL schemaUrl = getClass().getResource("workspace.xsd"); if (schemaUrl == null) log.fatal("Could not find [org.jboss.dashboard.workspace.export.workspace.xsd]. Used [" + getClass().getClassLoader() + "] class loader in the search."); else//ww w. j a va 2 s .co m log.debug( "URL to org.jboss.dashboard.workspace.export.workspace.xsd is [" + schemaUrl.toString() + "]."); String schema = schemaUrl.toString(); //Create a DOMParser DOMParser parser = new DOMParser(); //Set the validation feature parser.setFeature("http://xml.org/sax/features/validation", true); //Set the schema validation feature parser.setFeature("http://apache.org/xml/features/validation/schema", true); //Set schema full grammar checking parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); //Disable whitespaces parser.setFeature("http://apache.org/xml/features/dom/include-ignorable-whitespace", false); //Set schema location parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", schema); //Set the error handler parser.setErrorHandler(new ErrorHandler() { public void error(SAXParseException exception) throws SAXParseException { throw exception; } public void fatalError(SAXParseException exception) throws SAXParseException { throw exception; } public void warning(SAXParseException exception) { /*getWarnings().add(exception.getMessage()); getWarningArguments().add(new Object[]{exception});*/ } }); // Put it in a byte array before because the parser closes the stream. ByteArrayOutputStream bos = new ByteArrayOutputStream(is.available()); int byteRead; while ((byteRead = is.read()) != -1) { bos.write(byteRead); } //Parse the XML document parser.parse(new InputSource(new ByteArrayInputStream(bos.toByteArray()))); Document doc = parser.getDocument(); init(doc); }