Example usage for javax.xml.validation SchemaFactory newInstance

List of usage examples for javax.xml.validation SchemaFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.validation SchemaFactory newInstance.

Prototype

public static SchemaFactory newInstance(String schemaLanguage) 

Source Link

Document

Lookup an implementation of the SchemaFactory that supports the specified schema language and return it.

Usage

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

@Override
public void contextInitialized(ServletContextEvent event) {

    // request windows line breaks to make the files easier to edit (in particular the marshalled .xml files)
    System.setProperty("line.separator", "\r\n");

    // get a reference to the servlet context
    ServletContext servletContext = event.getServletContext();

    // set up logging
    try {//from w ww . j  a  v  a  2  s .  c  o m

        // set the log path
        System.setProperty("logPath", servletContext.getRealPath("/") + "/WEB-INF/logs/Rapid.log");

        // get a logger
        _logger = Logger.getLogger(RapidHttpServlet.class);

        // set the logger and store in servletConext
        servletContext.setAttribute("logger", _logger);

        // log!
        _logger.info("Logger created");

    } catch (Exception e) {

        System.err.println("Error initilising logging : " + e.getMessage());

        e.printStackTrace();
    }

    try {

        // we're looking for a password and salt for the encryption
        char[] password = null;
        byte[] salt = null;
        // look for the rapid.txt file with the saved password and salt
        File secretsFile = new File(servletContext.getRealPath("/") + "/WEB-INF/security/encryption.txt");
        // if it exists
        if (secretsFile.exists()) {
            // get a file reader
            BufferedReader br = new BufferedReader(new FileReader(secretsFile));
            // read the first line
            String className = br.readLine();
            // read the next line
            String s = br.readLine();
            // close the reader
            br.close();

            try {
                // get the class 
                Class classClass = Class.forName(className);
                // get the interfaces
                Class[] classInterfaces = classClass.getInterfaces();
                // assume it doesn't have the interface we want
                boolean gotInterface = false;
                // check we got some
                if (classInterfaces != null) {
                    for (Class classInterface : classInterfaces) {
                        if (com.rapid.utils.Encryption.EncryptionProvider.class.equals(classInterface)) {
                            gotInterface = true;
                            break;
                        }
                    }
                }
                // check the class extends com.rapid.Action
                if (gotInterface) {
                    // get the constructors
                    Constructor[] classConstructors = classClass.getDeclaredConstructors();
                    // check we got some
                    if (classConstructors != null) {
                        // assume we don't get the parameterless one we need
                        Constructor constructor = null;
                        // loop them
                        for (Constructor classConstructor : classConstructors) {
                            // check parameters
                            if (classConstructor.getParameterTypes().length == 0) {
                                constructor = classConstructor;
                                break;
                            }
                        }
                        // check we got what we want
                        if (constructor == null) {
                            _logger.error(
                                    "Encyption not initialised : Class in security.txt class must have a parameterless constructor");
                        } else {
                            // construct the class
                            EncryptionProvider encryptionProvider = (EncryptionProvider) constructor
                                    .newInstance();
                            // get the password
                            password = encryptionProvider.getPassword();
                            // get the salt
                            salt = encryptionProvider.getSalt();
                            // log
                            _logger.info("Encyption initialised");
                        }
                    }
                } else {
                    _logger.error(
                            "Encyption not initialised : Class in security.txt class must extend com.rapid.utils.Encryption.EncryptionProvider");
                }
            } catch (Exception ex) {
                _logger.error("Encyption not initialised : " + ex.getMessage(), ex);
            }
        } else {
            _logger.info("Encyption not initialised");
        }

        // create the encypted xml adapter (if the file above is not found there no encryption will occur)
        RapidHttpServlet.setEncryptedXmlAdapter(new EncryptedXmlAdapter(password, salt));

        // initialise the schema factory (we'll reuse it in the various loaders)
        _schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        // initialise the list of classes we're going to want in the JAXB context (the loaders will start adding to it)
        _jaxbClasses = new ArrayList<Class>();

        _logger.info("Loading database drivers");

        // load the database drivers first
        loadDatabaseDrivers(servletContext);

        _logger.info("Loading connection adapters");

        // load the connection adapters 
        loadConnectionAdapters(servletContext);

        _logger.info("Loading security adapters");

        // load the security adapters 
        loadSecurityAdapters(servletContext);

        _logger.info("Loading form adapters");

        // load the form adapters
        loadFormAdapters(servletContext);

        _logger.info("Loading actions");

        // load the actions 
        loadActions(servletContext);

        _logger.info("Loading templates");

        // load templates
        loadThemes(servletContext);

        _logger.info("Loading controls");

        // load the controls 
        loadControls(servletContext);

        // add some classes manually
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.NameRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.EnumerationRestriction.class);
        _jaxbClasses.add(com.rapid.soa.Webservice.class);
        _jaxbClasses.add(com.rapid.soa.SQLWebservice.class);
        _jaxbClasses.add(com.rapid.soa.JavaWebservice.class);
        _jaxbClasses.add(com.rapid.core.Validation.class);
        _jaxbClasses.add(com.rapid.core.Action.class);
        _jaxbClasses.add(com.rapid.core.Event.class);
        _jaxbClasses.add(com.rapid.core.Style.class);
        _jaxbClasses.add(com.rapid.core.Control.class);
        _jaxbClasses.add(com.rapid.core.Page.class);
        _jaxbClasses.add(com.rapid.core.Application.class);
        _jaxbClasses.add(com.rapid.core.Device.class);
        _jaxbClasses.add(com.rapid.core.Device.Devices.class);

        // convert arraylist to array
        Class[] classes = _jaxbClasses.toArray(new Class[_jaxbClasses.size()]);
        // re-init the JAXB context to include our injectable classes               
        JAXBContext jaxbContext = JAXBContext.newInstance(classes);

        // this logs the JAXB classes
        _logger.trace("JAXB  content : " + jaxbContext.toString());

        // store the jaxb context in RapidHttpServlet
        RapidHttpServlet.setJAXBContext(jaxbContext);

        // load the devices
        Devices.load(servletContext);

        // load the applications!
        loadApplications(servletContext);

        // add some useful global objects 
        servletContext.setAttribute("xmlDateFormatter", new SimpleDateFormat("yyyy-MM-dd"));
        servletContext.setAttribute("xmlDateTimeFormatter", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));

        String localDateFormat = servletContext.getInitParameter("localDateFormat");
        if (localDateFormat == null)
            localDateFormat = "dd/MM/yyyy";
        servletContext.setAttribute("localDateFormatter", new SimpleDateFormat(localDateFormat));

        String localDateTimeFormat = servletContext.getInitParameter("localDateTimeFormat");
        if (localDateTimeFormat == null)
            localDateTimeFormat = "dd/MM/yyyy HH:mm a";
        servletContext.setAttribute("localDateTimeFormatter", new SimpleDateFormat(localDateTimeFormat));

        boolean actionCache = Boolean.parseBoolean(servletContext.getInitParameter("actionCache"));
        if (actionCache)
            servletContext.setAttribute("actionCache", new ActionCache(servletContext));

        int pageAgeCheckInterval = MONITOR_CHECK_INTERVAL;
        try {
            String pageAgeCheckIntervalString = servletContext.getInitParameter("pageAgeCheckInterval");
            if (pageAgeCheckIntervalString != null)
                pageAgeCheckInterval = Integer.parseInt(pageAgeCheckIntervalString);
        } catch (Exception ex) {
            _logger.error("pageAgeCheckInterval is not an integer");
        }

        int pageMaxAge = MONITOR_MAX_AGE;
        try {
            String pageMaxAgeString = servletContext.getInitParameter("pageMaxAge");
            if (pageMaxAgeString != null)
                pageMaxAge = Integer.parseInt(pageMaxAgeString);
        } catch (Exception ex) {
            _logger.error("pageMaxAge is not an integer");
        }

        // start the monitor
        _monitor = new Monitor(servletContext, pageAgeCheckInterval, pageMaxAge);
        _monitor.start();

        // allow calling to https without checking certs (for now)
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = new TrustManager[] { new Https.TrustAllCerts() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    } catch (Exception ex) {

        _logger.error("Error loading applications : " + ex.getMessage());

        ex.printStackTrace();
    }

}

