Example usage for javax.xml.validation Validator validate

List of usage examples for javax.xml.validation Validator validate

Introduction

In this page you can find the example usage for javax.xml.validation Validator validate.

Prototype

public void validate(Source source) throws SAXException, IOException 

Source Link

Document

Validates the specified input.

Usage

From source file:edu.unc.lib.dl.ingest.sip.METSPackageSIPProcessor.java

private void xsdValidate(File metsFile2) throws IngestException {
    // TODO can reuse schema object, it is thread safe
    javax.xml.validation.SchemaFactory schemaFactory = javax.xml.validation.SchemaFactory
            .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    StreamSource xml = new StreamSource(getClass().getResourceAsStream(schemaPackage + "xml.xsd"));
    StreamSource xlink = new StreamSource(getClass().getResourceAsStream(schemaPackage + "xlink.xsd"));
    StreamSource mets = new StreamSource(getClass().getResourceAsStream(schemaPackage + "mets.xsd"));
    StreamSource premis = new StreamSource(getClass().getResourceAsStream(schemaPackage + "premis-v2-0.xsd"));
    StreamSource mods = new StreamSource(getClass().getResourceAsStream(schemaPackage + "mods-3-4.xsd"));
    StreamSource acl = new StreamSource(getClass().getResourceAsStream(schemaPackage + "acl.xsd"));
    Schema schema;/*w ww  .  java  2 s.c  om*/
    try {
        Source[] sources = { xml, xlink, mets, premis, mods, acl };
        schema = schemaFactory.newSchema(sources);
    } catch (SAXException e) {
        throw new Error("Cannot locate METS schema in classpath.", e);
    }

    Validator metsValidator = schema.newValidator();
    METSParseException handler = new METSParseException("There was a problem parsing METS XML.");
    metsValidator.setErrorHandler(handler);
    // TODO get a Result document for reporting error
    try {
        metsValidator.validate(new StreamSource(metsFile2));
    } catch (SAXException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        }
        throw handler;
    } catch (IOException e) {
        throw new IngestException("The supplied METS file is not readable.", e);
    }
}

From source file:com.rapid.server.RapidServletContextListener.java

public static int loadConnectionAdapters(ServletContext servletContext) throws Exception {

    int adapterCount = 0;

    // retain our class constructors in a hashtable - this speeds up initialisation
    HashMap<String, Constructor> connectionConstructors = new HashMap<String, Constructor>();

    // create an array list of json objects which we will sort later according to the order
    ArrayList<JSONObject> connectionAdapters = new ArrayList<JSONObject>();

    // get the directory in which the control xml files are stored
    File dir = new File(servletContext.getRealPath("/WEB-INF/database/"));

    // create a filter for finding .control.xml files
    FilenameFilter xmlFilenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".connectionadapter.xml");
        }//from  w w w . ja  v  a 2  s. c  om
    };

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/connectionAdapter.xsd"));
    // create a validator
    Validator validator = schema.newValidator();

    // loop the xml files in the folder
    for (File xmlFile : dir.listFiles(xmlFilenameFilter)) {

        // read the xml into a string
        String xml = Strings.getString(xmlFile);

        // validate the control xml file against the schema
        validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));

        // convert the string into JSON
        JSONObject jsonConnectionAdapter = org.json.XML.toJSONObject(xml).getJSONObject("connectionAdapter");

        // get the class name from the json
        String className = jsonConnectionAdapter.getString("class");
        // get the class 
        Class classClass = Class.forName(className);
        // check the class extends com.rapid.data.ConnectionAdapter
        if (!Classes.extendsClass(classClass, com.rapid.data.ConnectionAdapter.class))
            throw new Exception(
                    classClass.getCanonicalName() + " must extend com.rapid.data.ConnectionAdapter");
        // check this class is unique
        if (connectionConstructors.get(className) != null)
            throw new Exception(className + " connection adapter already loaded.");
        // add to constructors hashmap referenced by type
        connectionConstructors.put(className, classClass.getConstructor(ServletContext.class, String.class,
                String.class, String.class, String.class));

        // add to to our array list
        connectionAdapters.add(jsonConnectionAdapter);

        // increment the count
        adapterCount++;

    }

    // sort the connection adapters according to their order property
    Collections.sort(connectionAdapters, new Comparator<JSONObject>() {
        @Override
        public int compare(JSONObject o1, JSONObject o2) {
            try {
                return o1.getInt("order") - o2.getInt("order");
            } catch (JSONException e) {
                return 999;
            }
        }
    });

    // create a JSON Array object which will hold json for all of the available security adapters
    JSONArray jsonConnectionAdapters = new JSONArray();

    // loop the sorted connection adapters and add to the json array
    for (JSONObject jsonConnectionAdapter : connectionAdapters)
        jsonConnectionAdapters.put(jsonConnectionAdapter);

    // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet)
    servletContext.setAttribute("jsonConnectionAdapters", jsonConnectionAdapters);

    // put the constructors hashmapin a context attribute (this is available via the getContructor method in RapidHttpServlet)
    servletContext.setAttribute("securityConstructors", connectionConstructors);

    _logger.info(adapterCount + " connection adapters loaded in .connectionAdapter.xml files");

    return adapterCount;

}

