Search in sources :

Example 31 with ErrorHandler

use of org.xml.sax.ErrorHandler in project ACS by ACS-Community.

the class XMLValidator method run.

public void run(String[] args) {
    try {
        if (args.length != 2) {
            System.out.println("Incorrect arguments. You need to provide the XML and XSD files.");
            System.exit(3);
        }
        XMLValidator.error = false;
        // define the type of schema - we use W3C:
        String schemaLang = "http://www.w3.org/2001/XMLSchema";
        // get validation driver:
        SchemaFactory factory = SchemaFactory.newInstance(schemaLang);
        // create schema by reading it from an XSD file:
        Schema schema = factory.newSchema(new StreamSource(args[1]));
        Validator validator = schema.newValidator();
        ErrorHandler eh = new XMLErrorHandler(args[0]);
        validator.setErrorHandler(eh);
        // at last perform validation:
        XMLInputFactory xFact = XMLInputFactory.newInstance();
        XMLStreamReader xRead = xFact.createXMLStreamReader(new FileReader(args[0]));
        if (xRead.getVersion() == null) {
            System.err.println(args[0] + ": There is no XML Definition.");
            XMLValidator.error = true;
        } else if (xRead.getCharacterEncodingScheme() == null) {
            System.err.println(args[0] + ": The encoding attribute is not defined in the XML Definition.");
            XMLValidator.error = true;
        } else if (xRead.getCharacterEncodingScheme().compareTo("ISO-8859-1") != 0) {
            System.err.println(args[0] + ": Incorrect encoding type in the XML Definition.");
            XMLValidator.error = true;
        }
        validator.validate(new StreamSource(args[0]));
    } catch (SAXException ex) {
        System.err.println("Fatal Error");
        System.err.println(args[0] + ": " + ex.getMessage());
        XMLValidator.error = true;
    } catch (Exception ex) {
        ex.printStackTrace();
        XMLValidator.error = true;
    }
    if (XMLValidator.error) {
        //System.exit(1); //Error
        //Warning
        System.exit(0);
    } else {
        System.exit(0);
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) ErrorHandler(org.xml.sax.ErrorHandler) XMLStreamReader(javax.xml.stream.XMLStreamReader) Schema(javax.xml.validation.Schema) StreamSource(javax.xml.transform.stream.StreamSource) FileReader(java.io.FileReader) Validator(javax.xml.validation.Validator) XMLInputFactory(javax.xml.stream.XMLInputFactory) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) SAXException(org.xml.sax.SAXException)

Example 32 with ErrorHandler

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

the class XMLUtil method validate.