From source file:org.keycloak.testsuite.adapter.servlet.AbstractSAMLServletsAdapterTest.java

private void validateXMLWithSchema(String xml, String schemaFileName) throws SAXException, IOException {
    URL schemaFile = getClass().getResource(schemaFileName);

    Source xmlFile = new StreamSource(new ByteArrayInputStream(xml.getBytes()), xml);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    try {/*  w w w.j a va 2  s  . c  o m*/
        validator.validate(xmlFile);
        System.out.println(xmlFile.getSystemId() + " is valid");
    } catch (SAXException e) {
        System.out.println(xmlFile.getSystemId() + " is NOT valid");
        System.out.println("Reason: " + e.getLocalizedMessage());
        Assert.fail();
    }
}

From source file:ch.entwine.weblounge.common.impl.site.SiteImpl.java

/**
 * Loads and registers the integration tests that are found in the bundle at
 * the given location./*  www. j  a va  2s .  c o m*/
 * 
 * @param dir
 *          the directory containing the test files
 */
private List<IntegrationTest> loadIntegrationTestDefinitions(String dir) {
    Enumeration<?> entries = bundleContext.getBundle().findEntries(dir, "*.xml", true);

    // Schema validator setup
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = SiteImpl.class.getResource("/xsd/test.xsd");
    Schema testSchema = null;
    try {
        testSchema = schemaFactory.newSchema(schemaUrl);
    } catch (SAXException e) {
        logger.error("Error loading XML schema for test definitions: {}", e.getMessage());
        return Collections.emptyList();
    }

    // Module.xml document builder setup
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setSchema(testSchema);
    docBuilderFactory.setNamespaceAware(true);

    // The list of tests
    List<IntegrationTest> tests = new ArrayList<IntegrationTest>();

    while (entries != null && entries.hasMoreElements()) {
        URL entry = (URL) entries.nextElement();

        // Validate and read the module descriptor
        ValidationErrorHandler errorHandler = new ValidationErrorHandler(entry);
        DocumentBuilder docBuilder;

        try {
            docBuilder = docBuilderFactory.newDocumentBuilder();
            docBuilder.setErrorHandler(errorHandler);
            Document doc = docBuilder.parse(entry.openStream());
            if (errorHandler.hasErrors()) {
                logger.warn("Error parsing integration test {}: XML validation failed", entry);
                continue;
            }
            IntegrationTestGroup test = IntegrationTestParser.fromXml(doc.getFirstChild());
            test.setSite(this);
            test.setGroup(getName());
            tests.add(test);
        } catch (SAXException e) {
            throw new IllegalStateException(e);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        } catch (ParserConfigurationException e) {
            throw new IllegalStateException(e);
        }
    }

    return tests;
}