From source file:org.kite9.diagram.server.AbstractKite9Controller.java

protected void validateXML(String xml) throws SAXException, IOException {
    // validate the xml against the schema
    InputSource is = new InputSource(new StringReader(xml));

    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    // load a WXS schema, represented by a Schema instance
    Source schemaFile = new StreamSource(Diagram.class.getResourceAsStream("/adl_1.0.xsd"));
    Schema schema = factory.newSchema(schemaFile);

    Validator validator = schema.newValidator();

    SAXSource source = new SAXSource(is);
    validator.validate(source);
}

From source file:com.rapid.server.RapidServletContextListener.java

public static int loadThemes(ServletContext servletContext) throws Exception {

    // assume no themes
    int themeCount = 0;

    // create a list for our themes
    List<Theme> themes = new ArrayList<Theme>();

    // get the directory in which the control xml files are stored
    File dir = new File(servletContext.getRealPath("/WEB-INF/themes/"));

    // create a filter for finding .control.xml files
    FilenameFilter xmlFilenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".theme.xml");
        }/* w w  w. j  a  v  a  2  s .c om*/
    };

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/theme.xsd"));
    // create a validator
    Validator validator = schema.newValidator();

    // loop the xml files in the folder
    for (File xmlFile : dir.listFiles(xmlFilenameFilter)) {

        // get a scanner to read the file
        Scanner fileScanner = new Scanner(xmlFile).useDelimiter("\\A");

        // read the xml into a string
        String xml = fileScanner.next();

        // close the scanner (and file)
        fileScanner.close();

        // validate the control xml file against the schema
        validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));

        // create a theme object from the xml
        Theme theme = new Theme(xml);

        // add it to our collection
        themes.add(theme);

        // inc the template count
        themeCount++;

    }

    // sort the list of templates by name
    Collections.sort(themes, new Comparator<Theme>() {
        @Override
        public int compare(Theme t1, Theme t2) {
            return Comparators.AsciiCompare(t1.getName(), t2.getName(), false);
        }

    });

    // put the jsonControls in a context attribute (this is available via the getJsonControls method in RapidHttpServlet)
    servletContext.setAttribute("themes", themes);

    _logger.info(themeCount + " templates loaded in .template.xml files");

    return themeCount;

}

From source file:ddf.test.itests.platform.TestSingleSignOn.java

