Search in sources :

Example 46 with ErrorHandler

use of org.xml.sax.ErrorHandler in project freemarker by apache.

the class NodeModel method parse.

/**
 * Same as {@link #parse(InputSource, boolean, boolean)}, but loads from a {@link File}; don't miss the security
 * warnings documented there.
 */
public static NodeModel parse(File f, boolean removeComments, boolean removePIs) throws SAXException, IOException, ParserConfigurationException {
    DocumentBuilder builder = getDocumentBuilderFactory().newDocumentBuilder();
    ErrorHandler errorHandler = getErrorHandler();
    if (errorHandler != null)
        builder.setErrorHandler(errorHandler);
    Document doc = builder.parse(f);
    if (removeComments && removePIs) {
        simplify(doc);
    } else {
        if (removeComments) {
            removeComments(doc);
        }
        if (removePIs) {
            removePIs(doc);
        }
        mergeAdjacentText(doc);
    }
    return wrap(doc);
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) DocumentBuilder(javax.xml.parsers.DocumentBuilder) Document(org.w3c.dom.Document)

Example 47 with ErrorHandler

use of org.xml.sax.ErrorHandler in project CodenameOne by codenameone.

the class L10nEditor method importResourceActionPerformed.

// GEN-LAST:event_exportResourceActionPerformed
private void importResourceActionPerformed(java.awt.event.ActionEvent evt) {
    // GEN-FIRST:event_importResourceActionPerformed
    final String locale = (String) locales.getSelectedItem();
    int val = JOptionPane.showConfirmDialog(this, "This will overwrite existing values for " + locale + "\nAre you sure?", "Import", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    if (val == JOptionPane.YES_OPTION) {
        File[] files = ResourceEditorView.showOpenFileChooser("Properties, XML, CSV", "prop", "properties", "l10n", "locale", "xml", "csv");
        if (files != null) {
            FileInputStream f = null;
            try {
                f = new FileInputStream(files[0]);
                if (files[0].getName().toLowerCase().endsWith("xml")) {
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    SAXParser saxParser = spf.newSAXParser();
                    XMLReader xmlReader = saxParser.getXMLReader();
                    xmlReader.setErrorHandler(new ErrorHandler() {

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

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

                        public void fatalError(SAXParseException exception) throws SAXException {
                            exception.printStackTrace();
                        }
                    });
                    xmlReader.setContentHandler(new ContentHandler() {

                        private String currentName;

                        private StringBuilder chars = new StringBuilder();

                        @Override
                        public void setDocumentLocator(Locator locator) {
                        }

                        @Override
                        public void startDocument() throws SAXException {
                        }

                        @Override
                        public void endDocument() throws SAXException {
                        }

                        @Override
                        public void startPrefixMapping(String prefix, String uri) throws SAXException {
                        }

                        @Override
                        public void endPrefixMapping(String prefix) throws SAXException {
                        }

                        @Override
                        public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
                            if ("string".equals(localName) || "string".equals(qName)) {
                                currentName = atts.getValue("name");
                                chars.setLength(0);
                            }
                        }

                        @Override
                        public void endElement(String uri, String localName, String qName) throws SAXException {
                            if ("string".equals(localName) || "string".equals(qName)) {
                                String str = chars.toString();
                                if (str.startsWith("\"") && str.endsWith("\"")) {
                                    str = str.substring(1);
                                    str = str.substring(0, str.length() - 1);
                                    res.setLocaleProperty(localeName, locale, currentName, str);
                                    return;
                                }
                                str = str.replace("\\'", "'");
                                res.setLocaleProperty(localeName, locale, currentName, str);
                            }
                        }

                        @Override
                        public void characters(char[] ch, int start, int length) throws SAXException {
                            chars.append(ch, start, length);
                        }

                        @Override
                        public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
                        }

                        @Override
                        public void processingInstruction(String target, String data) throws SAXException {
                        }

                        @Override
                        public void skippedEntity(String name) throws SAXException {
                        }
                    });
                    xmlReader.parse(new InputSource(new InputStreamReader(f, "UTF-8")));
                } else {
                    if (files[0].getName().toLowerCase().endsWith("csv")) {
                        CSVParserOptions po = new CSVParserOptions(this);
                        if (po.isCanceled()) {
                            f.close();
                            return;
                        }
                        CSVParser p = new CSVParser(po.getDelimiter());
                        String[][] data = p.parse(new InputStreamReader(f, po.getEncoding()));
                        for (int iter = 1; iter < data.length; iter++) {
                            if (data[iter].length > 0) {
                                String key = data[iter][0];
                                for (int col = 1; col < data[iter].length; col++) {
                                    if (res.getL10N(localeName, data[0][col]) == null) {
                                        res.addLocale(localeName, data[0][col]);
                                    }
                                    res.setLocaleProperty(localeName, data[0][col], key, data[iter][col]);
                                }
                            }
                        }
                    } else {
                        Properties prop = new Properties();
                        prop.load(f);
                        for (Object key : prop.keySet()) {
                            res.setLocaleProperty(localeName, locale, (String) key, prop.getProperty((String) key));
                        }
                    }
                }
                f.close();
                initLocaleList();
                for (Object localeObj : localeList) {
                    Hashtable current = res.getL10N(localeName, (String) localeObj);
                    for (Object key : current.keySet()) {
                        if (!keys.contains(key)) {
                            keys.add(key);
                        }
                    }
                }
                Collections.sort(keys);
                initTable();
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "Error: " + ex, "Error Occured", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}
Also used : InputSource(org.xml.sax.InputSource) Attributes(org.xml.sax.Attributes) Properties(java.util.Properties) ContentHandler(org.xml.sax.ContentHandler) SAXException(org.xml.sax.SAXException) Locator(org.xml.sax.Locator) SAXParseException(org.xml.sax.SAXParseException) SAXParser(javax.xml.parsers.SAXParser) UIBuilderOverride(com.codename1.ui.util.UIBuilderOverride) XMLReader(org.xml.sax.XMLReader) ErrorHandler(org.xml.sax.ErrorHandler) InputStreamReader(java.io.InputStreamReader) Hashtable(java.util.Hashtable) FileInputStream(java.io.FileInputStream) SAXException(org.xml.sax.SAXException) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) CSVParser(com.codename1.io.CSVParser) EventObject(java.util.EventObject) File(java.io.File) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Example 48 with ErrorHandler

use of org.xml.sax.ErrorHandler in project teiid by teiid.

the class TestTeiidConfiguration method validate.

private void validate(String marshalled) throws SAXException, IOException {
    URL xsdURL = Thread.currentThread().getContextClassLoader().getResource("schema/jboss-teiid.xsd");
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = factory.newSchema(xsdURL);
    Validator validator = schema.newValidator();
    Source source = new StreamSource(new ByteArrayInputStream(marshalled.getBytes()));
    validator.setErrorHandler(new ErrorHandler() {

        @Override
        public void warning(SAXParseException exception) throws SAXException {
            fail(exception.getMessage());
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            fail(exception.getMessage());
        }

        @Override
        public void error(SAXParseException exception) throws SAXException {
            if (!exception.getMessage().contains("cvc-enumeration-valid") && !exception.getMessage().contains("cvc-type")) {
                fail(exception.getMessage());
            }
        }
    });
    validator.validate(source);
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) ErrorHandler(org.xml.sax.ErrorHandler) ByteArrayInputStream(java.io.ByteArrayInputStream) SAXParseException(org.xml.sax.SAXParseException) Schema(javax.xml.validation.Schema) StreamSource(javax.xml.transform.stream.StreamSource) URL(java.net.URL) Validator(javax.xml.validation.Validator) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) SAXException(org.xml.sax.SAXException)

