Example usage for org.xml.sax ErrorHandler ErrorHandler

List of usage examples for org.xml.sax ErrorHandler ErrorHandler

Introduction

In this page you can find the example usage for org.xml.sax ErrorHandler ErrorHandler.

Prototype

ErrorHandler

Source Link

Usage

From source file:Main.java

/**
 * Check whether a DOM tree is valid according to a schema. Example of
 * usage:/* ww w . j a v a  2s.co  m*/
 * <pre>
 * Element fragment = ...;
 * SchemaFactory f = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
 * Schema s = f.newSchema(This.class.getResource("something.xsd"));
 * try {
 *     XMLUtil.validate(fragment, s);
 *     // valid
 * } catch (SAXException x) {
 *     // invalid
 * }
 * </pre>
 *
 * @param data   a DOM tree
 * @param schema a parsed schema
 * @throws SAXException if validation failed
 * @since org.openide.util 7.17
 */
public static void validate(Element data, Schema schema) throws SAXException {
    Validator v = schema.newValidator();
    final SAXException[] error = { null };
    v.setErrorHandler(new ErrorHandler() {
        @Override
        public void warning(SAXParseException x) throws SAXException {
        }

        @Override
        public void error(SAXParseException x) throws SAXException {
            // Just rethrowing it is bad because it will also print it to stderr.
            error[0] = x;
        }

        @Override
        public void fatalError(SAXParseException x) throws SAXException {
            error[0] = x;
        }
    });
    try {
        v.validate(new DOMSource(fixupAttrs(data)));
    } catch (IOException x) {
        assert false : x;
    }
    if (error[0] != null) {
        throw error[0];
    }
}

From source file:cl.vmetrix.operation.persistence.XmlValidator.java

/**
 * The method validatorXMLstg determinate if the String XML is correct. 
 * @return a boolean (true or false) to indicate if the XML is correct.
 * @param xml is the String XML to validate against XSD Schema
 * @throws SAXException//w  w  w  .j a v a2  s  .c o m
 * @throws IOException
 */

public boolean validateXMLstg(String xml) throws SAXException, IOException {
    String rpta = "";

    boolean validation = true;
    try {

        xml = new String(xml.getBytes("UTF-8"));

        //         System.out.println("---> XML in UTF-8: "+ xml);
        // convert String into InputStream
        InputStream is = new ByteArrayInputStream(xml.getBytes());

        Source xmlFile = new StreamSource(is);//new File("C:/XML/424437.xml"));

        // XSD schema
        String schemea = getFileSchema("operationSchema.xsd");

        InputStream sch = new ByteArrayInputStream(schemea.getBytes());

        Source schemaFile = new StreamSource(sch);//new File("main/resources/Operation.xsd"));

        // Preparing the schema
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(schemaFile);

        // Validator creation
        Validator validator = schema.newValidator();

        // DException handle of validator
        final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
        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);
            }
        });

        // XML validation
        validator.validate(xmlFile);

        // Validation result. If there are errors, detailed the exact position in the XML  and the error
        if (exceptions.size() == 0) {
            rpta = "XML IS VALID";
        } else {
            validation = false;
            StringBuffer sb = new StringBuffer();
            sb.append("XML IS INVALID");
            sb.append("\n");
            sb.append("NUMBER OF ERRORS: " + exceptions.size());
            sb.append("\n");
            for (int i = 0; i < exceptions.size(); i++) {
                i = i + 1;
                sb.append("Error # " + i + ":");
                sb.append("\n");
                i = i - 1;
                sb.append("    - Line: " + ((SAXParseException) exceptions.get(i)).getLineNumber());
                sb.append("\n");
                sb.append("    - Column: " + ((SAXParseException) exceptions.get(i)).getColumnNumber());
                sb.append("\n");
                sb.append("    - Error message: " + ((Throwable) exceptions.get(i)).getLocalizedMessage());
                sb.append("\n");
                sb.append("------------------------------");
            }
            rpta = sb.toString();
            logger.debug(rpta);

        }
    } catch (SAXException e) {
        logger.error("SAXException in XML validator: ", e);
        logger.debug(rpta);
        throw new SAXException(e);
    } catch (IOException e) {
        logger.error("IOException in XML validator: ", e);
        logger.debug(rpta);
        throw new IOException(e);
    }

    return validation;
}