From source file:fll.scheduler.TournamentSchedule.java

/**
 * Validate the schedule XML document./*w  w w .  j  a v a2 s.c o  m*/
 * 
 * @throws SAXException on an error
 */
public static void validateXML(final org.w3c.dom.Document document) throws SAXException {
    try {
        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Source schemaFile = new StreamSource(
                classLoader.getResourceAsStream("fll/resources/schedule.xsd"));
        final Schema schema = factory.newSchema(schemaFile);

        final Validator validator = schema.newValidator();
        validator.validate(new DOMSource(document));
    } catch (final IOException e) {
        throw new RuntimeException("Internal error, should never get IOException here", e);
    }

}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Gets the <code>Schema</code> object for the provided <code>InputStream</code>.
 * //from  w ww  .j a va2 s . c  om
 * @param schemaStream
 *            The Stream containing the schema.
 * @return Returns the <code>Schema</code> object.
 * @throws Exception
 *             If anything fails.
 */
private static Schema getSchema(final InputStream schemaStream) throws Exception {

    if (schemaStream == null) {
        throw new Exception("No schema input stream provided");
    }

    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    // set resource resolver to change schema-location-host
    sf.setResourceResolver(new SchemaBaseResourceResolver());
    Schema theSchema = sf.newSchema(new SAXSource(new InputSource(schemaStream)));
    return theSchema;
}