Example 49 with ErrorHandler

use of org.xml.sax.ErrorHandler in project BibleMultiConverter by schierlm.

the class ValidateXML method validateFile.

private static void validateFile(Schema schema, File file, final String errorHeader, String okMessage, String errorFooter) throws IOException {
    Validator validator = schema.newValidator();
    final int[] errorCountHolder = new int[1];
    validator.setErrorHandler(new ErrorHandler() {

        private void printHeader() {
            if (errorCountHolder[0] == 0 && errorHeader != null) {
                System.out.println(errorHeader);
            }
            errorCountHolder[0]++;
        }

        @Override
        public void warning(SAXParseException exception) throws SAXException {
            printHeader();
            System.out.println("\t[Warning] " + exception.toString());
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            printHeader();
            System.out.println("\t[Fatal Error] " + exception.toString());
        }

        @Override
        public void error(SAXParseException exception) throws SAXException {
            printHeader();
            System.out.println("\t[Error] " + exception.toString());
        }
    });
    try {
        validator.validate(new StreamSource(file));
    } catch (SAXException ex) {
    // already handled by ValidationHandler
    }
    String resultMessage = (errorCountHolder[0] > 0) ? errorFooter : okMessage;
    if (resultMessage != null)
        System.out.println(resultMessage);
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) SAXParseException(org.xml.sax.SAXParseException) StreamSource(javax.xml.transform.stream.StreamSource) Validator(javax.xml.validation.Validator) SAXException(org.xml.sax.SAXException)