From source file:com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptorParser.java

private static Digester initDigester() throws SAXNotRecognizedException, SAXNotSupportedException {
    Digester digester = new Digester();
    digester.setValidating(true);//from   www  .  ja v a 2 s. co m
    digester.setErrorHandler(new ErrorHandler() {
        @Override
        public void warning(SAXParseException exception) throws SAXException {
            throw new SAXException("XML Schema validation of Plugin Descriptor(plugin.xml) failed", exception);
        }

        @Override
        public void error(SAXParseException exception) throws SAXException {
            throw new SAXException("XML Schema validation of Plugin Descriptor(plugin.xml) failed", exception);
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            throw new SAXException("XML Schema validation of Plugin Descriptor(plugin.xml) failed", exception);
        }
    });
    digester.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            XMLConstants.W3C_XML_SCHEMA_NS_URI);
    digester.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
            GoPluginDescriptorParser.class.getResourceAsStream("/plugin-descriptor.xsd"));
    return digester;
}

From source file:ambit.data.qmrf.Qmrf_Xml_Pdf.java

public Qmrf_Xml_Pdf(String ttffont) {
    super();/*from w  ww  .  ja  va  2  s  .c om*/
    try {
        this.ttffont = ttffont;
        docBuilder = docBuilderFactory.newDocumentBuilder();
        nodeBuilder = docBuilderFactory.newDocumentBuilder();
        nodeBuilder.setErrorHandler(new ErrorHandler() {
            public void error(SAXParseException arg0) throws SAXException {
                throw new SAXException(arg0);
            }

            public void fatalError(SAXParseException arg0) throws SAXException {
                throw new SAXException(arg0);
            }

            public void warning(SAXParseException arg0) throws SAXException {
            }
        });
        //PRIndirectReference pri;
        //pri.
        try {

            baseFont = BaseFont.createFont(ttffont,
                    //"c:\\windows\\fonts\\times.ttf",
                    BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            System.out.println(ttffont);
        } catch (Exception x) {
            x.printStackTrace();
            baseFont = BaseFont.createFont("c:\\windows\\fonts\\times.ttf", BaseFont.IDENTITY_H,
                    BaseFont.EMBEDDED);
            System.out.println("Default font c:\\windows\\fonts\\times.ttf");
        }

        font = new Font(baseFont, 12);
        bfont = new Font(baseFont, 12, Font.BOLD);
    } catch (Exception x) {
        docBuilder = null;
    }

}

From source file:esg.security.yadis.XrdsDoc.java

protected Document parseXmlInput(String input) throws XrdsParseException {
    if (input == null)
        throw new XrdsParseException("No XML message set");

    try {//  w  w w.ja v a 2s  .c  om
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(true);
        dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        dbf.setAttribute(JAXP_SCHEMA_SOURCE, new Object[] { this.getClass().getResourceAsStream(XRD_SCHEMA),
                this.getClass().getResourceAsStream(XRDS_SCHEMA), });
        DocumentBuilder builder = dbf.newDocumentBuilder();
        builder.setErrorHandler(new ErrorHandler() {
            public void error(SAXParseException exception) throws SAXException {
                throw exception;
            }

            public void fatalError(SAXParseException exception) throws SAXException {
                throw exception;
            }

            public void warning(SAXParseException exception) throws SAXException {
                throw exception;
            }
        });

        return builder.parse(new ByteArrayInputStream(input.getBytes()));
    } catch (ParserConfigurationException e) {
        throw new XrdsParseException("Parser configuration error", e);
    } catch (SAXException e) {
        throw new XrdsParseException("Error parsing XML document", e);
    } catch (IOException e) {
        throw new XrdsParseException("Error reading XRDS document", e);
    }
}

From source file:com.smartitengineering.cms.spi.impl.type.validator.XMLSchemaBasedTypeValidator.java

private Document getDocumentForSource(InputStream contentTypeDef)
        throws SAXException, ParserConfigurationException, IOException {
    final DocumentBuilderFactory docBuilderFactor = DocumentBuilderFactory.newInstance();
    docBuilderFactor.setNamespaceAware(true);
    DocumentBuilder parser = docBuilderFactor.newDocumentBuilder();
    parser.setErrorHandler(new ErrorHandler() {

        public void warning(SAXParseException exception) throws SAXException {
            throw exception;
        }/* ww w  .j  a  v  a2s . c o m*/

        public void error(SAXParseException exception) throws SAXException {
            throw exception;
        }

        public void fatalError(SAXParseException exception) throws SAXException {
            throw exception;
        }
    });
    Document document = parser.parse(contentTypeDef);
    return document;
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.StreamsConfigSAXParser.java

/**
 * Validates configuration XML against XML defined XSD schema.
 *
 * @param config//  ww w.  j  a  va  2  s .c o m
 *            {@link InputStream} to get configuration data from
 * @return map of found validation errors
 * @throws SAXException
 *             if there was an error parsing the configuration
 * @throws IOException
 *             if there is an error reading the configuration data
 */
public static Map<OpLevel, List<SAXParseException>> validate(InputStream config)
        throws SAXException, IOException {
    final Map<OpLevel, List<SAXParseException>> validationErrors = new HashMap<>();
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema();
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.WARNING, exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.ERROR, exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.FATAL, exception);
            }

            private void handleValidationError(OpLevel level, SAXParseException exception) {
                List<SAXParseException> lErrorsList = validationErrors.get(level);
                if (lErrorsList == null) {
                    lErrorsList = new ArrayList<>();
                    validationErrors.put(level, lErrorsList);
                }

                lErrorsList.add(exception);
            }
        });
        validator.validate(new StreamSource(config));
    } finally {
        if (config.markSupported()) {
            config.reset();
        }
    }

    return validationErrors;
}