From source file:it.isislab.dmason.util.SystemManagement.Master.thrower.DMasonMaster.java

private static boolean validateXML(File configFile, InputStream xsdFile) throws IOException {
    Source schemaFile = new StreamSource(xsdFile);
    Source xmlFile = new StreamSource(configFile);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    try {/*from  w  w w.jav a  2 s. co m*/

        Schema schema = schemaFactory.newSchema(schemaFile);
        Validator validator = schema.newValidator();
        validator.validate(xmlFile);
        return true;
        //System.out.println(xmlFile.getSystemId() + " is valid");
    } catch (SAXException e) {
        //System.out.println(xmlFile.getSystemId() + " is NOT valid");
        //System.out.println("Reason: " + e.getLocalizedMessage());
        return false;
    }
}

From source file:net.sourceforge.pmd.testframework.RuleTst.java

public RuleTst() {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema;/*from  www  .  j a  v a 2 s  . c o m*/
    try {
        schema = schemaFactory.newSchema(RuleTst.class.getResource("/rule-tests_1_0_0.xsd"));
        dbf.setSchema(schema);
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = dbf.newDocumentBuilder();
        builder.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw exception;
            }

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

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw exception;
            }
        });
        documentBuilder = builder;
    } catch (SAXException | ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:nl.armatiek.xslweb.configuration.Context.java

private void initXMLSchemas() throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    File schemaFile = new File(homeDir, "config/xsd/xslweb/webapp.xsd");
    if (!schemaFile.isFile()) {
        logger.warn(String.format("XML Schema \"%s\" not found", schemaFile.getAbsolutePath()));
    } else {//from   www.  j  a  v a 2  s. c om
        webAppSchema = factory.newSchema(schemaFile);
    }
}

From source file:nl.b3p.viewer.admin.stripes.GeoServiceActionBean.java

public Resolution validateSldXml() {
    Resolution jsp = new ForwardResolution(JSP_EDIT_SLD);
    Document sldXmlDoc = null;/*from   w  ww.  j  a  v  a2s  . c om*/
    String stage = "Fout bij parsen XML document";
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();

        sldXmlDoc = db.parse(new ByteArrayInputStream(sld.getSldBody().getBytes("UTF-8")));

        stage = "Fout bij controleren SLD";

        Element root = sldXmlDoc.getDocumentElement();
        if (!"StyledLayerDescriptor".equals(root.getLocalName())) {
            throw new Exception("Root element moet StyledLayerDescriptor zijn");
        }
        String version = root.getAttribute("version");
        if (version == null || !("1.0.0".equals(version) || "1.1.0".equals(version))) {
            throw new Exception("Geen of ongeldige SLD versie!");
        }

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema s = sf
                .newSchema(new URL("http://schemas.opengis.net/sld/" + version + "/StyledLayerDescriptor.xsd"));
        s.newValidator().validate(new DOMSource(sldXmlDoc));

    } catch (Exception e) {
        String extra = "";
        if (e instanceof SAXParseException) {
            SAXParseException spe = (SAXParseException) e;
            if (spe.getLineNumber() != -1) {
                extra = " (regel " + spe.getLineNumber();
                if (spe.getColumnNumber() != -1) {
                    extra += ", kolom " + spe.getColumnNumber();
                }
                extra += ")";
            }
        }
        getContext().getValidationErrors()
                .addGlobalError(new SimpleError("{2}: {3}{4}", stage, ExceptionUtils.getMessage(e), extra));
        return jsp;
    }

    getContext().getMessages().add(new SimpleMessage("SLD is valide!"));

    return jsp;
}

From source file:nl.clockwork.mule.common.filter.AbstractXSDValidationFilter.java

public void setXsdFile(String xsdFile) {
    try {/* www .  j  a  va  2  s  .co m*/
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        //schema = factory.newSchema(new StreamSource(this.getClass().getResourceAsStream(xsdFile)));
        String systemId = this.getClass().getResource(xsdFile).toString();
        schema = factory.newSchema(new StreamSource(this.getClass().getResourceAsStream(xsdFile), systemId));
    } catch (SAXException e) {
        logger.fatal("", e);
        throw new RuntimeException(e);
    }
}