private void validateSaml(String xml, SamlSchema schema) throws IOException {

    // Prepare the schema and xml
    String schemaFileName = "saml-schema-" + schema.toString().toLowerCase() + "-2.0.xsd";
    URL schemaURL = getClass().getClassLoader().getResource(schemaFileName);
    StreamSource streamSource = new StreamSource(new StringReader(xml));

    // If we fail to create a validator we don't want to stop the show, so we just log a warning
    Validator validator = null;
    try {/*from   ww  w .  jav a 2 s  .  com*/
        validator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaURL)
                .newValidator();
    } catch (SAXException e) {
        LOGGER.warn("Exception creating validator. ", e);
    }

    // If the xml is invalid, then we want to fail completely
    if (validator != null) {
        try {
            validator.validate(streamSource);
        } catch (SAXException e) {
            fail("Failed to validate SAML " + e.getMessage());
        }
    }
}

From source file:InlineSchemaValidator.java

public void validate(Validator validator, Source source, String systemId, int repetitions,
        boolean memoryUsage) {
    try {/* w w w  .  j  a v  a  2  s .  com*/
        long timeBefore = System.currentTimeMillis();
        long memoryBefore = Runtime.getRuntime().freeMemory();
        for (int j = 0; j < repetitions; ++j) {
            validator.validate(source);
        }
        long memoryAfter = Runtime.getRuntime().freeMemory();
        long timeAfter = System.currentTimeMillis();

        long time = timeAfter - timeBefore;
        long memory = memoryUsage ? memoryBefore - memoryAfter : Long.MIN_VALUE;
        printResults(fOut, systemId, time, memory, repetitions);
    } catch (SAXParseException e) {
        // ignore
    } catch (Exception e) {
        System.err.println("error: Parse error occurred - " + e.getMessage());
        Exception se = e;
        if (e instanceof SAXException) {
            se = ((SAXException) e).getException();
        }
        if (se != null)
            se.printStackTrace(System.err);
        else
            e.printStackTrace(System.err);

    }
}

From source file:com.rapid.server.RapidServletContextListener.java

public static int loadControls(ServletContext servletContext) throws Exception {

    // assume no controls
    int controlCount = 0;

    // create a list for our controls
    List<JSONObject> jsonControls = new ArrayList<JSONObject>();

    // get the directory in which the control xml files are stored
    File dir = new File(servletContext.getRealPath("/WEB-INF/controls/"));

    // create a filter for finding .control.xml files
    FilenameFilter xmlFilenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".control.xml");
        }//from  www. j  a v a 2  s  . com
    };

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/control.xsd"));
    // create a validator
    Validator validator = schema.newValidator();

    // loop the xml files in the folder
    for (File xmlFile : dir.listFiles(xmlFilenameFilter)) {

        // get a scanner to read the file
        Scanner fileScanner = new Scanner(xmlFile).useDelimiter("\\A");

        // read the xml into a string
        String xml = fileScanner.next();

        // close the scanner (and file)
        fileScanner.close();

        // validate the control xml file against the schema
        validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));

        // convert the string into JSON
        JSONObject jsonControlCollection = org.json.XML.toJSONObject(xml).getJSONObject("controls");

        JSONObject jsonControl;
        int index = 0;
        int count = 0;

        if (jsonControlCollection.optJSONArray("control") == null) {
            jsonControl = jsonControlCollection.getJSONObject("control");
        } else {
            jsonControl = jsonControlCollection.getJSONArray("control").getJSONObject(index);
            count = jsonControlCollection.getJSONArray("control").length();
        }

        do {

            // check this type does not already exist
            for (int i = 0; i < jsonControls.size(); i++) {
                if (jsonControl.getString("type").equals(jsonControls.get(i).getString("type")))
                    throw new Exception(" control type is loaded already. Type names must be unique");
            }

            // add the jsonControl to our array
            jsonControls.add(jsonControl);

            // inc the control count
            controlCount++;
            // inc the count of controls in this file
            index++;

            // get the next one
            if (index < count)
                jsonControl = jsonControlCollection.getJSONArray("control").getJSONObject(index);

        } while (index < count);

    }

    // sort the list of controls by name
    Collections.sort(jsonControls, new Comparator<JSONObject>() {
        @Override
        public int compare(JSONObject c1, JSONObject c2) {
            try {
                return Comparators.AsciiCompare(c1.getString("name"), c2.getString("name"), false);
            } catch (JSONException e) {
                return 0;
            }
        }

    });

    // create a JSON Array object which will hold json for all of the available controls
    JSONArray jsonArrayControls = new JSONArray(jsonControls);

    // put the jsonControls in a context attribute (this is available via the getJsonControls method in RapidHttpServlet)
    servletContext.setAttribute("jsonControls", jsonArrayControls);

    _logger.info(controlCount + " controls loaded in .control.xml files");

    return controlCount;

}