From source file:de.dfki.iui.mmds.dialogue.SiamStateMachine.java

private SCXML load(final String scxml) {

    ErrorHandler errHandler = new ErrorHandler() {
        @Override//  w w w.jav  a  2  s . c om
        public void error(SAXParseException e) throws SAXException {
            System.err.println(e.getMessage());

        }

        @Override
        public void fatalError(SAXParseException e) throws SAXException {
            System.err.println(e.getMessage());

        }

        @Override
        public void warning(SAXParseException e) throws SAXException {
            System.err.println(e.getMessage());
        }
    };

    SCXML stateMachine = null;
    try {
        stateMachine = SCXMLParser.parse(new InputSource(new StringReader(scxml)), errHandler);// ca
        // );
    } catch (IOException | SAXException | ModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return stateMachine;
}

From source file:eu.delving.x3ml.X3MLEngine.java

public static List<String> validateStream(InputStream inputStream) throws SAXException, IOException {
    Schema schema = schemaFactory().newSchema(new StreamSource(inputStream("x3ml_v1.0.xsd")));
    Validator validator = schema.newValidator();
    final List<String> errors = new ArrayList<String>();
    validator.setErrorHandler(new ErrorHandler() {
        @Override//from w w w .j  a  v a 2  s.  c  o  m
        public void warning(SAXParseException exception) throws SAXException {
            errors.add(errorMessage(exception));
        }

        @Override
        public void error(SAXParseException exception) throws SAXException {
            errors.add(errorMessage(exception));
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            errors.add(errorMessage(exception));
        }
    });
    StreamSource source = new StreamSource(inputStream);
    validator.validate(source);
    return errors;
}

From source file:com.google.code.joliratools.bind.apt.JAXROProcessorJSONTest.java

/**
 * @param xmlContent/*from   w ww. jav a  2s .co m*/
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
private static XMLNode parse(final String xmlContent)
        throws ParserConfigurationException, SAXException, IOException {
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);

    final DocumentBuilder builder = factory.newDocumentBuilder();

    builder.setErrorHandler(new ErrorHandler() {
        @Override
        public void error(final SAXParseException exception) throws SAXException {
            throw exception;
        }

        @Override
        public void fatalError(final SAXParseException exception) throws SAXException {
            throw exception;
        }

        @Override
        public void warning(final SAXParseException exception) throws SAXException {
            throw exception;
        }
    });

    final Document document = builder.parse(new InputSource(new StringReader(xmlContent)));
    final XMLNode root = new XMLNode(document);
    return root;
}