Example usage for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI

List of usage examples for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI

Introduction

In this page you can find the example usage for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI.

Prototype

String W3C_XML_SCHEMA_NS_URI

To view the source code for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI.

Click Source Link

Document

W3C XML Schema Namespace URI.

Usage

From source file:eu.europa.esig.dss.DSSXMLUtils.java

private static Schema getSchema() throws SAXException {

    final ResourceLoader resourceLoader = new ResourceLoader();
    final InputStream xadesXsd = resourceLoader.getResource(XAD_ESV141_XSD);
    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    return factory.newSchema(new StreamSource(xadesXsd));
}

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * @throws IOException//from w  w  w.java 2s . co m
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private static void initializeSchemas() throws IOException, SAXException, ParserConfigurationException {
    File[] schemaFiles = ResourceUtil.getFilenamesInDirectory("xsd/", TestBase.class.getClassLoader());
    schemas = new HashMap<String, Schema>();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    for (File file : schemaFiles) {
        try {
            Schema schema = sf.newSchema(file);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            DefaultHandler handler = new DefaultHandler() {
                private String nameSpace = null;
                private boolean found = false;

                public void startElement(String uri, String localName, String qName, Attributes attributes) {
                    if (!found) {
                        String tagName = null;
                        int ix = qName.indexOf(":");
                        if (ix >= 0) {
                            tagName = qName.substring(ix + 1);
                        } else {
                            tagName = qName;
                        }
                        if ("schema".equals(tagName)) {
                            nameSpace = attributes.getValue("targetNamespace");
                            found = true;
                        }
                    }
                }

                public String toString() {
                    return nameSpace;
                }
            };
            parser.parse(file, handler);
            if (handler.toString() != null) {
                schemas.put(handler.toString(), schema);
            } else {
                logger.warn("Error reading xml schema: " + file);
            }

        } catch (Exception e) {
            logger.warn("Invalid xml schema " + file);
            logger.debug("Stacktrace: ", e);
        }

    }
}

From source file:jeeves.utils.Xml.java

private static SchemaFactory factory() {
    return SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
}

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * Gets the <code>Schema</code> object for the provided <code>File</code>.
 * /*from   www .ja  v  a  2  s .  com*/
 * @param schemaStream The file containing the schema.
 * @return Returns the <code>Schema</code> object.
 * @throws Exception If anything fails.
 */
private static Schema getSchema(final String schemaFileName) throws Exception {
    if (schemaFileName == null) {
        throw new IllegalArgumentException(
                TestBase.class.getSimpleName() + ":getSchema:schemaFileName is null");
    }
    File schemaFile = new File(schemaFileName);

    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema theSchema = sf.newSchema(schemaFile);
    return theSchema;
}

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 {// ww w.  j a va 2  s.c om

        // 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 av  a 2s.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./*w w  w .j  a v a  2s  . c  om*/
 * 
 * @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.//from  www.  j  a  va  2  s.c om
 * 
 * @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  w w . jav  a 2  s. c  o m
 * @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  .j  av a2 s . c o  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;
    }
}