Example usage for javax.xml.parsers SAXParserFactory setValidating

List of usage examples for javax.xml.parsers SAXParserFactory setValidating

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory setValidating.

Prototype


public void setValidating(boolean validating) 

Source Link

Document

Specifies that the parser produced by this code will validate documents as they are parsed.

Usage

From source file:de.uzk.hki.da.convert.PublishXSLTConversionStrategy.java

/**
 * Creates the xml source.// w w  w.ja v  a  2s.com
 *
 * @param file the file
 * @return the source
 */
private Source createXMLSource(File file) {
    // disable validation in order to prevent url resolution of DTDs etc.
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(false);
    try {
        spf.setFeature("http://xml.org/sax/features/validation", false);
        spf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
        spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    } catch (Exception e) {
        logger.warn(e.getMessage());
    }
    XMLReader reader;
    try {
        reader = spf.newSAXParser().getXMLReader();
    } catch (Exception e) {
        throw new IllegalStateException("Unable to create SAXParser", e);
    }

    return new SAXSource(reader, new InputSource(file.getAbsolutePath()));
}

From source file:edu.psu.citeseerx.updates.external.metadata.ACMMetadataUpdater.java

public void updateACM() {
    try {/*from ww  w  . jav  a2 s .  c  om*/
        // Get the SAX factory.
        SAXParserFactory factory = SAXParserFactory.newInstance();

        // Neither we want validation nor namespaces.
        factory.setNamespaceAware(false);
        factory.setValidating(true);

        SAXParser parser = factory.newSAXParser();

        /*xmlReader.setFeature(
            "http://apache.org/xml/features/nonvalidating/load-external-dtd", 
            false);*/

        parser.parse(ACMDataFile, acmHandler);
    } catch (ParserConfigurationException e) {
        logger.error("The underlaying parser doesn't support the " + "requested feature", e);
    } catch (SAXException e) {
        logger.error("Error", e);
    } catch (IOException e) {
        logger.error("A parsing error has occurred: " + ACMDataFile, e);
    }
}

From source file:de.betterform.connector.SchemaValidator.java

/**
 * validate the instance according to the schema specified on the model
 *
 * @return false if the instance is not valid
 *//*from   w  ww  . j  a  v a 2  s .c  o  m*/
public boolean validateSchema(Model model, Node instance) throws XFormsException {
    boolean valid = true;
    String message;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("SchemaValidator.validateSchema: validating instance");

    //needed if we want to load schemas from Model + set it as "schemaLocation" attribute
    String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema");
    if (schemas != null && !schemas.equals("")) {
        //          valid=false;

        //add schemas to element
        //shouldn't it be done on a copy of the doc ?
        Element el = null;
        if (instance.getNodeType() == Node.ELEMENT_NODE)
            el = (Element) instance;
        else if (instance.getNodeType() == Node.DOCUMENT_NODE)
            el = ((Document) instance).getDocumentElement();
        else {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("instance node type is: " + instance.getNodeType());
        }

        String prefix = NamespaceResolver.getPrefix(el, NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
        //test if with targetNamespace or not
        //if more than one schema : namespaces are mandatory ! (optional only for 1)
        StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false);
        String schemaLocations = null;
        String noNamespaceSchemaLocation = null;
        while (tokenizer.hasMoreElements()) {
            String token = (String) tokenizer.nextElement();
            //check that it is an URL
            URI uri = null;
            try {
                uri = new java.net.URI(token);
            } catch (java.net.URISyntaxException ex) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(token + " is not an URI");
            }

            if (uri != null) {
                String ns;
                try {
                    ns = this.getSchemaNamespace(uri);

                    if (ns != null && !ns.equals("")) {
                        if (schemaLocations == null)
                            schemaLocations = ns + " " + token;
                        else
                            schemaLocations = schemaLocations + " " + ns + " " + token;

                        ///add the namespace declaration if it is not on the instance?
                        //TODO: how to know with which prefix ?
                        String nsPrefix = NamespaceResolver.getPrefix(el, ns);
                        if (nsPrefix == null) { //namespace not declared !
                            LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token
                                    + " is not declared in instance: declaring it as default...");
                            el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns);
                        }
                    } else if (noNamespaceSchemaLocation == null)
                        noNamespaceSchemaLocation = token;
                    else { //we have more than one schema without namespace
                        LOGGER.warn("SchemaValidator: There is more than one schema without namespace !");
                    }
                } catch (Exception ex) {
                    LOGGER.warn(
                            "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(),
                            ex);
                    //in case there was an exception: do nothing, do not set the schema
                }
            }
        }
        //write schemaLocations found
        if (schemaLocations != null && !schemaLocations.equals(""))
            el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation",
                    schemaLocations);
        if (noNamespaceSchemaLocation != null)
            el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation",
                    noNamespaceSchemaLocation);

        //save and parse the doc
        ValidationErrorHandler handler = null;
        File f;
        try {
            //save document
            f = File.createTempFile("instance", ".xml");
            f.deleteOnExit();
            TransformerFactory trFact = TransformerFactory.newInstance();
            Transformer trans = trFact.newTransformer();
            DOMSource source = new DOMSource(el);
            StreamResult result = new StreamResult(f);
            trans.transform(source, result);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath());

            //parse it with error handler to validate it
            handler = new ValidationErrorHandler();
            SAXParserFactory parserFact = SAXParserFactory.newInstance();
            parserFact.setValidating(true);
            parserFact.setNamespaceAware(true);
            SAXParser parser = parserFact.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            //validation activated
            reader.setFeature("http://xml.org/sax/features/validation", true);
            //schema validation activated
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            //used only to validate the schema, not the instance
            //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true);
            //validate only if there is a grammar
            reader.setFeature("http://apache.org/xml/features/validation/dynamic", true);

            parser.parse(f, handler);
        } catch (Exception ex) {
            LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex);
            //throw new XFormsException("XMLSchema validation failed. "+message);
        }

        //if no exception
        if (handler != null && handler.isValid())
            valid = true;
        else {
            message = handler.getMessage();
            //TODO: find a way to get the error message displayed
            throw new XFormsException("XMLSchema validation failed. " + message);
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Validator.validateSchema: result=" + valid);

    }

    return valid;
}