From source file:com.rapid.server.RapidServletContextListener.java

public static int loadActions(ServletContext servletContext) throws Exception {

    // assume no actions
    int actionCount = 0;

    // create a list of json actions which we will sort later
    List<JSONObject> jsonActions = new ArrayList<JSONObject>();

    // retain our class constructors in a hashtable - this speeds up initialisation
    HashMap<String, Constructor> actionConstructors = new HashMap<String, Constructor>();

    // build a collection of classes so we can re-initilise the JAXB context to recognise our injectable classes
    ArrayList<Action> actions = new ArrayList<Action>();

    // get the directory in which the control xml files are stored
    File dir = new File(servletContext.getRealPath("/WEB-INF/actions/"));

    // create a filter for finding .control.xml files
    FilenameFilter xmlFilenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".action.xml");
        }/*w  w w  . ja v a 2s. com*/
    };

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/action.xsd"));
    // create a validator
    Validator validator = schema.newValidator();

    // loop the xml files in the folder
    for (File xmlFile : dir.listFiles(xmlFilenameFilter)) {

        // get a scanner to read the file
        Scanner fileScanner = new Scanner(xmlFile).useDelimiter("\\A");

        // read the xml into a string
        String xml = fileScanner.next();

        // close the scanner (and file)
        fileScanner.close();

        // validate the control xml file against the schema
        validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));

        // convert the string into JSON
        JSONObject jsonActionCollection = org.json.XML.toJSONObject(xml).getJSONObject("actions");

        JSONObject jsonAction;
        int index = 0;
        int count = 0;

        // the JSON library will add a single key of there is a single class, otherwise an array
        if (jsonActionCollection.optJSONArray("action") == null) {
            jsonAction = jsonActionCollection.getJSONObject("action");
        } else {
            jsonAction = jsonActionCollection.getJSONArray("action").getJSONObject(index);
            count = jsonActionCollection.getJSONArray("action").length();
        }

        do {

            // check this type does not already exist
            for (int i = 0; i < jsonActions.size(); i++) {
                if (jsonAction.getString("type").equals(jsonActions.get(i).getString("type")))
                    throw new Exception(" action type is loaded already. Type names must be unique");
            }

            // add the jsonControl to our array
            jsonActions.add(jsonAction);
            // get the named type from the json
            String type = jsonAction.getString("type");
            // get the class name from the json
            String className = jsonAction.getString("class");
            // get the class 
            Class classClass = Class.forName(className);
            // check the class extends com.rapid.Action
            if (!Classes.extendsClass(classClass, com.rapid.core.Action.class))
                throw new Exception(type + " action class " + classClass.getCanonicalName()
                        + " must extend com.rapid.core.Action.");
            // check this type is unique
            if (actionConstructors.get(type) != null)
                throw new Exception(type + " action already loaded. Type names must be unique.");
            // add to constructors hashmap referenced by type
            actionConstructors.put(type, classClass.getConstructor(RapidHttpServlet.class, JSONObject.class));
            // add to our jaxb classes collection            
            _jaxbClasses.add(classClass);
            // inc the control count
            actionCount++;
            // inc the count of controls in this file
            index++;

            // get the next one
            if (index < count)
                jsonAction = jsonActionCollection.getJSONArray("control").getJSONObject(index);

        } while (index < count);

    }

    // sort the list of actions by name
    Collections.sort(jsonActions, new Comparator<JSONObject>() {
        @Override
        public int compare(JSONObject c1, JSONObject c2) {
            try {
                return Comparators.AsciiCompare(c1.getString("name"), c2.getString("name"), false);
            } catch (JSONException e) {
                return 0;
            }
        }

    });

    // create a JSON Array object which will hold json for all of the available controls
    JSONArray jsonArrayActions = new JSONArray(jsonActions);

    // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet)
    servletContext.setAttribute("jsonActions", jsonArrayActions);

    // put the constructors hashmapin a context attribute (this is available via the getContructor method in RapidHttpServlet)
    servletContext.setAttribute("actionConstructors", actionConstructors);

    _logger.info(actionCount + " actions loaded in .action.xml files");

    return actionCount;

}

