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:org.tinygroup.jspengine.xmlparser.ParserUtils.java

private static Schema getSchema(String schemaPublicId) throws SAXException {

    Schema schema = schemaCache.get(schemaPublicId);
    if (schema == null) {
        synchronized (schemaCache) {
            schema = schemaCache.get(schemaPublicId);
            if (schema == null) {
                SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                schemaFactory.setResourceResolver(new MyLSResourceResolver());
                schemaFactory.setErrorHandler(new MyErrorHandler());
                schema = schemaFactory.newSchema(new StreamSource(
                        ParserUtils.class.getResourceAsStream(schemaResourcePrefix + schemaPublicId)));
                schemaCache.put(schemaPublicId, schema);
            }//from  w  w  w.j a  v a  2 s  . c om
        }
    }

    return schema;
}

From source file:org.tridas.io.formats.tridasjson.TridasJSONFile.java

public void validate() throws ImpossibleConversionException {
    Schema schema = null;/*from  w  ww . j  a v a 2  s  . c om*/

    // Validate output against schema first
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL file = IOUtils.getFileInJarURL("schemas/tridas.xsd");
    if (file == null) {
        log.error("Could not find schema file");
    } else {
        try {
            schema = factory.newSchema(file);
        } catch (SAXException e) {
            log.error("Error getting TRiDaS schema for validation, not using.", e);
            throw new ImpossibleConversionException(I18n.getText("fileio.errorGettingSchema"));
        }
    }

    swriter = new StringWriter();
    // Marshaller code goes here...
    JAXBContext jc;
    try {
        jc = JAXBContext.newInstance("org.tridas.schema");
        Marshaller m = jc.createMarshaller();
        m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new TridasNamespacePrefixMapper());
        if (schema != null) {
            m.setSchema(schema);
        }
        m.marshal(getTridasContainer(), swriter);

    } catch (Exception e) {
        log.error("Jaxb error", e);

        String cause = e.getCause().getMessage();
        if (cause != null) {
            throw new ImpossibleConversionException(I18n.getText("fileio.jaxbError") + " " + cause);
        } else {
            throw new ImpossibleConversionException(I18n.getText("fileio.jaxbError"));
        }

    }

}

From source file:org.voltdb.compiler.VoltCompiler.java

/**
 * Read the project file and get the database object.
 * @param projectFileURL  project file URL/path
 * @return  database for project or null
 *///from   ww w  .j  av a2 s  .  c o  m
private DatabaseType getProjectDatabase(final VoltCompilerReader projectReader) {
    DatabaseType database = null;
    if (projectReader != null) {
        m_currentFilename = projectReader.getName();
        try {
            JAXBContext jc = JAXBContext.newInstance("org.voltdb.compiler.projectfile");
            // This schema shot the sheriff.
            SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(this.getClass().getResource("ProjectFileSchema.xsd"));
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            // But did not shoot unmarshaller!
            unmarshaller.setSchema(schema);
            @SuppressWarnings("unchecked")
            JAXBElement<ProjectType> result = (JAXBElement<ProjectType>) unmarshaller.unmarshal(projectReader);
            ProjectType project = result.getValue();
            database = project.getDatabase();
        } catch (JAXBException e) {
            // Convert some linked exceptions to more friendly errors.
            if (e.getLinkedException() instanceof java.io.FileNotFoundException) {
                addErr(e.getLinkedException().getMessage());
                compilerLog.error(e.getLinkedException().getMessage());
            } else {
                DeprecatedProjectElement deprecated = DeprecatedProjectElement.valueOf(e);
                if (deprecated != null) {
                    addErr("Found deprecated XML element \"" + deprecated.name() + "\" in project.xml file, "
                            + deprecated.getSuggestion());
                    addErr("Error schema validating project.xml file. " + e.getLinkedException().getMessage());
                    compilerLog.error(
                            "Found deprecated XML element \"" + deprecated.name() + "\" in project.xml file");
                    compilerLog.error(e.getMessage());
                    compilerLog.error(projectReader.getPath());
                } else if (e.getLinkedException() instanceof org.xml.sax.SAXParseException) {
                    addErr("Error schema validating project.xml file. " + e.getLinkedException().getMessage());
                    compilerLog.error(
                            "Error schema validating project.xml file: " + e.getLinkedException().getMessage());
                    compilerLog.error(e.getMessage());
                    compilerLog.error(projectReader.getPath());
                } else {
                    throw new RuntimeException(e);
                }
            }
        } catch (SAXException e) {
            addErr("Error schema validating project.xml file. " + e.getMessage());
            compilerLog.error("Error schema validating project.xml file. " + e.getMessage());
        }
    } else {
        // No project.xml - create a stub object.
        database = new DatabaseType();
    }

    return database;
}

From source file:org.wso2.carbon.apimgt.gateway.mediators.XMLSchemaValidator.java

/**
 * This method validates the request payload xml with the relevant xsd.
 *
 * @param messageContext      This message context contains the request message properties of the relevant
 *                            API which was enabled the XML_Validator message mediation in flow.
 * @param bufferedInputStream Buffered input stream to be validated.
 * @throws APIMThreatAnalyzerException Exception might be occurred while parsing the xml payload.
 *///from  w  w w .j a v a  2 s  .c  om