From source file:com.trailmagic.image.util.ImagesParserImpl.java

@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void parseFile(File metadataFile) {
    try {/*from ww  w  .ja  v a2s. c  o  m*/

        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(true);
        SAXParser parser = factory.newSAXParser();

        s_logger.info("Parsing " + metadataFile.getPath() + "...");
        parser.parse(metadataFile, this);
        s_logger.info("done");
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }

}

From source file:kmlvalidator.KmlValidatorServlet.java

/**
 * Handles POST requests for the servlet.
 *///  w w  w.  j  a v  a 2 s. c  om
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Our response is always JSON.
    response.setContentType("application/json");

    // Create the JSON response objects to be filled in later.
    JSONObject responseObj = new JSONObject();
    JSONArray responseErrors = new JSONArray();

    try {
        // Load XSD files here. Note that the Java runtime should be caching
        // these files.
        Object[] schemas = {
                new URL("http://schemas.opengis.net/kml/2.2.0/atom-author-link.xsd").openConnection()
                        .getInputStream(),
                new URL("http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd").openConnection().getInputStream(),
                new URL("http://code.google.com/apis/kml/schema/kml22gx.xsd").openConnection()
                        .getInputStream() };

        // Create a SAX parser factory (not a DOM parser, we don't need the
        // overhead) and set it to validate and be namespace aware, for
        // we want to validate against multiple XSDs.
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setValidating(true);
        parserFactory.setNamespaceAware(true);

        // Create a SAX parser and prepare for XSD validation.
        SAXParser parser = parserFactory.newSAXParser();
        parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        parser.setProperty(JAXP_SCHEMA_SOURCE, schemas);

        // Create a parser handler to trap errors during parse.
        KmlValidatorParserHandler parserHandler = new KmlValidatorParserHandler();

        // Parse the KML and send all errors to our handler.
        parser.parse(request.getInputStream(), parserHandler);

        // Check our handler for validation results.
        if (parserHandler.getErrors().size() > 0) {
            // There were errors, enumerate through them and create JSON objects
            // for each one.
            for (KmlValidationError e : parserHandler.getErrors()) {
                JSONObject error = new JSONObject();

                switch (e.getType()) {
                case KmlValidationError.VALIDATION_WARNING:
                    error.put("type", "warning");
                    break;

                case KmlValidationError.VALIDATION_ERROR:
                    error.put("type", "error");
                    break;

                case KmlValidationError.VALIDATION_FATAL_ERROR:
                    error.put("type", "fatal_error");
                    break;

                default:
                    error.put("type", "fatal_error");
                }

                // fill in parse exception details
                SAXParseException innerException = e.getInnerException();
                error.put("message", innerException.getMessage());

                if (innerException.getLineNumber() >= 0)
                    error.put("line", innerException.getLineNumber());

                if (innerException.getColumnNumber() >= 0)
                    error.put("column", innerException.getColumnNumber());

                // add this error to the list
                responseErrors.add(error);
            }

            // The KML wasn't valid.
            responseObj.put("status", "invalid");
        } else {
            // The KML is valid against the XSDs.
            responseObj.put("status", "valid");
        }
    } catch (SAXException e) {
        // We should never get here due to regular parse errors. This error
        // must've been thrown by the schema factory.
        responseObj.put("status", "internal_error");

        JSONObject error = new JSONObject();
        error.put("type", "fatal_error");
        error.put("message", "Internal error: " + e.getMessage());
        responseErrors.add(error);

    } catch (ParserConfigurationException e) {
        // Internal error at this point.
        responseObj.put("status", "internal_error");

        JSONObject error = new JSONObject();
        error.put("type", "fatal_error");
        error.put("message", "Internal parse error.");
        responseErrors.add(error);
    }

    // If there were errors, add them to the final response JSON object.
    if (responseErrors.size() > 0) {
        responseObj.put("errors", responseErrors);
    }

    // output the JSON object as the HTTP response and append a newline for
    // prettiness
    response.getWriter().print(responseObj);
    response.getWriter().println();
}