Example 50 with ErrorHandler

use of org.xml.sax.ErrorHandler in project hale by halestudio.

the class Validate method validate.

/**
 * @see Validator#validate(InputStream)
 */
public void validate(InputStream xml) {
    javax.xml.validation.Schema validateSchema;
    try {
        URI mainUri = null;
        Source[] sources = new Source[schemaLocations.length];
        for (int i = 0; i < this.schemaLocations.length; i++) {
            URI schemaLocation = this.schemaLocations[i];
            if (mainUri == null) {
                // use first schema location for main URI
                mainUri = schemaLocation;
            }
            // load a WXS schema, represented by a Schema instance
            sources[i] = new StreamSource(schemaLocation.toURL().openStream());
        }
        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        factory.setResourceResolver(new SchemaResolver(mainUri));
        validateSchema = factory.newSchema(sources);
    } catch (Exception e) {
        // $NON-NLS-1$
        throw new IllegalStateException("Error parsing schema for XML validation", e);
    }
    final AtomicInteger warnings = new AtomicInteger(0);
    final AtomicInteger errors = new AtomicInteger(0);
    // create a Validator instance, which can be used to validate an
    // instance document
    javax.xml.validation.Validator validator = validateSchema.newValidator();
    validator.setErrorHandler(new ErrorHandler() {

        @Override
        public void warning(SAXParseException exception) throws SAXException {
            System.out.println(MessageFormat.format(MESSAGE_PATTERN, exception.getLocalizedMessage(), exception.getLineNumber(), exception.getColumnNumber()));
            warnings.incrementAndGet();
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            System.err.println(MessageFormat.format(MESSAGE_PATTERN, exception.getLocalizedMessage(), exception.getLineNumber(), exception.getColumnNumber()));
            errors.incrementAndGet();
        }

        @Override
        public void error(SAXParseException exception) throws SAXException {
            System.err.println(MessageFormat.format(MESSAGE_PATTERN, exception.getLocalizedMessage(), exception.getLineNumber(), exception.getColumnNumber()));
            errors.incrementAndGet();
        }
    });
    // validate the XML document
    try {
        validator.validate(new StreamSource(xml));
    } catch (Exception e) {
        // $NON-NLS-1$
        throw new IllegalStateException("Error validating XML file", e);
    }
    System.out.println("Validation completed.");
    System.out.println(warnings.get() + " warnings");
    System.out.println(errors.get() + " errors");
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) ErrorHandler(org.xml.sax.ErrorHandler) StreamSource(javax.xml.transform.stream.StreamSource) URI(java.net.URI) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) FileNotFoundException(java.io.FileNotFoundException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) SAXException(org.xml.sax.SAXException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SAXParseException(org.xml.sax.SAXParseException)

Aggregations

ErrorHandler (org.xml.sax.ErrorHandler)69 SAXException (org.xml.sax.SAXException)59 SAXParseException (org.xml.sax.SAXParseException)55 DocumentBuilder (javax.xml.parsers.DocumentBuilder)26 IOException (java.io.IOException)25 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)24 Document (org.w3c.dom.Document)20 InputSource (org.xml.sax.InputSource)17 FileInputStream (java.io.FileInputStream)11 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)11 Element (org.w3c.dom.Element)10 File (java.io.File)9 ByteArrayInputStream (java.io.ByteArrayInputStream)8 InputStream (java.io.InputStream)8 Validator (javax.xml.validation.Validator)8 EntityResolver (org.xml.sax.EntityResolver)8 StreamSource (javax.xml.transform.stream.StreamSource)6 Schema (javax.xml.validation.Schema)6 SchemaFactory (javax.xml.validation.SchemaFactory)6 Node (org.w3c.dom.Node)5