List of usage examples for javax.xml.validation SchemaFactory newSchema
public abstract Schema newSchema(Source[] schemas) throws SAXException;
From source file:org.rivetlogic.export.components.AbstractXMLProcessor.java
public void setXsdPath(String xsdPath) throws SAXException { this.xsdPath = xsdPath; if (xsdPath != null) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = null;/*from www . java 2 s . c o m*/ try { schema = factory.newSchema(this.getClass().getClassLoader().getResource(xsdPath)); } catch (SAXException e) { logger.error(e); throw e; } validator = schema.newValidator(); } }
From source file:org.mitre.stix.STIXSchema.java
/** * Private constructor to permit a single STIXSchema to exists. *//*from www .j a v a 2s. c om*/ private STIXSchema() { this.version = ((Version) this.getClass().getPackage().getAnnotation(Version.class)).schema(); ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver( this.getClass().getClassLoader()); Resource[] schemaResources; try { schemaResources = patternResolver.getResources("classpath:schemas/v" + version + "/**/*.xsd"); prefixSchemaBindings = new HashMap<String, String>(); String url, prefix, targetNamespace; Document schemaDocument; NamedNodeMap attributes; Node attribute; for (Resource resource : schemaResources) { url = resource.getURL().toString(); schemaDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(resource.getInputStream()); schemaDocument.getDocumentElement().normalize(); attributes = schemaDocument.getDocumentElement().getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { attribute = attributes.item(i); targetNamespace = schemaDocument.getDocumentElement().getAttribute("targetNamespace"); if (attribute.getNodeName().startsWith("xmlns:") && attribute.getNodeValue().equals(targetNamespace)) { prefix = attributes.item(i).getNodeName().split(":")[1]; if ((prefixSchemaBindings.containsKey(prefix)) && (prefixSchemaBindings.get(prefix).split("schemas/v" + version + "/")[1] .startsWith("external"))) { continue; } LOGGER.fine(" adding: " + prefix + " :: " + url); prefixSchemaBindings.put(prefix, url); } } } SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source[] schemas = new Source[prefixSchemaBindings.values().size()]; int i = 0; for (String schemaLocation : prefixSchemaBindings.values()) { schemas[i++] = new StreamSource(schemaLocation); } schema = factory.newSchema(schemas); validator = schema.newValidator(); validator.setErrorHandler(new ValidationErrorHandler()); } catch (IOException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } }
From source file:eu.artist.postmigration.eubt.executiontrace.abstractor.SOAPTraceAbstractor.java
/** * Validates soap trace (i.e., list of soap responses) against schema and * stores the result/*from w w w . j av a 2 s .c o m*/ * * @param soapResponseTrace trace that contains soap responses * @return map of soap responses and their respective validation result * @throws EUBTException in case the schema location could not be found */ private LinkedMap<SOAPResponse, String> validateSoapTrace(final SOAPTrace soapResponseTrace) throws EUBTException { final LinkedMap<SOAPResponse, String> validationResults = new LinkedMap<SOAPResponse, String>(); final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Validator validator; try { final Schema schema = schemaFactory.newSchema(new URL(schemaLocation)); validator = schema.newValidator(); } catch (SAXException | IOException e) { throw new EUBTException("Failed to create Schema from Schema location " + schemaLocation + ". Detailed Exception: " + e.getMessage()); } // for each soap response for (final Response response : soapResponseTrace.getResponses()) { String validationResult = VALIDATION_INVALID; final SOAPResponse soapResponse = (SOAPResponse) response; final SOAPEnvelope soapEnvelope = (SOAPEnvelope) soapResponse.getData(); final OMElement bodyContent = soapEnvelope.getBody().getFirstElement(); // create some invalid content // SOAP12Factory factory = new SOAP12Factory(); // OMElement invalidElement = factory.createOMElement(new QName("blah")); // OMNamespace invalidNamespace = factory.createOMNamespace("http://notMyNamespace.com", "invNS"); // OMAttribute invalidAttribute = factory.createOMAttribute("someAttribute", invalidNamespace, "attributeValue"); // bodyContent.addChild(invalidElement); // bodyContent.addAttribute(invalidAttribute); // validate soap body content -> will cause an exception if not valid try { validator.validate(bodyContent.getSAXSource(true)); // validation succeeded validationResult = VALIDATION_VALID; Debug.debug(this, "Successfully validated SOAP body content " + bodyContent); } catch (final IOException e) { throw new EUBTException("Failed to validate SOAP body content " + bodyContent + ". Detailed Exception: " + e.getMessage()); } catch (final SAXException e) { // validation failed Debug.debug(this, "Failed to validate soap SOAP content " + bodyContent + ". Detailed Exception: " + e.getMessage()); } // finished validating, store result validationResults.put(soapResponse, validationResult); validator.reset(); } // for each soap response return validationResults; }
From source file:eu.esdihumboldt.hale.io.appschema.writer.AppSchemaFileWriterTest.java
private boolean isMappingValid(File mappingFile) throws IOException { URL mappingSchema = getClass().getResource(MAPPING_SCHEMA); Source xmlFile = new StreamSource(mappingFile); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); javax.xml.validation.Schema schema = null; try {/*from ww w. j a va 2 s . c o m*/ schema = schemaFactory.newSchema(mappingSchema); } catch (SAXException e) { fail("Exception parsing mapping schema: " + e.getMessage()); } @SuppressWarnings("null") Validator validator = schema.newValidator(); try { validator.validate(xmlFile); return true; } catch (SAXException e) { log.error("Mapping file validation failed", e); return false; } }
From source file:no.met.jtimeseries.service.TimeSeriesService.java
private Schema getLocationForecastSchema() throws SAXException { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL locationForecastSchemaUrl = getLocationForecastSchemaUrl(); Schema schema = sf.newSchema(locationForecastSchemaUrl); return schema; }
From source file:com.graphhopper.util.InstructionListTest.java
public void verifyGPX(String gpx) { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = null;//from w w w . j a v a 2 s . c o m try { Source schemaFile = new StreamSource(getClass().getResourceAsStream("gpx-schema.xsd")); schema = schemaFactory.newSchema(schemaFile); // using more schemas: http://stackoverflow.com/q/1094893/194609 } catch (SAXException e1) { throw new IllegalStateException( "There was a problem with the schema supplied for validation. Message:" + e1.getMessage()); } Validator validator = schema.newValidator(); try { validator.validate(new StreamSource(new StringReader(gpx))); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.aionemu.gameserver.dataholders.SpawnsData2.java
public synchronized boolean saveSpawn(Player admin, VisibleObject visibleObject, boolean delete) throws IOException { SpawnTemplate spawn = visibleObject.getSpawn(); Spawn oldGroup = DataManager.SPAWNS_DATA2.getSpawnsForNpc(visibleObject.getWorldId(), spawn.getNpcId()); File xml = new File("./data/static_data/spawns/" + getRelativePath(visibleObject)); SpawnsData2 data = null;/*from w w w. j a va2 s.c o m*/ SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = null; JAXBContext jc = null; boolean addGroup = false; try { schema = sf.newSchema(new File("./data/static_data/spawns/spawns.xsd")); jc = JAXBContext.newInstance(SpawnsData2.class); } catch (Exception e) { // ignore, if schemas are wrong then we even could not call the command; } FileInputStream fin = null; if (xml.exists()) { try { fin = new FileInputStream(xml); Unmarshaller unmarshaller = jc.createUnmarshaller(); unmarshaller.setSchema(schema); data = (SpawnsData2) unmarshaller.unmarshal(fin); } catch (Exception e) { log.error(e.getMessage()); PacketSendUtility.sendMessage(admin, "Could not load old XML file!"); return false; } finally { if (fin != null) { fin.close(); } } } if (oldGroup == null || oldGroup.isCustom()) { if (data == null) { data = new SpawnsData2(); } oldGroup = data.getSpawnsForNpc(visibleObject.getWorldId(), spawn.getNpcId()); if (oldGroup == null) { oldGroup = new Spawn(spawn.getNpcId(), spawn.getRespawnTime(), spawn.getHandlerType()); addGroup = true; } } else { if (data == null) { data = DataManager.SPAWNS_DATA2; } // only remove from memory, will be added back later allSpawnMaps.get(visibleObject.getWorldId()).remove(spawn.getNpcId()); addGroup = true; } SpawnSpotTemplate spot = new SpawnSpotTemplate(visibleObject.getX(), visibleObject.getY(), visibleObject.getZ(), visibleObject.getHeading(), visibleObject.getSpawn().getRandomWalk(), visibleObject.getSpawn().getWalkerId(), visibleObject.getSpawn().getWalkerIndex()); boolean changeX = visibleObject.getX() != spawn.getX(); boolean changeY = visibleObject.getY() != spawn.getY(); boolean changeZ = visibleObject.getZ() != spawn.getZ(); boolean changeH = visibleObject.getHeading() != spawn.getHeading(); if (changeH && visibleObject instanceof Npc) { Npc npc = (Npc) visibleObject; if (!npc.isAtSpawnLocation() || !npc.isInState(CreatureState.NPC_IDLE) || changeX || changeY || changeZ) { // if H changed, XSD validation fails, because it may be negative; thus, reset it back visibleObject.setXYZH(null, null, null, spawn.getHeading()); changeH = false; } } SpawnSpotTemplate oldSpot = null; for (SpawnSpotTemplate s : oldGroup.getSpawnSpotTemplates()) { if (s.getX() == spot.getX() && s.getY() == spot.getY() && s.getZ() == spot.getZ() && s.getHeading() == spot.getHeading()) { if (delete || !StringUtils.equals(s.getWalkerId(), spot.getWalkerId())) { oldSpot = s; break; } else { return false; // nothing to change } } else if (changeX && s.getY() == spot.getY() && s.getZ() == spot.getZ() && s.getHeading() == spot.getHeading() || changeY && s.getX() == spot.getX() && s.getZ() == spot.getZ() && s.getHeading() == spot.getHeading() || changeZ && s.getX() == spot.getX() && s.getY() == spot.getY() && s.getHeading() == spot.getHeading() || changeH && s.getX() == spot.getX() && s.getY() == spot.getY() && s.getZ() == spot.getZ()) { oldSpot = s; break; } } if (oldSpot != null) { oldGroup.getSpawnSpotTemplates().remove(oldSpot); } if (!delete) { oldGroup.addSpawnSpot(spot); } oldGroup.setCustom(true); SpawnMap map = null; if (data.templates == null) { data.templates = new ArrayList<SpawnMap>(); map = new SpawnMap(spawn.getWorldId()); data.templates.add(map); } else { map = data.templates.get(0); } if (addGroup) { map.addSpawns(oldGroup); } FileOutputStream fos = null; try { xml.getParentFile().mkdir(); fos = new FileOutputStream(xml); Marshaller marshaller = jc.createMarshaller(); marshaller.setSchema(schema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(data, fos); DataManager.SPAWNS_DATA2.templates = data.templates; DataManager.SPAWNS_DATA2.afterUnmarshal(null, null); DataManager.SPAWNS_DATA2.clearTemplates(); data.clearTemplates(); } catch (Exception e) { log.error(e.getMessage()); PacketSendUtility.sendMessage(admin, "Could not save XML file!"); return false; } finally { if (fos != null) { fos.close(); } } return true; }
From source file:com.rest4j.ApiFactory.java
/** * Create the API instance. The XML describing the API is read, preprocessed, analyzed for errors, * and the internal structures for Java object marshalling and unmarshalling are created, as * well as endpoint mappings.//from w w w. j av a2s .com * * @return The API instance * @throws ConfigurationException When there is a problem with your XML description. */ public API createAPI() throws ConfigurationException { try { JAXBContext context; if (extObjectFactory == null) context = JAXBContext.newInstance(com.rest4j.impl.model.ObjectFactory.class); else context = JAXBContext.newInstance(com.rest4j.impl.model.ObjectFactory.class, extObjectFactory); Document xml = getDocument(); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source apiXsdSource = new StreamSource(getClass().getResourceAsStream("api.xsd")); List<Source> xsds = new ArrayList<Source>(); xsds.add(apiXsdSource); Schema schema; if (!StringUtils.isEmpty(extSchema)) { xsds.add(new StreamSource(getClass().getClassLoader().getResourceAsStream(extSchema))); } xsds.add(new StreamSource(getClass().getResourceAsStream("html.xsd"))); schema = schemaFactory.newSchema(xsds.toArray(new Source[xsds.size()])); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setSchema(schema); JAXBElement<com.rest4j.impl.model.API> element = (JAXBElement<com.rest4j.impl.model.API>) unmarshaller .unmarshal(xml); com.rest4j.impl.model.API root = element.getValue(); APIImpl api; api = new APIImpl(root, pathPrefix, serviceProvider, factories.toArray(new ObjectFactory[factories.size()]), fieldFilters.toArray(new FieldFilter[fieldFilters.size()]), permissionChecker); return api; } catch (javax.xml.bind.UnmarshalException e) { if (e.getLinkedException() instanceof SAXParseException) { SAXParseException spe = (SAXParseException) e.getLinkedException(); throw new ConfigurationException("Cannot parse " + apiDescriptionXml, spe); } throw new AssertionError(e); } catch (ConfigurationException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new AssertionError(e); } }
From source file:ca.uhn.fhir.validation.SchemaBaseValidator.java
private Schema loadSchema(String theVersion, String theSchemaName) { String key = theVersion + "-" + theSchemaName; synchronized (myKeyToSchema) { Schema schema = myKeyToSchema.get(key); if (schema != null) { return schema; }/*w ww.java2 s. c om*/ Source baseSource = loadXml(null, theSchemaName); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setResourceResolver(new MyResourceResolver()); try { try { /* * See https://github.com/jamesagnew/hapi-fhir/issues/339 * https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing */ schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); } catch (SAXNotRecognizedException snex) { ourLog.warn("Jaxp 1.5 Support not found.", snex); } schema = schemaFactory.newSchema(new Source[] { baseSource }); } catch (SAXException e) { throw new ConfigurationException("Could not load/parse schema file: " + theSchemaName, e); } myKeyToSchema.put(key, schema); return schema; } }
From source file:org.kite9.diagram.server.AbstractKite9Controller.java
protected void validateXML(String xml) throws SAXException, IOException { // validate the xml against the schema InputSource is = new InputSource(new StringReader(xml)); SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); // load a WXS schema, represented by a Schema instance Source schemaFile = new StreamSource(Diagram.class.getResourceAsStream("/adl_1.0.xsd")); Schema schema = factory.newSchema(schemaFile); Validator validator = schema.newValidator(); SAXSource source = new SAXSource(is); validator.validate(source);/*from www .j ava2 s .c o m*/ }