From source file:com.trailmagic.image.util.ImagesParserImpl.java

@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void parse(InputStream inputStream) {
    try {//w ww.ja v a  2  s. c  o  m

        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(true);
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        //            CatalogManager cm = new CatalogManager();
        //            Catalog catalog = cm.getCatalog();
        //            catalog.parseCatalog(getClass().getClassLoader().getResource("CatalogManager.properties"));
        //            reader.setEntityResolver(new CatalogResolver(cm));

        s_logger.info("Parsing input stream...");
        parser.parse(inputStream, this);
        s_logger.info("done");
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

From source file:ebay.dts.client.CreateLMSParser.java

/**
 * Create the SAX parser//ww w.  j  av  a 2  s .com
 */
private void create() {
    try {
        // Obtain a new instance of a SAXParserFactory.
        SAXParserFactory factory = SAXParserFactory.newInstance();
        // Specifies that the parser produced by this code will provide support for XML namespaces.
        factory.setNamespaceAware(true);
        // Specifies that the parser produced by this code will validate documents as they are parsed.
        factory.setValidating(true);
        // Creates a new instance of a SAXParser using the currently configured factory parameters.
        saxParser = factory.newSAXParser();
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:se.lu.nateko.edca.svc.DescribeFeatureType.java

/**
 * Parses an XML response from a DescribeFeatureType request and stores the layer
 * attribute names and their data types in a GeographyLayer object.
 * @param xmlResponse A reader wrapped around an InputStream containing the XML response from a DescribeFeatureType request.
 *///w w  w  .j a v  a 2  s .c o m
protected boolean parseXMLResponse(Reader xmlResponse) {
    //      Log.d(TAG, "parseXMLResponse(Reader) called.");

    try {
        SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Make a SAXParser factory.
        spfactory.setValidating(false); // Tell the factory not to make validating parsers.
        SAXParser saxParser = spfactory.newSAXParser(); // Use the factory to make a SAXParser.
        XMLReader xmlReader = saxParser.getXMLReader(); // Get an XML reader from the parser, which will send event calls to its specified event handler.
        XMLEventHandler xmlEventHandler = new XMLEventHandler();
        xmlReader.setContentHandler(xmlEventHandler); // Set which event handler to use.
        xmlReader.setErrorHandler(xmlEventHandler); // Also set where to send error calls.
        InputSource source = new InputSource(xmlResponse); // Make an InputSource from the XML input to give to the reader.
        xmlReader.parse(source); // Start parsing the XML.
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        return false;
    }
    return true;
}

From source file:edu.psu.citeseerx.updates.external.metadata.DBLPMetadataUpdater.java

public void updateDBLP() {
    try {//from  w  w w .  j  ava 2 s. com
        // Get the SAX factory.
        SAXParserFactory factory = SAXParserFactory.newInstance();

        // Neither we want validation nor namespaces.
        factory.setNamespaceAware(false);
        factory.setValidating(true);

        SAXParser parser = factory.newSAXParser();
        parser.getXMLReader().setEntityResolver(new DBLPEntityResolver(DBLPDTDFile));

        /*xmlReader.setFeature(
            "http://apache.org/xml/features/nonvalidating/load-external-dtd", 
            false);*/

        parser.parse(DBLPDataFile, dblpHandler);
    } catch (ParserConfigurationException e) {
        logger.error("The underlaying parser doesn't support the " + "requested feature", e);
    } catch (SAXException e) {
        logger.error("Error", e);
    } catch (IOException e) {
        logger.error("A parsing error has occurred: " + DBLPDataFile, e);
    }

}

From source file:se.lu.nateko.edca.svc.GetCapabilities.java

/**
 * Parses an XML response from a GetCapabilities request and stores available Layers
 * and options in the local SQLite database.
 * @param xmlResponse A reader wrapped around an InputStream containing the XML response from a GetCapabilities request.
 *//*from   ww  w . ja  v a  2 s.  c om*/
protected boolean parseXMLResponse(BufferedReader xmlResponse) {
    Log.d(TAG, "parseXMLResponse(Reader) called.");

    try {
        SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Make a SAXParser factory.
        spfactory.setValidating(false); // Tell the factory not to make validating parsers.
        SAXParser saxParser = spfactory.newSAXParser(); // Use the factory to make a SAXParser.
        XMLReader xmlReader = saxParser.getXMLReader(); // Get an XML reader from the parser, which will send event calls to its specified event handler.
        XMLEventHandler xmlEventHandler = new XMLEventHandler();
        xmlReader.setContentHandler(xmlEventHandler); // Set which event handler to use.
        xmlReader.setErrorHandler(xmlEventHandler); // Also set where to send error calls.
        InputSource source = new InputSource(xmlResponse); // Make an InputSource from the XML input to give to the reader.
        xmlReader.parse(source); // Start parsing the XML.
    } catch (Exception e) {
        Log.e(TAG, "XML parsing error: " + e.toString() + " - " + e.getMessage());
        return false;
    }
    return true;
}