Java Xsd Schema Validation Example
Java Code Examples for javax.xml.validation.Schema
The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.
Example 1
From project CCR-Validator, under directory /src/main/java/org/openhealthdata/validation/.
Source file: CCRV1SchemaValidator.java
27
/** * Constructor which excepts the File location of the XSD. If no File was used special URIResolver would be needed. * @param schemaLocation * @throws SAXException */ public CCRV1SchemaValidator(String schemaLocation) throws SAXException { SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source schemaFile=new StreamSource(new File(schemaLocation)); Schema schema=factory.newSchema(schemaFile); validator=schema.newValidator(); validator.setErrorHandler(eHandler); logger.log(Level.INFO,"Created " + this.getClass().getName() + " instance"); }
Example 2
From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/xml/.
Source file: XSDChecker.java
27
public static boolean validateFile(final String filePath) throws SAXException, IOException { SchemaFactory factory=SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); Schema schema=factory.newSchema(new StreamSource(XSDChecker.class.getResourceAsStream("dad.xsd"))); Validator validator=schema.newValidator(); Source source=new StreamSource(filePath); validator.validate(source); return true; }
Example 3
From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/dataholders/loadingutils/.
Source file: XmlDataLoader.java
26
/** * Creates and returns {@link Schema} object representing xml schema of xml files * @return a Schema object. */ private Schema getSchema(){ Schema schema=null; SchemaFactory sf=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { schema=sf.newSchema(new File(XML_SCHEMA_FILE)); } catch ( SAXException saxe) { log.fatal("Error while getting schema",saxe); throw new Error("Error while getting schema",saxe); } return schema; }
Example 4
From project Archimedes, under directory /br.org.archimedes.io.xml/src/br/org/archimedes/io/xml/.
Source file: XMLImporter.java
26
/** * @param inputStream The input stream from which the schema should be read * @return A validator for the XML files or null if none could be loaded */ private Validator buildValidator(InputStream inputStream){ Schema schema=obtainSchema(inputStream); if (schema == null) { return null; } return schema.newValidator(); }
Example 5
From project Carolina-Digital-Repository, under directory /persistence/src/main/java/edu/unc/lib/dl/update/.
Source file: MODSUIPFilter.java
26
public MODSUIPFilter(){ SchemaFactory sf=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); StreamSource modsSource=new StreamSource(getClass().getResourceAsStream("/schemas/mods-3-4.xsd")); Schema modsSchema; try { modsSchema=sf.newSchema(modsSource); } catch ( SAXException e) { throw new RuntimeException("Initialization of MODS UIP Filter ran into an unexpected exception",e); } modsValidator=modsSchema.newValidator(); }
Example 6
From project harmony, under directory /harmony.common.serviceinterface/src/main/java/org/opennaas/extensions/idb/serviceinterface/databinding/validator/.
Source file: SyntaxValidator.java
26
/** * Constructor. * @param schemeLocation schemeLocation-URL * @param failLevel level of Failure * @throws SAXException A SAXException */ private void init(final URL schemeLocation,final int failLevel) throws SAXException { final Schema schema=SyntaxValidator.FACTORY.newSchema(schemeLocation); this.validator=schema.newValidator(); final ValidatorErrorHandler errorHandler=new ValidatorErrorHandler(failLevel); this.validator.setErrorHandler(errorHandler); }
Example 7
From project hibernate-validator, under directory /engine/src/main/java/org/hibernate/validator/internal/xml/.
Source file: XmlParserHelper.java
26
public Schema getSchema(String schemaResource){ Schema schema=schemaCache.get(schemaResource); if (schema != null) { return schema; } schema=loadSchema(schemaResource); Schema previous=schemaCache.putIfAbsent(schemaResource,schema); return previous != null ? previous : schema; }
Example 8
@Test public void testValidBundleUnamrashalling() throws Exception { Unmarshaller unmarshaller=JAXBContext.newInstance(org.apache.ivory.oozie.bundle.BUNDLEAPP.class).createUnmarshaller(); SchemaFactory schemaFactory=SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); Schema schema=schemaFactory.newSchema(this.getClass().getResource("/oozie-bundle-0.1.xsd")); unmarshaller.setSchema(schema); Object bundle=unmarshaller.unmarshal(new StreamSource(BundleUnmarshallingTest.class.getResourceAsStream("/oozie/xmls/bundle.xml")),BUNDLEAPP.class); BUNDLEAPP bundleApp=((JAXBElement<BUNDLEAPP>)bundle).getValue(); Assert.assertEquals(bundleApp.getName(),"bundle-app"); Assert.assertEquals(bundleApp.getCoordinator().get(0).getName(),"coord-1"); }
Example 9
From project jboss-modules, under directory /src/test/java/org/jboss/modules/.
Source file: JAXPModuleTest.java
26
public void checkSchema(Class<?> clazz,boolean fake) throws Exception { Schema parser=invokeMethod(clazz.newInstance(),"schema"); SchemaFactory factory=invokeMethod(clazz.newInstance(),"schemaFactory"); Assert.assertEquals(__SchemaFactory.class.getName(),factory.getClass().getName()); if (fake) { Assert.assertEquals(FakeSchema.class.getName(),parser.getClass().getName()); } else { Assert.assertSame(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema().getClass(),parser.getClass()); } }
Example 10
From project JMaNGOS, under directory /Commons/src/main/java/org/jmangos/commons/dataholder/.
Source file: XmlDataLoader.java
26
/** * Gets the schema. * @param Schema the schema * @return the schema */ private static Schema getSchema(final String Schema){ final SchemaFactory sf=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema=null; try { schema=sf.newSchema(new File(Schema)); } catch ( final SAXException e) { System.err.println("Error getting schema"); e.printStackTrace(); } return schema; }
Example 11
From project karaf, under directory /features/core/src/main/java/org/apache/karaf/features/internal/.
Source file: FeatureValidationUtil.java
26
private static void validate(Document doc,String schemaLocation) throws SAXException { SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema=factory.newSchema(new StreamSource(FeatureValidationUtil.class.getResourceAsStream(schemaLocation))); Validator validator=schema.newValidator(); try { validator.validate(new DOMSource(doc)); } catch ( Exception e) { throw new IllegalArgumentException("Unable to validate " + doc.getDocumentURI(),e); } }
Example 12
From project Lily, under directory /cr/indexer/engine/src/test/resources/org/lilyproject/indexer/engine/test/.
Source file: SchemaTest.java
26
@Test public void test() throws Exception { SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL url=getClass().getClassLoader().getResource("org/lilyproject/indexer/conf/indexerconf.xsd"); Schema schema=factory.newSchema(url); Validator validator=schema.newValidator(); InputStream is=getClass().getClassLoader().getResourceAsStream("org/lilyproject/indexer/test/indexerconf1.xml"); validator.validate(new StreamSource(is)); }
Example 13
From project Ohmage_Server_2, under directory /src/org/ohmage/config/xml/.
Source file: CampaignValidator.java
26
/** * Validates a campaign's schema. * @param xml The campaign that will have its schema validated. * @param schema The schema used to validate the campaign XML. * @throws IOException Thrown if the schema file cannot be found or read. * @throws SAXException Thrown if the schema validation fails. */ private void checkSchemaOnStrings(String xml,String schemaFileName) throws IOException, SAXException { SAXSource xmlSource=new SAXSource(new InputSource(new StringReader(xml))); StreamSource schemaDocument=new StreamSource(new File(schemaFileName)); SchemaFactory sf=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema s=sf.newSchema(schemaDocument); Validator v=s.newValidator(); v.validate(xmlSource); }
Example 14
From project repose, under directory /project-set/components/versioning/src/test/java/com/rackspace/papi/components/versioning/testhelpers/.
Source file: XmlTestHelper.java
26
public static Schema getVersioningSchemaInfo(){ Schema schema=null; try { schema=SCHEMA_FACTORY.newSchema(new StreamSource[]{new StreamSource(VersioningFilter.class.getResourceAsStream("/META-INF/schema/xml/xml.xsd")),new StreamSource(VersioningFilter.class.getResourceAsStream("/META-INF/schema/atom/atom.xsd")),new StreamSource(VersioningFilter.class.getResourceAsStream("/META-INF/schema/versioning/versioning.xsd"))}); } catch ( SAXException e) { LOG.error("Failed to create schema object!",e); } return schema; }
Example 15
From project seage, under directory /seage-misc/src/main/java/org/seage/data/xml/.
Source file: XmlHelper.java
26
public static DataNode readXml(InputStream is,InputStream schema) throws Exception { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); if (schema != null) factory.setNamespaceAware(true); else factory.setNamespaceAware(false); DocumentBuilder builder=factory.newDocumentBuilder(); Document doc=builder.parse(is); if (schema != null) { SchemaFactory factory2=SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); Schema schemaObj=factory2.newSchema(new StreamSource(schema)); Validator validator=schemaObj.newValidator(); validator.validate(new DOMSource(doc)); } return readElement(doc.getDocumentElement()); }
Example 16
From project SIARD-Val, under directory /SIARD-Val/src/main/java/ch/kostceco/tools/siardval/validation/module/impl/.
Source file: ValidationHcontentModuleImpl.java
26
private boolean validate(File xmlFile,File schemaLocation) throws SAXException, IOException { SchemaFactory factory=SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); ValidationErrorHandler errorHandler=new ValidationErrorHandler(xmlFile,schemaLocation); Schema schema=factory.newSchema(schemaLocation); Validator validator=schema.newValidator(); validator.setErrorHandler(errorHandler); Source source=new StreamSource(xmlFile); validator.validate(source); return errorHandler.isValid(); }
Example 17
From project skalli, under directory /org.eclipse.skalli.testutil/src/main/java/org/eclipse/skalli/testutil/.
Source file: SchemaValidationUtils.java
26
private static DocumentBuilderFactory getDocumentBuilderFactory(String xsdFile) throws Exception { URL schemaFile=RestUtils.findSchemaResource(xsdFile); String mergedSchema=SchemaValidationUtils.resolveIncludes(schemaFile); SchemaFactory xsFact=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema=xsFact.newSchema(new StreamSource(new StringReader(mergedSchema))); DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(false); dbf.setSchema(schema); return dbf; }
Example 18
From project activemq-apollo, under directory /apollo-dto/src/main/java/org/apache/activemq/apollo/dto/.
Source file: XmlCodec.java
25
static public <T>T decode(Class<T> clazz,InputStream is,Properties props,ValidationEventHandler validationHandler) throws IOException, XMLStreamException, JAXBException, SAXException { ClassLoader original=Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(ClassFinder.class_loader()); if (is == null) { throw new IllegalArgumentException("input stream was null"); } try { XMLStreamReader reader=factory.createXMLStreamReader(is); if (props != null) { reader=new PropertiesFilter(reader,props); } Unmarshaller unmarshaller=context().createUnmarshaller(); if (validationHandler != null) { try { SchemaFactory sf=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); sf.setFeature("http://apache.org/xml/features/validation/schema-full-checking",false); Schema schema=sf.newSchema(XmlCodec.class.getResource("apollo.xsd")); unmarshaller.setSchema(schema); unmarshaller.setEventHandler(validationHandler); } catch ( Exception e) { System.err.println("Could not load schema: " + e.getMessage()); } } return clazz.cast(unmarshaller.unmarshal(reader)); } finally { is.close(); } } finally { Thread.currentThread().setContextClassLoader(original); } }
Example 19
From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/coreutils/.
Source file: XMLUtil.java
25
/** * Utility to validate XML files against pre-defined schema files. The schema files are extracted automatically when this function is called, the XML being validated is not. Be sure the XML file is already extracted otherwise it will return false. * @param xmlfile The XML file to validate, in DOMSource format * @param type The file name of the schema to validate against, must exist as a resource in the same package as where this function is being called.For example usages, please see KeywordSearchListsXML, HashDbXML, or IngestModuleLoader. */ public static boolean xmlIsValid(DOMSource xmlfile,Class clazz,String schemaFile){ try { PlatformUtil.extractResourceToUserConfigDir(clazz,schemaFile); File schemaLoc=new File(PlatformUtil.getUserConfigDirectory() + File.separator + schemaFile); SchemaFactory schm=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { Schema schema=schm.newSchema(schemaLoc); Validator validator=schema.newValidator(); DOMResult result=new DOMResult(); validator.validate(xmlfile,result); return true; } catch ( SAXException e) { Logger.getLogger(clazz.getName()).log(Level.WARNING,"Unable to validate XML file.",e); return false; } } catch ( IOException e) { Logger.getLogger(clazz.getName()).log(Level.WARNING,"Unable to load XML file [" + xmlfile.toString() + "] of type ["+ schemaFile+ "]",e); return false; } }
Example 20
From project core_1, under directory /config/src/main/java/org/switchyard/config/model/.
Source file: Descriptor.java
25
/** * Creates a Schema based on the combined schema documents/definitions found that are associated with the specified namespaces. * @param namespaces the namespaces of the schemas * @return the new Schema */ public synchronized Schema getSchema(Set<String> namespaces){ Schema schema=_namespaces_schema_map.get(namespaces); if (schema == null) { Map<String,Source> nsSourceMap=new TreeMap<String,Source>(new NamespaceComparator()); try { for ( String namespace : namespaces) { String schemaLocation=getSchemaLocation(namespace); if (schemaLocation != null) { URL url=Classes.getResource(schemaLocation,Descriptor.class); if (url != null) { String xsd=new StringPuller().pull(url); nsSourceMap.put(namespace,new StreamSource(new StringReader(xsd))); } } } if (nsSourceMap.size() > 0) { SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver(new DescriptorLSResourceResolver(this)); Collection<Source> sortedSources=nsSourceMap.values(); Source[] schemaSources=sortedSources.toArray(new Source[sortedSources.size()]); schema=factory.newSchema(schemaSources); _namespaces_schema_map.put(namespaces,schema); } } catch ( Exception e) { throw new RuntimeException(e); } } return schema; }
Example 21
From project drools-chance, under directory /drools-shapes/drools-shapes-examples/conyard-example/src/test/java/.
Source file: FactTest.java
25
@Test @Ignore public void validateXMLWithSchema() throws SAXException { StringWriter writer=new StringWriter(); try { marshaller.marshal(painting,writer); } catch ( JAXBException e) { fail(e.getMessage()); } String inXSD="conyard_$impl.xsd"; String xml=writer.toString(); System.out.println(xml); SchemaFactory factory=SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); Source schemaFile=null; try { schemaFile=new StreamSource(new ClassPathResource(inXSD).getInputStream()); } catch ( IOException e) { fail(e.getMessage()); } Schema schema=factory.newSchema(schemaFile); Validator validator=schema.newValidator(); Source source=new StreamSource(new ByteArrayInputStream(xml.getBytes())); try { validator.validate(source); } catch ( SAXException ex) { fail(ex.getMessage()); } catch ( IOException ex) { fail(ex.getMessage()); } }
Example 22
protected void validate(String xmlText,String definitionPath) throws ApsSystemException { SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); InputStream schemaIs=null; InputStream xmlIs=null; try { schemaIs=this.getClass().getResourceAsStream(this.getSchemaFileName()); Source schemaSource=new StreamSource(schemaIs); Schema schema=factory.newSchema(schemaSource); Validator validator=schema.newValidator(); xmlIs=new ByteArrayInputStream(xmlText.getBytes("UTF-8")); Source source=new StreamSource(xmlIs); validator.validate(source); ApsSystemUtils.getLogger().info("Valid definition : " + definitionPath); } catch ( Throwable t) { String message="Error validating definition : " + definitionPath; ApsSystemUtils.logThrowable(t,this,"this",message); throw new ApsSystemException(message,t); } finally { try { if (null != schemaIs) schemaIs.close(); if (null != xmlIs) xmlIs.close(); } catch ( IOException e) { ApsSystemUtils.logThrowable(e,this,"this"); } } }
Example 23
From project fedora-client, under directory /fedora-client-core/src/main/java/com/yourmediashelf/fedora/client/response/.
Source file: FedoraResponseImpl.java
25
/** * Unmarshall the Fedora ClientResponse using the JAXB schema-generated classes (see: target/generated-sources/). * @param contextPath JAXB contextPath * @return the unmarshalled XML * @throws FedoraClientException */ public Object unmarshallResponse(ContextPath contextPath) throws FedoraClientException { Object response=null; Schema schema=null; if (validateSchema()) { try { SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schema=schemaFactory.newSchema(); } catch ( SAXException e) { throw new FedoraClientException(e.getMessage(),e); } } try { JAXBContext context=JAXBContext.newInstance(contextPath.path()); Unmarshaller unmarshaller=context.createUnmarshaller(); unmarshaller.setSchema(schema); response=unmarshaller.unmarshal(new BufferedReader(new InputStreamReader(getEntityInputStream()))); } catch ( JAXBException e) { throw new FedoraClientException(e.getMessage(),e); } return response; }
Example 24
/** * {@inheritDoc} * @see net.sf.hajdbc.DatabaseClusterConfigurationFactory#createConfiguration() */ @Override public DatabaseClusterConfiguration<Z,D> createConfiguration() throws SQLException { logger.log(Level.INFO,Messages.HA_JDBC_INIT.getMessage(),Version.getVersion(),this.streamFactory); try { SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema=schemaFactory.newSchema(SCHEMA); Unmarshaller unmarshaller=JAXBContext.newInstance(this.targetClass).createUnmarshaller(); unmarshaller.setSchema(schema); XMLReader reader=new PropertyReplacementFilter(XMLReaderFactory.createXMLReader()); InputSource source=SAXSource.sourceToInputSource(this.streamFactory.createSource()); return this.targetClass.cast(unmarshaller.unmarshal(new SAXSource(reader,source))); } catch ( JAXBException e) { throw new SQLException(e); } catch ( SAXException e) { throw new SQLException(e); } }
Example 25
From project hibernate-metamodelgen, under directory /src/main/java/org/hibernate/jpamodelgen/xml/.
Source file: XmlParser.java
25
private Schema getSchema(String schemaName){ Schema schema=null; URL schemaUrl=this.getClass().getClassLoader().getResource(schemaName); if (schemaUrl == null) { return schema; } SchemaFactory sf=SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); try { schema=sf.newSchema(schemaUrl); } catch ( SAXException e) { context.logMessage(Diagnostic.Kind.WARNING,"Unable to create schema for " + schemaName + ": "+ e.getMessage()); } return schema; }
Example 26
From project interoperability-framework, under directory /toolwrapper/src/main/java/eu/impact_project/iif/tw/gen/.
Source file: ToolspecValidator.java
25
/** * @throws GeneratorException */ public void validateWithXMLSchema() throws GeneratorException { try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder=factory.newDocumentBuilder(); Document doc=builder.parse(new File(ioc.getXmlConf())); SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source schemaFile=new StreamSource(new File("src/main/resources/toolspec.xsd")); Schema schema=schemaFactory.newSchema(schemaFile); Validator validator=schema.newValidator(); validator.validate(new DOMSource(doc)); logger.info("XML tool specification file successfully validated."); } catch ( SAXException ex) { org.xml.sax.SAXParseException saxex=null; if (ex instanceof org.xml.sax.SAXParseException) { saxex=(org.xml.sax.SAXParseException)ex; logger.error("SAX parse error: " + saxex.getLocalizedMessage()); } else { logger.error("SAXException:",ex); } throw new GeneratorException("SAXException occurred while validating instance."); } catch ( IOException ex) { throw new GeneratorException("IOException occurred while validating instance."); } catch ( ParserConfigurationException ex) { throw new GeneratorException("ParserConfigurationException occurred while validating instance."); } }
Example 27
protected void validate(String xmlText,String definitionPath) throws ApsSystemException { SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); InputStream schemaIs=null; InputStream xmlIs=null; try { schemaIs=this.getClass().getResourceAsStream(this.getSchemaFileName()); Source schemaSource=new StreamSource(schemaIs); Schema schema=factory.newSchema(schemaSource); Validator validator=schema.newValidator(); xmlIs=new ByteArrayInputStream(xmlText.getBytes("UTF-8")); Source source=new StreamSource(xmlIs); validator.validate(source); ApsSystemUtils.getLogger().info("Valid definition : " + definitionPath); } catch ( Throwable t) { String message="Error validating definition : " + definitionPath; ApsSystemUtils.logThrowable(t,this,"this",message); throw new ApsSystemException(message,t); } finally { try { if (null != schemaIs) schemaIs.close(); if (null != xmlIs) xmlIs.close(); } catch ( IOException e) { ApsSystemUtils.logThrowable(e,this,"this"); } } }
Example 28
From project jCAE, under directory /amibe/src/org/jcae/mesh/xmldata/.
Source file: XMLWriter.java
25
public XMLWriter(String f,URL xsdPath) throws IOException { XMLStreamWriter o=null; try { document=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); DOMResult result=new DOMResult(document); o=XMLOutputFactory.newInstance().createXMLStreamWriter(result); o.writeStartDocument(); Schema xsd=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(xsdPath); this.validator=xsd.newValidator(); } catch ( SAXException ex) { LOGGER.log(Level.SEVERE,ex.getMessage(),ex); } catch ( ParserConfigurationException ex) { LOGGER.log(Level.SEVERE,ex.getMessage(),ex); } catch ( XMLStreamException ex) { LOGGER.log(Level.SEVERE,ex.getMessage(),ex); } out=o; filename=f; }
Example 29
From project jobcreator-tool, under directory /src/main/java/dk/hlyh/hudson/tools/jobcreator/input/xml/.
Source file: XmlLoader.java
25
dk.hlyh.hudson.tools.jobcreator.input.xml.model.Pipeline loadXml(){ File inputFile=arguments.getInput(); if (inputFile == null || !inputFile.exists()) { throw new ImportException("Pipline file '" + inputFile + "' cannot be found"); } try { JAXBContext context=JAXBContext.newInstance(ROOT_NODE); Unmarshaller unmarshaller=context.createUnmarshaller(); Schema schema=loadSchema(); unmarshaller.setSchema(schema); dk.hlyh.hudson.tools.jobcreator.input.xml.model.Pipeline pipeline=(dk.hlyh.hudson.tools.jobcreator.input.xml.model.Pipeline)unmarshaller.unmarshal(new FileInputStream(inputFile)); LogFacade.info("Successfully loaded pipline from {0}",inputFile); return pipeline; } catch ( FileNotFoundException ex) { throw new ImportException("Could not find pipeline file: " + inputFile); } catch ( UnmarshalException ex) { if (ex.getCause() instanceof org.xml.sax.SAXParseException) { SAXParseException pe=(SAXParseException)ex.getCause(); LogFacade.severe("Failed to validate the pipeline definition against the schema: \"{0}\" at line {1}, column={2}",pe.getMessage(),pe.getLineNumber(),pe.getColumnNumber()); } else { LogFacade.severe(ex); } throw new ImportException("Failed to validate the pipeline definition against the schema" + ex); } catch ( JAXBException ex) { throw new ImportException("Failed to configure JAXB",ex); } }
Example 30
From project jSCSI, under directory /bundles/initiator/src/main/java/org/jscsi/initiator/.
Source file: Configuration.java
25
/** * Reads the given configuration file in memory and creates a DOM representation. * @throws SAXException If this operation is supported but failed for some reason. * @throws ParserConfigurationException If a <code>DocumentBuilder</code> cannot be created which satisfies the configuration requested. * @throws IOException If any IO errors occur. */ private final Document parse(final File schemaLocation,final File configFile) throws ConfigurationException { try { final SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema=schemaFactory.newSchema(schemaLocation); final Validator validator=schema.newValidator(); final DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); final DocumentBuilder builder=domFactory.newDocumentBuilder(); final Document doc=builder.parse(configFile); final DOMSource source=new DOMSource(doc); final DOMResult result=new DOMResult(); validator.validate(source,result); return (Document)result.getNode(); } catch ( final SAXException exc) { throw new ConfigurationException(exc); } catch ( final ParserConfigurationException exc) { throw new ConfigurationException(exc); } catch ( final IOException exc) { throw new ConfigurationException(exc); } }
Example 31
From project litle-sdk-for-java, under directory /lib/jaxb/samples/unmarshal-validate/src/.
Source file: Main.java
25
public static void main(String[] args){ try { JAXBContext jc=JAXBContext.newInstance("primer.po"); Unmarshaller u=jc.createUnmarshaller(); SchemaFactory sf=SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { Schema schema=sf.newSchema(new File("po.xsd")); u.setSchema(schema); u.setEventHandler(new ValidationEventHandler(){ public boolean handleEvent( ValidationEvent ve){ if (ve.getSeverity() != ValidationEvent.WARNING) { ValidationEventLocator vel=ve.getLocator(); System.out.println("Line:Col[" + vel.getLineNumber() + ":"+ vel.getColumnNumber()+ "]:"+ ve.getMessage()); } return true; } } ); } catch ( org.xml.sax.SAXException se) { System.out.println("Unable to validate due to following error."); se.printStackTrace(); } System.out.println("NOTE: This sample is working correctly if you see validation errors!!"); Object poe=u.unmarshal(new File("po.xml")); System.out.println(""); System.out.println("Still able to marshal invalid document"); Marshaller m=jc.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE); m.marshal(poe,System.out); } catch ( UnmarshalException ue) { System.out.println("Caught UnmarshalException"); } catch ( JAXBException je) { je.printStackTrace(); } }
Example 32
From project mobilis, under directory /MobilisServer/src/de/tudresden/inf/rn/mobilis/server/deployment/helper/.
Source file: MSDLValidator.java
25
/** * Validate a msdl against the schema. * @param inMsdlStream the msdl as input stream * @param inMsdlSchemaStream the schema as input stream * @return true, if msdl is valid */ public boolean validateSchema(InputStream inMsdlStream,InputStream inMsdlSchemaStream){ boolean isValid=false; try { SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema=schemaFactory.newSchema(new StreamSource(inMsdlSchemaStream)); Validator validator=schema.newValidator(); validator.validate(new StreamSource(inMsdlStream)); isValid=true; } catch ( SAXException ex) { _lastValidationErrorMessage=ex.getMessage(); } catch ( Exception ex) { ex.printStackTrace(); } return isValid; }
Example 33
From project modello, under directory /modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/.
Source file: FeaturesXsdGeneratorTest.java
25
public void testXsdGenerator() throws Throwable { ModelloCore modello=(ModelloCore)lookup(ModelloCore.ROLE); Model model=modello.loadModel(getXmlResourceReader("/features.mdo")); Properties parameters=getModelloParameters("1.0.0"); modello.generate(model,"xsd",parameters); SchemaFactory sf=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema=sf.newSchema(new StreamSource(new File(getOutputDirectory(),"features-1.0.0.xsd"))); Validator validator=schema.newValidator(); try { validator.validate(new StreamSource(getClass().getResourceAsStream("/features.xml"))); } catch ( SAXParseException e) { throw new ModelloException("line " + e.getLineNumber() + " column "+ e.getColumnNumber(),e); } try { validator.validate(new StreamSource(getClass().getResourceAsStream("/features-invalid.xml"))); fail("parsing of features-invalid.xml should have failed"); } catch ( SAXParseException e) { assertTrue(String.valueOf(e.getMessage()).indexOf("invalidElement") >= 0); } try { validator.validate(new StreamSource(getClass().getResourceAsStream("/features-invalid-transient.xml"))); fail("XSD did not prohibit appearance of transient fields"); } catch ( SAXParseException e) { assertTrue(String.valueOf(e.getMessage()).indexOf("transientString") >= 0); } }
Example 34
From project ODE-X, under directory /spi/src/main/java/org/apache/ode/spi/repo/.
Source file: XMLValidate.java
25
@Override public boolean validate(StringBuilder messages){ try { SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); ArrayList<Source> sourceSchemas=new ArrayList<Source>(); Set<SchemaSource> srcs=schemaSources.get(dh.getContentType()); if (srcs != null) { for ( SchemaSource src : srcs) { for ( Source s : src.getSchemaSource()) { sourceSchemas.add(s); } } } Source[] sources=sourceSchemas.toArray(new Source[0]); Schema schema=factory.newSchema(sources); Validator validator=schema.newValidator(); ValidationErrorHandler er=new ValidationErrorHandler(messages); validator.setErrorHandler(er); validator.setResourceResolver(new LSResourceResolverImpl()); validator.validate(new StreamSource(dh.getInputStream())); return !er.hasError(); } catch ( Exception e) { messages.append(e); return false; } }
Example 35
From project org.openscada.external, under directory /org.openscada.external.jOpenDocument/src/org/jopendocument/util/.
Source file: JDOMUtils.java
25
/** * Validate a document using JAXP. * @param doc the document to validate * @param schemaLanguage the language see {@linkplain SchemaFactory the list}. * @param schemaLocation the schema. * @return <code>null</code> if <code>doc</code> is valid, a String describing the pb otherwise. * @throws SAXException If a SAX error occurs during parsing of schemas. * @see SchemaFactory */ public static String isValid(final Document doc,final String schemaLanguage,final URL schemaLocation) throws SAXException { ByteArrayInputStream ins; try { ins=new ByteArrayInputStream(output(doc).getBytes("UTF8")); } catch ( UnsupportedEncodingException e) { throw new IllegalStateException("unicode not found ",e); } final Schema schema=SchemaFactory.newInstance(schemaLanguage).newSchema(schemaLocation); try { schema.newValidator().validate(new StreamSource(ins)); return null; } catch ( Exception e) { return ExceptionUtils.getStackTrace(e); } }
Example 36
public OServerConfiguration load() throws IOException { try { if (file.exists()) { context=JAXBContext.newInstance(rootClass); Unmarshaller unmarshaller=context.createUnmarshaller(); Schema schema=null; unmarshaller.setSchema(schema); OServerConfiguration obj=rootClass.cast(unmarshaller.unmarshal(file)); obj.location=filePath; OGlobalConfiguration config; for ( OEntryConfiguration prop : obj.properties) { try { config=OGlobalConfiguration.findByKey(prop.name); if (config != null) { config.setValue(prop.value); } } catch ( Exception e) { } } return obj; } else return rootClass.getConstructor(OServerConfigurationLoaderXml.class,String.class).newInstance(this,filePath); } catch ( Exception e) { OLogManager.instance().error(this,"Invalid syntax. Below an example of how it should be:",e); try { context=JAXBContext.newInstance(rootClass); Marshaller marshaller=context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE); Object example=rootClass.getConstructor(OServerConfigurationLoaderXml.class).newInstance(this); marshaller.marshal(example,System.out); } catch ( Exception ex) { throw new IOException(ex); } throw new IOException(e); } }
Example 37
From project processFlowProvision, under directory /osProvision/src/main/java/org/jboss/processFlow/openshift/.
Source file: ShifterProvisioner.java
25
private static void validateAccountDetailsXmlFile() throws Exception { SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); InputStream xsdStream=null; InputStream xmlStream=null; try { xsdStream=ShifterProvisioner.class.getResourceAsStream(OPENSHIFT_ACCOUNT_DETAILS_SCHEMA_FILE); if (xsdStream == null) throw new RuntimeException("validateAccountDetails() can't find schema: " + OPENSHIFT_ACCOUNT_DETAILS_SCHEMA_FILE); Schema schemaObj=schemaFactory.newSchema(new StreamSource(xsdStream)); File xmlFile=new File(openshiftAccountDetailsFile); if (!xmlFile.exists()) throw new RuntimeException("validateAccountDetails() can't find xml file: " + openshiftAccountDetailsFile); xmlStream=new FileInputStream(xmlFile); Validator v=schemaObj.newValidator(); v.validate(new StreamSource(xmlStream)); } finally { if (xsdStream != null) xsdStream.close(); if (xmlStream != null) xmlStream.close(); } }
Example 38
From project scape, under directory /xa-toolwrapper/src/main/java/eu/scape_project/xa/tw/gen/.
Source file: ToolspecValidator.java
25
/** * @throws GeneratorException */ public void validateWithXMLSchema() throws GeneratorException { try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder=factory.newDocumentBuilder(); Document doc=builder.parse(new File(ioc.getXmlConf())); SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source schemaFile=new StreamSource(ClassLoader.getSystemResourceAsStream(Constants.TOOLSPEC_SCHEMA_RESOURCE_PATH)); Schema schema=schemaFactory.newSchema(schemaFile); Validator validator=schema.newValidator(); validator.validate(new DOMSource(doc)); logger.info("XML tool specification file successfully validated."); } catch ( SAXException ex) { org.xml.sax.SAXParseException saxex=null; if (ex instanceof org.xml.sax.SAXParseException) { saxex=(org.xml.sax.SAXParseException)ex; logger.error("SAX parse error: " + saxex.getLocalizedMessage()); } else { logger.error("SAXException:",ex); } throw new GeneratorException("SAXException occurred while validating instance."); } catch ( IOException ex) { throw new GeneratorException("IOException occurred while validating instance."); } catch ( ParserConfigurationException ex) { throw new GeneratorException("ParserConfigurationException occurred while validating instance."); } }
Example 39
From project scufl2, under directory /scufl2-rdfxml/src/main/java/uk/org/taverna/scufl2/rdfxml/.
Source file: RDFXMLSerializer.java
25
public Marshaller getMarshaller(){ String schemaPath="xsd/scufl2.xsd"; Marshaller marshaller; try { marshaller=getJaxbContext().createMarshaller(); if (isUsingSchema()) { SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema=schemaFactory.newSchema(getClass().getResource(schemaPath)); marshaller.setSchema(schema); } marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE); marshaller.setProperty("jaxb.schemaLocation","http://ns.taverna.org.uk/2010/scufl2# http://ns.taverna.org.uk/2010/scufl2/scufl2.xsd " + "http://www.w3.org/1999/02/22-rdf-syntax-ns# http://ns.taverna.org.uk/2010/scufl2/rdf.xsd"); } catch ( JAXBException e) { throw new IllegalStateException(e); } catch ( SAXException e) { throw new IllegalStateException("Could not load schema " + schemaPath,e); } setPrefixMapper(marshaller); return marshaller; }
Example 40
From project smart-cms, under directory /spi-modules/content-spi-type-validators-impl/src/main/java/com/smartitengineering/cms/spi/impl/type/validator/.
Source file: XMLSchemaBasedTypeValidator.java
25
protected boolean isValid(Document document) throws Exception { SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final InputStream xsdStream=getClass().getClassLoader().getResourceAsStream(XSD_LOCATION); Source schemaFile=new StreamSource(xsdStream); schemaFile.setSystemId(CONTENT_TYPE_SCHEMA_URI); Schema schema=factory.newSchema(schemaFile); Validator validator=schema.newValidator(); try { validator.validate(new DOMSource(document)); return true; } catch ( SAXException e) { e.printStackTrace(); return false; } }
Example 41
From project turmeric-monitoring, under directory /SOAMetricsQueryServiceImpl/src/main/java/org/ebayopensource/turmeric/monitoring/util/.
Source file: XMLParseUtil.java
25
private static void validate(String schemaName,String filename,Node document,SchemaValidationLevel checkLevel) throws Exception { if (checkLevel.equals(SchemaValidationLevel.NONE)) { return; } ClassLoader classLoader=ContextUtil.getClassLoader(); URL url=classLoader.getResource(schemaName); if (url == null) { throw new Exception("cannot load file: " + schemaName); } SchemaFactory factory=SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { Schema schema=factory.newSchema(url); Validator validator=schema.newValidator(); ErrorHandler errorHandler=new ParseErrorHandler(filename,checkLevel); validator.setErrorHandler(errorHandler); validator.validate(new DOMSource(document)); } catch ( SAXException se) { throw new Exception("parse error on filename: " + filename + ", "+ se.toString()); } catch ( IOException ioe) { throw new Exception("parse error on schema: " + filename + ", "+ ioe.toString()); } }
Example 42
From project turmeric-releng, under directory /utils/TurmericUtils/src/org/ebayopensource/turmeric/utils/.
Source file: XMLParseUtils.java
25
private static void validate(String schemaName,String filename,Node document,SchemaValidationLevel checkLevel) throws Exception { if (checkLevel.equals(SchemaValidationLevel.NONE)) { return; } ClassLoader classLoader=ContextUtils.getClassLoader(); URL url=classLoader.getResource(schemaName); if (url == null) { throw new Exception("cannot load file: " + schemaName); } SchemaFactory factory=SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { Schema schema=factory.newSchema(url); Validator validator=schema.newValidator(); ErrorHandler errorHandler=new ParseErrorHandler(filename,checkLevel); validator.setErrorHandler(errorHandler); validator.validate(new DOMSource(document)); } catch ( SAXException se) { throw new Exception("parse error on filename: " + filename + ", "+ se.toString()); } catch ( IOException ioe) { throw new Exception("parse error on schema: " + filename + ", "+ ioe.toString()); } }
Example 43
From project xcode-maven-plugin, under directory /modules/xcode-maven-plugin/src/main/java/com/sap/prd/mobile/ios/mios/.
Source file: DomUtils.java
25
static void validateDocument(Document doc) throws SAXException, IOException { SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); InputStream schemaIs=null; try { schemaIs=XCodeVersionInfoMojo.class.getResourceAsStream("/com/sap/tip/production/xcode/VersionInfoSchema.xsd"); StreamSource[] inputSources=new StreamSource[1]; inputSources[0]=new StreamSource(schemaIs); Schema schema=schemaFactory.newSchema(inputSources); Validator validator=schema.newValidator(); validator.validate(new DOMSource(doc)); } finally { if (schemaIs != null) { schemaIs.close(); } } }
Example 44
From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/.
Source file: Parser.java
23
public void validate(Schema schema){ try { Validator validator=schema.newValidator(); for ( Document doc : this.documents) { validator.validate(new DOMSource(doc)); } } catch ( Exception e) { throw new ComponentDefinitionException("Unable to validate xml",e); } }
Example 45
From project Opal, under directory /opal-struct/src/main/java/com/lyndir/lhunath/opal/xml/.
Source file: Structure.java
23
/** * @param coalescing <code>true</code> to convert CDATA to text nodes. * @param expandEntityRef <code>true</code> to expand entity reference nodes. * @param ignoreComments <code>true</code> to ignore comment nodes. * @param whitespace <code>true</code> to remove 'ignorable whitespace'. * @param awareness <code>true</code> to be namespace-aware. * @param xIncludes <code>true</code> to be XInclude-aware. * @param validating <code>true</code> to validate the XML data against a schema. * @param schema The schema to validate against. Specify <code>null</code> if not validating. * @return a builder that parses XML data according to the rules specified by the arguments. */ public static DocumentBuilder getXMLBuilder(final boolean coalescing,final boolean expandEntityRef,final boolean ignoreComments,final boolean whitespace,final boolean awareness,final boolean xIncludes,final boolean validating,final Schema schema){ try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setCoalescing(coalescing); factory.setExpandEntityReferences(expandEntityRef); factory.setIgnoringComments(ignoreComments); factory.setIgnoringElementContentWhitespace(whitespace); factory.setNamespaceAware(awareness); factory.setXIncludeAware(xIncludes); factory.setValidating(validating); factory.setSchema(schema); return factory.newDocumentBuilder(); } catch ( ParserConfigurationException e) { logger.err(e,"Document Builder has not been configured correctly!"); } return null; }
Example 46
From project seamless, under directory /xml/src/main/java/org/seamless/xml/.
Source file: DOMParser.java
23
public Schema getSchema(){ if (schema == null) { try { SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setResourceResolver(new CatalogResourceResolver(new HashMap<URI,URL>(){ { put(DOM.XML_SCHEMA_NAMESPACE,XML_SCHEMA_RESOURCE); } } )); if (schemaSources != null) { schema=schemaFactory.newSchema(schemaSources); } else { schema=schemaFactory.newSchema(); } } catch ( Exception ex) { throw new RuntimeException(ex); } } return schema; }
Example 47
From project sleeparchiver, under directory /src/com/pavelfatin/sleeparchiver/model/.
Source file: Document.java
23
private static Schema getSchema(){ if (_schema == null) { _schema=loadSchema("document.xsd"); } return _schema; }
Source: http://www.javased.com/?api=javax.xml.validation.Schema
0 Response to "Java Xsd Schema Validation Example"
إرسال تعليق