From source file:integration.AbstractTest.java

/**
 * Parses the specified file and returns the document.
 * /*from www  . j a v  a2 s  .  co  m*/
 * @param file The file to parse.
 * @param schemaStreamArray The schema as array of stream sources used to validate the specified file.
 * @return
 * @throws Exception Thrown if an error occurred.
 */
protected Document parseFileWithStreamArray(File file, StreamSource[] schemaStreamArray) throws Exception {
    if (file == null)
        throw new IllegalArgumentException("No file to parse.");

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true); // This must be set to avoid error : cvc-elt.1: Cannot find the declaration of element 'OME'.
    SchemaFactory sFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SchemaResolver theTestClassResolver = new SchemaResolver();
    sFactory.setResourceResolver(theTestClassResolver);

    Schema theSchema = sFactory.newSchema(schemaStreamArray);

    /*
    // Version - one step parse and validate (print error to stdErr)
    dbf.setSchema(theSchema);
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document theDoc = builder.parse(file);
    */

    // Version - two step parse then validate (throws error as exception)
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document theDoc = builder.parse(file);
    Validator validator = theSchema.newValidator();
    validator.validate(new DOMSource(theDoc));
    return theDoc;
}

From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java

/**
 * Validate xml./*from w  w w . java  2  s .co m*/
 * 
 * @param inSchemas the in schemas
 * @param inXml the in xml
 * @param schemaLanguage the schema language
 * 
 * @return the xML error handler
 * 
 * @throws MotuException the motu exception
 */
public static XMLErrorHandler validateXML(InputStream[] inSchemas, InputStream inXml, String schemaLanguage)
        throws MotuException {
    // parse an XML document into a DOM tree
    Document document;
    // create a Validator instance, which can be used to validate an instance document
    Validator validator;
    XMLErrorHandler errorHandler = new XMLErrorHandler();

    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true); // Must enable namespace processing!!!!!
        try {
            documentBuilderFactory.setXIncludeAware(true);
        } catch (Exception e) {
            // Do Nothing
        }
        // documentBuilderFactory.setExpandEntityReferences(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // document = documentBuilder.parse(new File(xmlUrl.toURI()));
        documentBuilder.setErrorHandler(errorHandler);
        document = documentBuilder.parse(inXml);

        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
        schemaFactory.setErrorHandler(errorHandler);

        // load a WXS schema, represented by a Schema instance

        Source[] schemaFiles = new Source[inSchemas.length];

        // InputStream inShema = null;
        int i = 0;
        for (InputStream inSchema : inSchemas) {
            schemaFiles[i] = new StreamSource(inSchema);
            i++;
        }

        Schema schema = schemaFactory.newSchema(schemaFiles);

        validator = schema.newValidator();
        validator.setErrorHandler(errorHandler);
        validator.validate(new DOMSource(document));

    } catch (Exception e) {
        throw new MotuException(e);
        // instance document is invalid!
    }

    return errorHandler;
}