Search in sources :

Example 16 with ErrorHandler

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

the class CDBChecker method validateSchemas.

/**
	 * This method validates the XSD files.
	 * 
	 * @param xsdFilenames names with absolute path of the XSD file to validate.
	 */
protected void validateSchemas(Vector<String> xsdFilenames) {
    System.out.println("*** Will verify XSD files in: " + this.XSDPath);
    // We share the resolver, to benefit more from its cache.
    CDBSchemasResolver resolver = new CDBSchemasResolver(this, schemaFolder + File.pathSeparator + XSDPath);
    ErrorHandler errorHandler = new CDBErrorHandler(this);
    for (String xsdFilename : xsdFilenames) {
        final File xsdFile = new File(xsdFilename);
        if (xsdFile.length() != 0) {
            if (verbose) {
                System.out.print("    " + xsdFilename);
            }
            try {
                validateFileEncoding(xsdFilename);
                SP.reset();
                // not sure why, but this is the legacy behavior
                resolver.setResolveOnlyHttp(true);
                SP.setEntityResolver(resolver);
                SP.setFeature("http://xml.org/sax/features/validation", true);
                SP.setFeature("http://apache.org/xml/features/validation/schema", true);
                SP.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
                SP.setFeature("http://xml.org/sax/features/namespaces", true);
                SP.setErrorHandler(errorHandler);
                SP.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", "http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema.xsd");
                FileInputStream fis = new FileInputStream(xsdFile);
                InputSource inputSource = new InputSource(fis);
                inputSource.setSystemId("file:///" + xsdFile.getAbsolutePath());
                SP.parse(inputSource);
                fis.close();
                try {
                    // Now we know that the schema is technically valid (well, it does not seem to check xsd imports...)
                    // Still we have to check special requirements for CharacteristicComponent XSDs.
                    // This second check probably includes the first check's functionality, so that the
                    // first check could be removed once we have verified XSOM's xsd error reporting
                    // and hooked up the shared error handler in BaciSchemaChecker.
                    // here we want to resolve all schemas
                    resolver.setResolveOnlyHttp(false);
                    BaciSchemaChecker baciChecker = new BaciSchemaChecker(xsdFile, resolver, errorHandler, logger);
                    List<BaciPropertyLocator> badProps = baciChecker.findBaciPropsOutsideCharacteristicComp();
                    if (!badProps.isEmpty()) {
                        // Reduce the available error output to show only xsd element(s), not the individual baci properties
                        Set<String> badXsdElementNames = new HashSet<String>();
                        for (BaciPropertyLocator badProp : badProps) {
                            badXsdElementNames.add(badProp.elementName);
                        }
                        System.out.println(xsdFilename + ": illegal use of baci properties in xsd elements that are not derived from baci:CharacteristicComponent. " + "Offending element(s): " + StringUtils.join(badXsdElementNames, ' '));
                        errorFlag = true;
                        globalErrorFlag = true;
                    }
                } catch (SAXException ex) {
                // ignore SAXException coming from BaciSchemaChecker, because we don't want to report errors
                // twice when the xsd file is really messed up. 
                // There are cases where xerces reports a normal error but XSOM reports a fatal error and throws this exception.
                }
                if (verbose && !errorFlag) {
                    System.out.println("[OK]");
                }
            } catch (SAXException e) {
                System.out.println("Caught a SAXException in validateSchemas: ");
                e.printStackTrace(System.out);
            } catch (IOException e) {
                System.out.println("[IOException] Probably " + xsdFilename + " doesn't exists.");
            }
        } else {
            System.out.print(xsdFilename + ": [Warning] file is empty.\n");
        }
    }
    // back to legacy mode again... yuck, our resolver still sticks to the "SP" field and will be used elsewhere!
    resolver.setResolveOnlyHttp(true);
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) InputSource(org.xml.sax.InputSource) BaciPropertyLocator(alma.acs.cdbChecker.BaciSchemaChecker.BaciPropertyLocator) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) SAXException(org.xml.sax.SAXException) BaciSchemaChecker(alma.acs.cdbChecker.BaciSchemaChecker) File(java.io.File) HashSet(java.util.HashSet)

Example 17 with ErrorHandler

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

the class XMLLiteralType method isValid.

/**
     * Test whether the given string is a legal lexical form
     * of this datatype.
     */