private boolean validateSchema(MessageContext messageContext, BufferedInputStream bufferedInputStream)
        throws APIMThreatAnalyzerException {
    String xsdURL;
    Schema schema;
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        Object messageProperty = messageContext.getProperty(APIMgtGatewayConstants.XSD_URL);
        if (messageProperty == null) {
            return true;
        } else {
            if (String.valueOf(messageProperty).isEmpty()) {
                return true;
            } else {
                xsdURL = String.valueOf(messageProperty);
                URL schemaFile = new URL(xsdURL);
                schema = schemaFactory.newSchema(schemaFile);
                Source xmlFile = new StreamSource(bufferedInputStream);
                Validator validator = schema.newValidator();
                validator.validate(xmlFile);
            }
        }
    } catch (SAXException | IOException e) {
        throw new APIMThreatAnalyzerException("Error occurred while parsing XML payload : " + e);
    }
    return true;
}

From source file:org.wso2.carbon.automation.engine.test.configuration.ConfigurationXSDValidatorTest.java

@Test(groups = "context.unit.test", description = "Upload aar service and verify deployment")
public void validateAutomationXml() throws IOException, SAXException {
    boolean validated = false;
    URL schemaFile = validateXsdFile.toURI().toURL();
    Source xmlFile = new StreamSource(configXmlFile);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    try {/* w  w  w.ja va2  s.  c  o m*/
        validator.validate(xmlFile);
        validated = true;

    } catch (SAXException e) {
        log.error(e.getStackTrace());
        throw new SAXException(e);
    }
    Assert.assertTrue(validated);

}

From source file:org.wso2.carbon.device.mgt.core.api.mgt.config.APIPublisherConfig.java

private static Schema getSchema() throws DeviceManagementException {
    try {/*ww w  . ja  v  a 2 s  .  com*/
        File deviceManagementSchemaConfig = new File(APIPublisherConfig.USER_DEFINED_API_CONFIG_SCHEMA_PATH);
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        return factory.newSchema(deviceManagementSchemaConfig);
    } catch (SAXException e) {
        throw new DeviceManagementException(
                "Error occurred while initializing the schema of " + "user-api-publisher-config.xml", e);
    }
}

From source file:org.wso2.carbon.device.mgt.core.app.mgt.AppManagementConfigurationManagerTest.java

@BeforeClass
private void initSchema() {
    File deviceManagementSchemaConfig = new File(
            AppManagementConfigurationManagerTest.TEST_CONFIG_SCHEMA_LOCATION);
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {/*w ww.j a  v a 2 s  .  co  m*/
        schema = factory.newSchema(deviceManagementSchemaConfig);
    } catch (SAXException e) {
        Assert.fail("Invalid schema found", e);
    }
}

From source file:org.wso2.carbon.device.mgt.core.DeviceManagementConfigTests.java

@BeforeClass
private void initSchema() {
    File deviceManagementSchemaConfig = new File(DeviceManagementConfigTests.TEST_CONFIG_SCHEMA_LOCATION);
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {/*from ww  w. ja va 2 s.  c  o  m*/
        schema = factory.newSchema(deviceManagementSchemaConfig);
    } catch (SAXException e) {
        Assert.fail("Invalid schema found", e);
    }
}

From source file:org.wso2.carbon.device.mgt.etc.config.devicetype.DeviceTypeConfigurationManager.java

public synchronized void initConfig() throws DeviceManagementException {
    try {// ww w.  j  av a 2s  .  c om
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(deviceMgtConfigXSDPath));

        File iotDeviceMgtConfig = new File(deviceMgtConfigXMLPath);
        Document doc = IotDeviceManagementUtil.convertToDocument(iotDeviceMgtConfig);
        JAXBContext iotDeviceMgmtContext = JAXBContext.newInstance(DeviceTypeConfigManager.class);
        Unmarshaller unmarshaller = iotDeviceMgmtContext.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new IotConfigValidationEventHandler());
        this.currentDeviceTypeConfig = (DeviceTypeConfigManager) unmarshaller.unmarshal(doc);

        List<DeviceTypeConfig> iotDeviceTypeConfigList = currentDeviceTypeConfig.getDeviceTypeConfigs();
        for (DeviceTypeConfig iotDeviceTypeConfig : iotDeviceTypeConfigList) {
            String applicationName = iotDeviceTypeConfig.getApiApplicationName();

            if (applicationName == null || applicationName.isEmpty()) {
                iotDeviceTypeConfig.setApiApplicationName(iotDeviceTypeConfig.getType());
            }
            deviceTypeConfigMap.put(iotDeviceTypeConfig.getType(), iotDeviceTypeConfig);
        }
        ApisAppClient.getInstance().setBase64EncodedConsumerKeyAndSecret(iotDeviceTypeConfigList);
    } catch (Exception e) {
        String error = "Error occurred while initializing device configurations";
        log.error(error, e);
    }
}

From source file:org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager.java

public void initConfig() throws DeviceControllerException {
    try {/*from ww  w  . j  a v a2 s.co m*/
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(XSDCONFIGS_FILE_LOCATION));

        File deviceCloudMgtConfig = new File(XMLCONFIGS_FILE_LOCATION);
        Document doc = IotDeviceManagementUtil.convertToDocument(deviceCloudMgtConfig);
        JAXBContext deviceCloudContext = JAXBContext.newInstance(DeviceCloudConfig.class);
        Unmarshaller unmarshaller = deviceCloudContext.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new IotConfigValidationEventHandler());
        this.currentDeviceCloudConfig = (DeviceCloudConfig) unmarshaller.unmarshal(doc);
    } catch (Exception e) {
        String error = "Error occurred while initializing DeviceController configurations";
        log.error(error);
        throw new DeviceControllerException(error, e);
    }
}