/**
     * Check whether a DOM tree is valid according to a schema. Example of
     * usage:
     * <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];
    }
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) DOMSource(javax.xml.transform.dom.DOMSource) SAXParseException(org.xml.sax.SAXParseException) IOException(java.io.IOException) Validator(javax.xml.validation.Validator) SAXException(org.xml.sax.SAXException)

Example 33 with ErrorHandler

use of org.xml.sax.ErrorHandler in project tdi-studio-se by Talend.

the class ImportProjectSettings method updateProjectSettings.

public void updateProjectSettings() throws ParserConfigurationException, SAXException, IOException {
    if (this.path == null) {
        return;
    }
    File file = new File(path);
    org.talend.core.model.properties.Project project = pro.getEmfProject();
    final DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
    DocumentBuilder analyseur = fabrique.newDocumentBuilder();
    analyseur.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 = analyseur.parse(file);
    // PTODO, if need, get the version from the imported file.
    // NodeList exportParametersNodes = document.getElementsByTagName("exportParameters");
    // String importStudioVersion=null;
    //$NON-NLS-1$
    final NodeList nodes = document.getElementsByTagName("exportParameter");
    List addedComponentSetting = new ArrayList();
    List technical = project.getTechnicalStatus();
    List documentation = project.getDocumentationStatus();
    technical.clear();
    documentation.clear();
    for (int i = 0; i < nodes.getLength(); i++) {
        final Node node = nodes.item(i);
        final NamedNodeMap attrMap = node.getAttributes();
        //$NON-NLS-1$
        final Node typeAttr = attrMap.getNamedItem("type");
        if ("technicalStatus".equals(typeAttr.getTextContent())) {
            //$NON-NLS-1$
            //$NON-NLS-1$
            updateStatus(node, attrMap, technical, "technicalStatus");
        } else if ("documentationStatus".equals(typeAttr.getTextContent())) {
            //$NON-NLS-1$
            //$NON-NLS-1$
            updateStatus(node, attrMap, documentation, "documentationStatus");
        } else if ("security".equals(typeAttr.getTextContent())) {
            //$NON-NLS-1$
            project.isHidePassword();
            project.setHidePassword(Boolean.valueOf(node.getTextContent()));
        } else if ("statAndLogs".equals(typeAttr.getTextContent())) {
            //$NON-NLS-1$
            if (project.getStatAndLogsSettings() == null) {
                TalendFileFactory talendF = TalendFileFactory.eINSTANCE;
                StatAndLogsSettings stats = PropertiesFactory.eINSTANCE.createStatAndLogsSettings();
                project.setStatAndLogsSettings(stats);
                stats.setParameters(talendF.createParametersType());
            }
            List statAndLogs = project.getStatAndLogsSettings().getParameters().getElementParameter();
            updateParameters(node, attrMap, statAndLogs);
        } else if ("implicitContext".equals(typeAttr.getTextContent())) {
            //$NON-NLS-1$
            if (project.getImplicitContextSettings() == null) {
                TalendFileFactory talendF = TalendFileFactory.eINSTANCE;
                ImplicitContextSettings implicit = PropertiesFactory.eINSTANCE.createImplicitContextSettings();
                project.setImplicitContextSettings(implicit);
                implicit.setParameters(talendF.createParametersType());
            }
            List implicitContexts = project.getImplicitContextSettings().getParameters().getElementParameter();
            updateParameters(node, attrMap, implicitContexts);
        } else if ("palette".equals(typeAttr.getTextContent())) {
            //$NON-NLS-1$
            List componentSettings = project.getComponentsSettings();
            boolean existed = false;
            //$NON-NLS-1$
            String name = attrMap.getNamedItem("name").getTextContent();
            //$NON-NLS-1$
            final Node familyAttr = attrMap.getNamedItem("family");
            Boolean hide = Boolean.valueOf(node.getTextContent());
            for (Object obj : componentSettings) {
                ComponentSetting setting = (ComponentSetting) obj;
                if (setting.getName().equals(name)) {
                    if (familyAttr != null && familyAttr.getTextContent().equals(setting.getFamily())) {
                        existed = true;
                        setting.setHidden(hide);
                    }
                }
            }
            if (!existed && familyAttr != null) {
                ComponentSetting setting = PropertiesFactory.eINSTANCE.createComponentSetting();
                setting.setFamily(familyAttr.getTextContent());
                setting.setName(name);
                setting.setHidden(hide);
                addedComponentSetting.add(setting);
            }
        }
    }
    project.getComponentsSettings().addAll(addedComponentSetting);
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) TalendFileFactory(org.talend.designer.core.model.utils.emf.talendfile.TalendFileFactory) SAXParseException(org.xml.sax.SAXParseException) StatAndLogsSettings(org.talend.core.model.properties.StatAndLogsSettings) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) ErrorHandler(org.xml.sax.ErrorHandler) NamedNodeMap(org.w3c.dom.NamedNodeMap) NodeList(org.w3c.dom.NodeList) ComponentSetting(org.talend.core.model.properties.ComponentSetting) ImplicitContextSettings(org.talend.core.model.properties.ImplicitContextSettings) DocumentBuilder(javax.xml.parsers.DocumentBuilder) File(java.io.File)

Example 34 with ErrorHandler

use of org.xml.sax.ErrorHandler in project tdi-studio-se by Talend.

the class AutoConvertTypesUtils method save.

public static boolean save(List<AutoConversionType> beans, File file) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    OutputStreamWriter output = null;
    try {
        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;
            }
        });
        Document document = builder.newDocument();
        //document.setXmlVersion("1.0");//$NON-NLS-1$
        //$NON-NLS-1$
        Element root = document.createElement("mapping");
        document.appendChild(root);
        for (int i = 0; i < beans.size(); i++) {
            AutoConversionType bean = beans.get(i);
            //$NON-NLS-1$
            Element typeNode = document.createElement("conversionType");
            //$NON-NLS-1$
            typeNode.setAttribute("source", bean.getSourceDataType());
            //$NON-NLS-1$
            typeNode.setAttribute("target", bean.getTargetDataType());
            //$NON-NLS-1$
            typeNode.setAttribute("function", bean.getConversionFunction());
            root.appendChild(typeNode);
        }
        // save into file
        if (document != null) {
            XMLSerializer serializer = new XMLSerializer();
            OutputFormat outputFormat = new OutputFormat();
            outputFormat.setIndenting(true);
            serializer.setOutputFormat(outputFormat);
            output = new OutputStreamWriter(new FileOutputStream(file));
            serializer.setOutputCharStream(output);
            serializer.serialize(document);
            // update
            beanList = new ArrayList<>();
            beanList.addAll(beans);
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } finally {
        if (output != null) {
            output.close();
        }
    }
    return true;
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) XMLSerializer(com.sun.org.apache.xml.internal.serialize.XMLSerializer) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Element(org.w3c.dom.Element) OutputFormat(com.sun.org.apache.xml.internal.serialize.OutputFormat) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) AutoConversionType(org.talend.core.model.metadata.types.AutoConversionType) DocumentBuilder(javax.xml.parsers.DocumentBuilder) SAXParseException(org.xml.sax.SAXParseException) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 35 with ErrorHandler

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

the class NTriple method processOpts.

private static int processOpts(String opts, String nextArg) {
    boolean usedNext = false;
    ARPOptions options = arp.getOptions();
    for (int i = 0; i < opts.length(); i++) {
        char opt = opts.charAt(i);
        if ("beiwD".indexOf(opt) != -1) {
            if (usedNext)
                usage();
            usedNext = true;
        }
        switch(opt) {
            case 'D':
                final int nStatements = Integer.parseInt(nextArg);
                rt.gc();
                rt.gc();
                startMem = (int) (rt.totalMemory() - rt.freeMemory());
                arp.getHandlers().setStatementHandler(new StatementHandler() {

                    int debugC = 0;

                    @Override
                    public void statement(AResource subj, AResource pred, AResource obj) {
                        statement(null, null, (ALiteral) null);
                    }

                    @Override
                    public void statement(AResource subj, AResource pred, ALiteral lit) {
                        if (++debugC % 100 == 0) {
                            System.out.println("T: " + debugC);
                            rt.gc();
                            System.out.println("M1: " + (rt.totalMemory() - rt.freeMemory() - startMem));
                            rt.gc();
                            System.out.println("M2: " + (rt.totalMemory() - rt.freeMemory() - startMem));
                        }
                        if (debugC == 1) {
                            rt.gc();
                            rt.gc();
                            startMem = (int) (rt.totalMemory() - rt.freeMemory());
                        }
                        if (debugC == nStatements) {
                            rt.gc();
                            System.err.println("Kill me now.");
                            try {
                                Thread.sleep(200000);
                            } catch (Exception e) {
                            // ignore
                            }
                        }
                    }
                });
                break;
            case 'x':
                options.setLaxErrorMode();
                break;
            case 's':
                options.setStrictErrorMode();
                break;
            case 't':
                arp.getHandlers().setStatementHandler(getSH(false));
                break;
            case 'r':
                options.setEmbedding(false);
                break;
            case 'R':
                options.setEmbedding(true);
                break;
            case 'n':
                numbers = true;
                break;
            case 'E':
                arp.getHandlers().setErrorHandler(new ErrorHandler() {

                    @Override
                    public void warning(SAXParseException exception) {
                    /* ignore */
                    }

                    @Override
                    public void error(SAXParseException exception) {
                    /* ignore */
                    }

                    @Override
                    public void fatalError(SAXParseException exception) {
                    /* ignore */
                    }
                });
                arp.setBadStatementHandler(new SH(System.err));
                break;
            case 'b':
                xmlBase = nextArg;
                break;
            case 'e':
                setErrorMode(nextArg, EM_ERROR);
                break;
            case 'i':
                setErrorMode(nextArg, EM_IGNORE);
                break;
            case 'w':
                setErrorMode(nextArg, EM_WARNING);
                break;
            case 'f':
                for (int j = 0; j < 400; j++) {
                    if (options.setErrorMode(j, -1) == EM_ERROR)
                        options.setErrorMode(j, EM_FATAL);
                }
                break;
            case 'u':
                options.setErrorMode(WARN_UNQUALIFIED_ATTRIBUTE, EM_IGNORE);
                options.setErrorMode(WARN_UNQUALIFIED_RDF_ATTRIBUTE, EM_IGNORE);
                break;
            default:
                usage();
        }
    }
    return usedNext ? 1 : 0;
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) SAXParseException(org.xml.sax.SAXParseException) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

ErrorHandler (org.xml.sax.ErrorHandler)38 SAXException (org.xml.sax.SAXException)36 SAXParseException (org.xml.sax.SAXParseException)33 IOException (java.io.IOException)16 DocumentBuilder (javax.xml.parsers.DocumentBuilder)14 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)14 Document (org.w3c.dom.Document)13 InputSource (org.xml.sax.InputSource)9 InputStream (java.io.InputStream)7 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)7 Element (org.w3c.dom.Element)7 FileInputStream (java.io.FileInputStream)6 EntityResolver (org.xml.sax.EntityResolver)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 File (java.io.File)4 StringReader (java.io.StringReader)4 OutputFormat (com.sun.org.apache.xml.internal.serialize.OutputFormat)3 XMLSerializer (com.sun.org.apache.xml.internal.serialize.XMLSerializer)3 Attr (org.w3c.dom.Attr)3 NodeList (org.w3c.dom.NodeList)3