@Override
public boolean isValid(final String lexicalForm) {
    /*
         * To check the lexical form we construct
         * a dummy RDF/XML document and parse it with
         * ARP. ARP performs an exclusive canonicalization,
         * the dummy document has exactly one triple.
         * If the lexicalForm is valid then the resulting
         * literal found by ARP is unchanged.
         * All other scenarios are either impossible
         * or occur because the lexical form is invalid.
         */
    final boolean[] status = new boolean[] { false, false, false };
    // status[0] true on error or other reason to know that this is not well-formed
    // status[1] true once first triple found
    // status[2] the result (good if status[1] and not status[0]).
    ARP arp = new ARP();
    arp.getHandlers().setErrorHandler(new ErrorHandler() {

        @Override
        public void fatalError(SAXParseException e) {
            status[0] = true;
        }

        @Override
        public void error(SAXParseException e) {
            status[0] = true;
        }

        @Override
        public void warning(SAXParseException e) {
            status[0] = true;
        }
    });
    arp.getHandlers().setStatementHandler(new StatementHandler() {

        @Override
        public void statement(AResource a, AResource b, ALiteral l) {
            /* this method is invoked exactly once
        	 * while parsing the dummy document.
        	 * The l argument is in exclusive canonical XML and
        	 * corresponds to where the lexical form has been 
        	 * in the dummy document. The lexical form is valid
        	 * iff it is unchanged.
        	 */
            if (status[1] || !l.isWellFormedXML()) {
                status[0] = true;
            }
            //throw new BrokenException("plain literal in XMLLiteral code.");
            status[1] = true;
            status[2] = l.toString().equals(lexicalForm);
        }

        @Override
        public void statement(AResource a, AResource b, AResource l) {
            status[0] = true;
        //throw new BrokenException("resource valued RDF/XML in XMLLiteral code.");
        }
    });
    try {
        arp.load(new StringReader("<rdf:RDF  xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>\n" + "<rdf:Description><rdf:value rdf:parseType='Literal'>" + lexicalForm + "</rdf:value>\n" + "</rdf:Description></rdf:RDF>"));
    } catch (IOException ioe) {
        throw new BrokenException(ioe);
    } catch (SAXException s) {
        return false;
    }
    return (!status[0]) && status[1] && status[2];
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) SAXParseException(org.xml.sax.SAXParseException) StatementHandler(org.apache.jena.rdfxml.xmlinput.StatementHandler) StringReader(java.io.StringReader) AResource(org.apache.jena.rdfxml.xmlinput.AResource) BrokenException(org.apache.jena.shared.BrokenException) ALiteral(org.apache.jena.rdfxml.xmlinput.ALiteral) IOException(java.io.IOException) ARP(org.apache.jena.rdfxml.xmlinput.ARP) SAXException(org.xml.sax.SAXException)

Example 18 with ErrorHandler

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

the class TestErrorMsg method check.

/**
	 * @param filename
	 *            Read this file
	 * @param regex
	 *            Error msg must match this.
	 *
	private void check(String filename, String regex)
		throws IOException, MalformedPatternException, SAXException {
		check(filename, regex, null);
	}
	*/
private void check(String filename, String regexPresent, String regexAbsent) throws IOException {
    final StringBuffer buf = new StringBuffer();
    ARP arp = new ARP();
    arp.getHandlers().setErrorHandler(new ErrorHandler() {

        @Override
        public void warning(SAXParseException exception) {
            buf.append(exception.getMessage());
            buf.append("\n");
        }

        @Override
        public void error(SAXParseException e) {
            warning(e);
        }

        @Override
        public void fatalError(SAXParseException e) {
            warning(e);
        }
    });
    try (InputStream in = new FileInputStream("testing/arp/error-msgs/" + filename + ".rdf")) {
        arp.load(in, "file:///" + filename);
    } catch (SAXException e) {
    }
    String contents = buf.toString();
    if (regexPresent != null)
        assertTrue("Should find /" + regexPresent + "/", Pattern.compile(regexPresent, Pattern.DOTALL).matcher(contents).find());
    if (regexAbsent != null)
        assertTrue("Should not find /" + regexAbsent + "/", !Pattern.compile(regexAbsent, Pattern.DOTALL).matcher(contents).find());
    contents = null;
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) SAXParseException(org.xml.sax.SAXParseException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileInputStream(java.io.FileInputStream) ARP(org.apache.jena.rdfxml.xmlinput.ARP) SAXException(org.xml.sax.SAXException)

Example 19 with ErrorHandler

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

the class MoreTests method testInterrupt.

public void testInterrupt() throws SAXException, IOException {
    ARP a = new ARP();
    try (InputStream in = new FileInputStream("testing/wg/miscellaneous/consistent001.rdf")) {
        a.getHandlers().setStatementHandler(new StatementHandler() {

            int countDown = 10;

            @Override
            public void statement(AResource subj, AResource pred, AResource obj) {
                if (countDown-- == 0)
                    Thread.currentThread().interrupt();
            }

            @Override
            public void statement(AResource subj, AResource pred, ALiteral lit) {
            }
        });
        a.getHandlers().setErrorHandler(new ErrorHandler() {

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw new RuntimeException("Unexpected error", exception);
            }

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

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw new RuntimeException("Unexpected warning", exception);
            }
        });
        try {
            a.load(in);
            fail("Thread was not interrupted.");
        } catch (InterruptedIOException | SAXParseException e) {
        }
    }
// System.err.println("Finished "+Thread.interrupted());
}
Also used : RDFErrorHandler(org.apache.jena.rdf.model.RDFErrorHandler) ErrorHandler(org.xml.sax.ErrorHandler) SAXException(org.xml.sax.SAXException) SAXParseException(org.xml.sax.SAXParseException)

Example 20 with ErrorHandler

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

the class FeatureDeploymentListener method parse.

protected Document parse(File artifact) throws Exception {
    if (dbf == null) {
        dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
    }
    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);
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) DocumentBuilder(javax.xml.parsers.DocumentBuilder) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException)

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