List of usage examples for javax.xml.validation SchemaFactory newSchema
public abstract Schema newSchema(Source[] schemas) throws SAXException;
From source file:org.sejda.core.context.XmlConfigurationStrategy.java
private void initializeSchemaValidation(DocumentBuilderFactory factory) throws SAXException { if (Boolean.getBoolean(Sejda.PERFORM_SCHEMA_VALIDATION_PROPERTY_NAME)) { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource( Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_SEJDA_CONFIG)) })); factory.setNamespaceAware(true); }//from ww w . j av a2 s .c o m }
From source file:org.silverpeas.core.importexport.control.ImportExport.java
/** * Mthode retournant l'arbre des objets mapps sur le fichier xml pass en paramtre. * @param xmlFileName le fichier xml interprt par JAXB * @return Un objet SilverPeasExchangeType contenant le mapping d'un fichier XML * @throws ImportExportException/*from w ww . j a v a2 s. c o m*/ */ private SilverPeasExchangeType loadSilverpeasExchange(String xmlFileName) throws ImportExportException { try { File xmlInputSource = new File(xmlFileName); String xsdSystemId = settings.getString("xsdDefaultSystemId"); SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new URL(xsdSystemId)); // Unmarshall the import model Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setSchema(schema); unmarshaller.setEventHandler(new ImportExportErrorHandler()); SilverPeasExchangeType silverpeasExchange = (SilverPeasExchangeType) unmarshaller .unmarshal(xmlInputSource); return silverpeasExchange; } catch (JAXBException me) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_UNMARSHALLING_FAILED", "XML Filename " + xmlFileName + ": " + me.getLocalizedMessage(), me); } catch (MalformedURLException ue) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_UNMARSHALLING_FAILED", "XML Filename " + xmlFileName + ": " + ue.getLocalizedMessage(), ue); } catch (SAXException ve) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + ve.getLocalizedMessage(), ve); } }
From source file:org.slc.sli.ingestion.parser.impl.EdfiRecordParserImpl2.java
public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor) throws SAXException, IOException, XmlParseException { EdfiRecordParserImpl2 parser = new EdfiRecordParserImpl2(); parser.addVisitor(visitor);//from w w w . jav a 2 s . c om parser.typeProvider = typeProvider; SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(schemaResource.getURL()); parser.parseAndValidate(input, schema); }
From source file:org.sonar.plugins.xml.checks.XmlSchemaCheck.java
/** * Create xsd schema for a list of schema's. *//* www .j a v a 2 s. com*/ private static Schema createSchema(String[] schemaList) { final String cacheKey = StringUtils.join(schemaList, ","); // first try to load a cached schema. Schema schema = cachedSchemas.get(cacheKey); if (schema != null) { return schema; } List<Source> schemaSources = new ArrayList<Source>(); // load each schema in a StreamSource. for (String schemaReference : schemaList) { InputStream input = SchemaResolver.getBuiltinSchema(schemaReference); if (input == null) { throw new SonarException("Could not load schema: " + schemaReference); } schemaSources.add(new StreamSource(input)); } // create a schema for the list of StreamSources. try { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setResourceResolver(new SchemaResolver()); schema = schemaFactory.newSchema(schemaSources.toArray(new Source[schemaSources.size()])); cachedSchemas.put(cacheKey, schema); return schema; } catch (SAXException e) { throw new SonarException(e); } }
From source file:org.springframework.oxm.jaxb.Jaxb2Marshaller.java
@SuppressWarnings("deprecation") // on JDK 9 private Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException { if (logger.isDebugEnabled()) { logger.debug("Setting validation schema to " + StringUtils.arrayToCommaDelimitedString(this.schemaResources)); }//from w w w. jav a 2 s. com Assert.notEmpty(resources, "No resources given"); Assert.hasLength(schemaLanguage, "No schema language provided"); Source[] schemaSources = new Source[resources.length]; XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); for (int i = 0; i < resources.length; i++) { Assert.notNull(resources[i], "Resource is null"); Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist"); InputSource inputSource = SaxResourceUtils.createInputSource(resources[i]); schemaSources[i] = new SAXSource(xmlReader, inputSource); } SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage); if (this.schemaResourceResolver != null) { schemaFactory.setResourceResolver(this.schemaResourceResolver); } return schemaFactory.newSchema(schemaSources); }
From source file:org.sweble.wikitext.dumpreader.DumpReader.java
private void setSchema(URL schemaUrl) throws Exception { SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); sf.setResourceResolver(new LSResourceResolverImplementation()); Schema schema = sf.newSchema(schemaUrl); unmarshaller.setSchema(schema);/*from w ww .j ava2s. c o m*/ unmarshaller.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(ValidationEvent ve) { try { return DumpReader.this.handleEvent(ve, ve.getLocator()); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new WrappedException(e); } } }); }
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); }/* www.ja v a2 s . com*/ } } return schema; }
From source file:org.tridas.io.formats.tridasjson.TridasJSONFile.java
public void validate() throws ImpossibleConversionException { Schema schema = null;//from w ww .ja v a 2 s. c o m // 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 *///www . ja va2 s . com 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. *///ww 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; }