List of usage examples for javax.xml.validation SchemaFactory newInstance
public static SchemaFactory newInstance(String schemaLanguage)
From source file:org.perfclipse.core.scenario.ScenarioManager.java
/** * Creates {@link ScenarioModel} object representation of the scenario * specified in XML file at scenarioURL parameter. * @param scenarioURL - URL to scenario XML definition * @return {@link ScenarioModel} of given XML definition * @throws ScenarioException/* w w w . j ava 2 s.co m*/ */ public ScenarioModel createModel(URL scenarioURL) throws ScenarioException { org.perfcake.model.Scenario model; if (scenarioURL == null) { log.error("URL to scenario is null"); throw new IllegalArgumentException("URL to scenario is null."); } try { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL schemaUrl = SchemaScanner.getSchema(); Schema schema = schemaFactory.newSchema(schemaUrl); JAXBContext context = JAXBContext.newInstance(org.perfcake.model.Scenario.class); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setSchema(schema); model = (org.perfcake.model.Scenario) unmarshaller.unmarshal(scenarioURL); return new ScenarioModel(model); } catch (JAXBException e) { throw new ScenarioException(e); } catch (IOException e) { throw new ScenarioException(e); } catch (SAXException e) { throw new ScenarioException(e); } }
From source file:org.perfclipse.core.scenario.ScenarioManager.java
/** * The createXML method converts scenario model into XML representation * according to PerfCake XML Schema and writes output to output stream out * @param model model to be converted// w w w .j a va2 s. c om * @param out OutputStream to which xml will be written * @throws ScenarioException */ public void createXML(org.perfcake.model.Scenario model, OutputStream out) throws ScenarioException { try { JAXBContext context = JAXBContext.newInstance(org.perfcake.model.Scenario.class); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); //obtain url to schema definition, which is located somewhere in PerfCakeBundle URL schemaUrl = SchemaScanner.getSchema(); Schema schema = schemaFactory.newSchema(schemaUrl); Marshaller marshaller = context.createMarshaller(); marshaller.setSchema(schema); //add line breaks and indentation into output marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(model, out); } catch (JAXBException e) { log.error("JAXB error", e); throw new ScenarioException("JAXB error", e); } catch (MalformedURLException e) { log.error("Malformed url", e); throw new ScenarioException("Malformed url", e); } catch (SAXException e) { log.error("Cannot obtain schema definition", e); throw new ScenarioException("Cannot obtain schema definition", e); } catch (IOException e) { log.error("Cannot obtain XML schema file", e); throw new ScenarioException("Cannot obtain XML schema file", e); } }
From source file:org.plasma.common.bind.ValidatingUnmarshaler.java
private Unmarshaller createUnmarshaler(URL url, JAXBContext context) throws JAXBException, SAXException { Unmarshaller u = context.createUnmarshaller(); // adds a custom object factory // u.setProperty("com.sun.xml.bind.ObjectFactory",new // ObjectFactoryEx()); SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); Schema schemaGrammar = schemaFactory.newSchema(url); u.setSchema(schemaGrammar);//from w w w.j a v a 2s .c om return u; }
From source file:org.plasma.common.bind.ValidatingUnmarshaler.java
/** * Creates an unmarshaler using the given factories and sream. Loads only * the given (subclass) schema as this is the "root" schema and it should * include any other schema resources it needs, and so on. Note all included * schemas MUST be found at the same class level as the root schema. * //from ww w . ja v a2 s.co m * @param stream * the Schema stream * @param context * the SAXB context * @param handler * the SAX handler * @param resolver * the SAX resolver * @return the unmarshaler * @throws JAXBException * @throws SAXException */ private Unmarshaller createUnmarshaler(InputStream[] streams, JAXBContext context, Handler handler, Resolver resolver) throws JAXBException, SAXException { Unmarshaller u = context.createUnmarshaller(); SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); StreamSource[] sources = new StreamSource[streams.length]; for (int i = 0; i < streams.length; i++) { sources[i] = new StreamSource(streams[i]); //FIXME: will not resolve relative URI's (included schemas) without this //sources[i].setSystemId(systemId) } Schema schemaGrammar = schemaFactory.newSchema(sources); u.setSchema(schemaGrammar); Validator schemaValidator = schemaGrammar.newValidator(); schemaValidator.setResourceResolver(resolver); schemaValidator.setErrorHandler(handler); return u; }
From source file:org.raml.parser.visitor.SchemaCompiler.java
public Schema compile(String schema, String path) { Schema compiledSchema = null; String trimmedSchema = StringUtils.trimToEmpty(schema); if (trimmedSchema.startsWith("<") && trimmedSchema.endsWith(">")) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); ContextPath actualContextPath = contextPath; if (path != null) { actualContextPath = new ContextPath(new IncludeInfo(path)); }//from www .j av a 2 s .c om factory.setResourceResolver(new XsdResourceResolver(actualContextPath, resourceLoader)); try { compiledSchema = factory.newSchema(new StreamSource(new StringReader(trimmedSchema))); } catch (Exception e) { //ignore exception as the error is detected by the validator // and here we cannot tell if the schema is intended for xml or not } } return compiledSchema; }
From source file:org.rhq.core.clientapi.descriptor.AgentPluginDescriptorUtil.java
/** * Parses a descriptor from InputStream without a validator. * @param is input to check//from www . j a v a 2 s.c om * @return parsed PluginDescriptor * @throws PluginContainerException if validation fails */ public static PluginDescriptor parsePluginDescriptor(InputStream is, ValidationEventCollector validationEventCollector) throws PluginContainerException { JAXBContext jaxbContext; try { jaxbContext = JAXBContext.newInstance(DescriptorPackages.PC_PLUGIN); } catch (Exception e) { throw new PluginContainerException("Failed to create JAXB Context.", new WrappedRemotingException(e)); } Unmarshaller unmarshaller; try { unmarshaller = jaxbContext.createUnmarshaller(); // Enable schema validation URL pluginSchemaURL = AgentPluginDescriptorUtil.class.getClassLoader().getResource(PLUGIN_SCHEMA_PATH); Schema pluginSchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(pluginSchemaURL); unmarshaller.setSchema(pluginSchema); unmarshaller.setEventHandler(validationEventCollector); PluginDescriptor pluginDescriptor = (PluginDescriptor) unmarshaller.unmarshal(is); return pluginDescriptor; } catch (JAXBException e) { throw new PluginContainerException(e); } catch (SAXException e) { throw new PluginContainerException(e); } }
From source file:org.rhq.enterprise.server.plugins.url.XmlIndexParser.java
@SuppressWarnings("unchecked") protected Map<String, RemotePackageInfo> jaxbParse(InputStream indexStream, URL indexUrl, String rootUrlString) throws Exception { JAXBContext jaxbContext = JAXBContext.newInstance(XmlSchemas.PKG_CONTENTSOURCE_PACKAGEDETAILS); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); // Enable schema validation URL pluginSchemaURL = XmlIndexParser.class.getClassLoader().getResource(PLUGIN_SCHEMA_PATH); Schema pluginSchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(pluginSchemaURL); unmarshaller.setSchema(pluginSchema); ValidationEventCollector vec = new ValidationEventCollector(); unmarshaller.setEventHandler(vec);//from ww w. j a va 2s. c om BufferedReader reader = new BufferedReader(new InputStreamReader(indexStream)); JAXBElement<PackageType> packagesXml = (JAXBElement<PackageType>) unmarshaller.unmarshal(reader); for (ValidationEvent event : vec.getEvents()) { log.debug("URL content source index [" + indexUrl + "] message {Severity: " + event.getSeverity() + ", Message: " + event.getMessage() + ", Exception: " + event.getLinkedException() + "}"); } Map<String, RemotePackageInfo> fileList = new HashMap<String, RemotePackageInfo>(); List<PackageDetailsType> allPackages = packagesXml.getValue().getPackage(); for (PackageDetailsType pkg : allPackages) { URL locationUrl = new URL(rootUrlString + pkg.getLocation()); ContentProviderPackageDetails details = translateXmlToDomain(pkg); FullRemotePackageInfo rpi = new FullRemotePackageInfo(locationUrl, details); fileList.put(stripLeadingSlash(rpi.getLocation()), rpi); } return fileList; }
From source file:org.rhq.enterprise.server.xmlschema.ServerPluginDescriptorUtil.java
/** * This will return a JAXB unmarshaller that will enable the caller to parse a server plugin * descriptor. The returned unmarshaller will have a {@link ValidationEventCollector} * installed as an {@link Unmarshaller#getEventHandler() event handler} which can be used * to obtain error messages if the unmarshaller fails to parse an XML document. * /*from ww w.j a va 2 s .c om*/ * @return a JAXB unmarshaller enabling the caller to parse server plugin descriptors * * @throws Exception if an unmarshaller could not be created */ public static Unmarshaller getServerPluginDescriptorUnmarshaller() throws Exception { // create the JAXB context with all the generated plugin packages in it JAXBContext jaxbContext; try { jaxbContext = JAXBContext.newInstance(PLUGIN_CONTEXT_PATH); } catch (Exception e) { throw new Exception("Failed to create JAXB Context.", e); } // create the unmarshaller that can be used to parse XML documents containing server plugin descriptors Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); // enable schema validation to ensure the XML documents parsed by the unmarshaller are valid descriptors ClassLoader cl = ServerPluginDescriptorUtil.class.getClassLoader(); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); StreamSource[] schemaSources = new StreamSource[PLUGIN_SCHEMA_PACKAGES.size()]; int i = 0; for (String schemaPath : PLUGIN_SCHEMA_PACKAGES.keySet()) { URL schemaURL = cl.getResource(schemaPath); schemaSources[i++] = new StreamSource(schemaURL.toExternalForm()); } Schema pluginSchema = schemaFactory.newSchema(schemaSources); unmarshaller.setSchema(pluginSchema); ValidationEventCollector vec = new ValidationEventCollector(); unmarshaller.setEventHandler(vec); return unmarshaller; }
From source file:org.rimudb.configuration.AbstractXmlLoader.java
/** * @param document//w ww.ja v a2s . c o m * @param compoundDbSchemaUrl * @return SAXParseException * @throws Exception */ protected SAXParseException validate(Document document, String compoundDbSchemaUrl) throws Exception { // Compile a schema for the XSD SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // Look up the schema URL and find it's local resource file URL schemaURL = null; String schemaPath = RimuDBNamespace.lookupInternalSchema(compoundDbSchemaUrl); if (schemaPath != null) { schemaURL = getClass().getClassLoader().getResource(schemaPath); } else { schemaURL = new URL(compoundDbSchemaUrl); } Schema schema = schemaFactory.newSchema(schemaURL); // Validate the document against the schema Validator validator = schema.newValidator(); validator.setErrorHandler(new StrictErrorHandler()); try { validator.validate(new DOMSource(document), new DOMResult()); } catch (SAXParseException e) { return e; } return null; }
From source file:org.roda.core.common.PremisV3Utils.java
public static boolean isPremisV2(Binary binary) throws IOException, SAXException { boolean premisV2 = true; InputStream inputStream = binary.getContent().createInputStream(); InputStream schemaStream = RodaCoreFactory.getConfigurationFileAsStream("schemas/premis-v2-0.xsd"); Source xmlFile = new StreamSource(inputStream); SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream)); Validator validator = schema.newValidator(); RodaErrorHandler errorHandler = new RodaErrorHandler(); validator.setErrorHandler(errorHandler); try {/*from www . j a v a2s .c o m*/ validator.validate(xmlFile); List<SAXParseException> errors = errorHandler.getErrors(); if (!errors.isEmpty()) { premisV2 = false; } } catch (SAXException e) { premisV2 = false; } IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(schemaStream); return premisV2; }