List of usage examples for javax.xml.validation SchemaFactory newSchema
public abstract Schema newSchema(Source[] schemas) throws SAXException;
From source file:at.gv.egiz.slbinding.SLUnmarshaller.java
private static Schema createSchema(Collection<String> schemaUrls) throws SAXException, IOException { Logger log = LoggerFactory.getLogger(SLUnmarshaller.class); Source[] sources = new Source[schemaUrls.size()]; Iterator<String> urls = schemaUrls.iterator(); StringBuilder sb = null;/*w ww. j a va 2 s.co m*/ if (log.isDebugEnabled()) { sb = new StringBuilder(); sb.append("Created schema using URLs: "); } for (int i = 0; i < sources.length && urls.hasNext(); i++) { String url = urls.next(); if (url != null && url.startsWith("classpath:")) { URL schemaUrl = new URL(null, url, new ClasspathURLStreamHandler()); sources[i] = new StreamSource(schemaUrl.openStream()); } else { sources[i] = new StreamSource(url); } if (sb != null) { sb.append(url); if (urls.hasNext()) { sb.append(", "); } } } SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(sources); if (sb != null) { log.debug(sb.toString()); } return schema; }
From source file:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java
private static Object validate(final Unmarshaller unmarshaller, final ValidationEventHandler validationEventHandler, final Reader reader, final boolean includeMetaDataSchema) throws JAXBException, SAXException, IOException { Object jaxbObject = null;//from w w w . ja v a2 s. com try { // Set the schema for the unmarshaller final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema = schemaFactory .newSchema(getSchemaSources(includeMetaDataSchema).toArray(new Source[] {})); unmarshaller.setSchema(schema); unmarshaller.setEventHandler(validationEventHandler); // Unmarshal and validate jaxbObject = unmarshaller.unmarshal(reader); } catch (UnmarshalException ue) { // Swallow the exception. The ValidationEventHandler attached to the unmarshaller will // contain the validation events logger.info(ue); } return jaxbObject; }
From source file:de.iteratec.iteraplan.businesslogic.service.SavedQueryXmlHelper.java
private static Schema getSchema(String schemaName) throws SAXException { SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); URL inStream = SavedQueryServiceImpl.class.getResource(schemaName); if (inStream == null) { throw new IteraplanTechnicalException(IteraplanErrorMessages.FILE_NOT_FOUND_EXCEPTION); }/*from w ww.j av a2 s. c o m*/ return sf.newSchema(inStream); }
From source file:com.maxl.java.aips2sqlite.Aips2Sqlite.java
static List<MedicalInformations.MedicalInformation> readAipsFile() { List<MedicalInformations.MedicalInformation> med_list = null; try {// w w w.ja v a2 s . c o m JAXBContext context = JAXBContext.newInstance(MedicalInformations.class); // Validation SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new File(Constants.FILE_MEDICAL_INFOS_XSD)); Validator validator = schema.newValidator(); validator.setErrorHandler(new MyErrorHandler()); // Marshaller /* * Marshaller ma = context.createMarshaller(); * ma.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); * MedicalInformations medi_infos = new MedicalInformations(); * ma.marshal(medi_infos, System.out); */ // Unmarshaller long startTime = System.currentTimeMillis(); if (CmlOptions.SHOW_LOGS) System.out.print("- Unmarshalling Swissmedic xml... "); FileInputStream fis = new FileInputStream(new File(Constants.FILE_MEDICAL_INFOS_XML)); Unmarshaller um = context.createUnmarshaller(); MedicalInformations med_infos = (MedicalInformations) um.unmarshal(fis); med_list = med_infos.getMedicalInformation(); long stopTime = System.currentTimeMillis(); if (CmlOptions.SHOW_LOGS) System.out.println(med_list.size() + " medis in " + (stopTime - startTime) / 1000.0f + " sec"); } catch (IOException e) { e.printStackTrace(); } catch (JAXBException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return med_list; }
From source file:org.psikeds.knowledgebase.xml.impl.XSDValidator.java
/** * Validate XML against specified XSD schmema.<br> * <b>Note:</b> The XML source/stream will not be closed. This must be * invoked by the caller afterwards!<br> * /* ww w . j av a2 s.com*/ * @param xsd * Source for XSD-schema that will be used to validate the XML * @param xml * Source for XML * @throws SAXException * if XML is not valid against XSD * @throws IOException */ public static void validate(final Source xsd, final Source xml) throws SAXException, IOException { final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema = factory.newSchema(xsd); final Validator validator = schema.newValidator(); validator.validate(xml); }
From source file:dk.netarkivet.common.utils.XmlUtils.java
/** * Validate that the settings xml files conforms to the XSD. * * @param xsdFile Schema to check settings against. * @throws ArgumentNotValid if unable to validate the settings files * @throws IOFailure If unable to read the settings files and/or * the xsd file.//www. ja v a 2 s.co m */ public static void validateWithXSD(File xsdFile) { ArgumentNotValid.checkNotNull(xsdFile, "File xsdFile"); List<File> settingsFiles = Settings.getSettingsFiles(); for (File settingsFile : settingsFiles) { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder parser = builderFactory.newDocumentBuilder(); org.w3c.dom.Document document = parser.parse(settingsFile); // create a SchemaFactory capable of understanding WXS schemas SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // load a WXS schema, represented by a Schema instance Source schemaFile = new StreamSource(xsdFile); Schema schema = factory.newSchema(schemaFile); // create a Validator instance, which can be used to validate an // instance document Validator validator = schema.newValidator(); // validate the DOM tree try { validator.validate(new DOMSource(document)); } catch (SAXException e) { // instance document is invalid! final String msg = "Settings file '" + settingsFile + "' does not validate using '" + xsdFile + "'"; log.warn(msg, e); throw new ArgumentNotValid(msg, e); } } catch (IOException e) { throw new IOFailure("Error while validating: ", e); } catch (ParserConfigurationException e) { final String msg = "Error validating settings file '" + settingsFile + "'"; log.warn(msg, e); throw new ArgumentNotValid(msg, e); } catch (SAXException e) { final String msg = "Error validating settings file '" + settingsFile + "'"; log.warn(msg, e); throw new ArgumentNotValid(msg, e); } } }
From source file:com.aionemu.gameserver.model.TribeRelationCheck.java
@BeforeClass public static void init() throws Exception { File xml = new File("./data/static_data/tribe/tribe_relations.xml"); Schema schema = null;/* ww w . j av a2 s. co m*/ SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); TribeRelationsData tribeRelations = null; NpcData npcTemplates = null; try { schema = sf.newSchema(new File("./data/static_data/tribe/tribe_relations.xsd")); JAXBContext jc = JAXBContext.newInstance(TribeRelationsData.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); unmarshaller.setSchema(schema); tribeRelations = (TribeRelationsData) unmarshaller.unmarshal(xml); xml = new File("./data/static_data/npcs/npc_templates.xml"); schema = sf.newSchema(new File("./data/static_data/npcs/npcs.xsd")); jc = JAXBContext.newInstance(NpcData.class); unmarshaller = jc.createUnmarshaller(); unmarshaller.setSchema(schema); npcTemplates = (NpcData) unmarshaller.unmarshal(xml); } catch (SAXException e1) { System.out.println(e1.getMessage()); } catch (JAXBException e2) { System.out.println(e2.getMessage()); } // Not interesting DataManager.NPC_SKILL_DATA = new NpcSkillData(); DataManager.NPC_DATA = npcTemplates; DataManager.TRIBE_RELATIONS_DATA = tribeRelations; DataManager.ZONE_DATA = new DummyZoneData(); DataManager.WORLD_MAPS_DATA = new DummyWorldMapData(); Config.load(); // AIConfig.ONCREATE_DEBUG = true; AIConfig.EVENT_DEBUG = true; ThreadConfig.THREAD_POOL_SIZE = 20; ThreadPoolManager.getInstance(); AI2Engine.getInstance().load(null); /** * Comment out these lines in DAOManager.registerDAO() if not using DB: <tt> * if (!dao.supports(getDatabaseName(), * getDatabaseMajorVersion(), getDatabaseMinorVersion())) { return; } * </tt> */ DAOManager.init(); world = World.getInstance(); asmo = DummyPlayer.createAsmodian(); asmoPosition = World.getInstance().createPosition(DummyWorldMapData.DEFAULT_MAP, 100f, 100f, 0f, (byte) 0, 0); MapRegion asmoRegion = asmoPosition.getWorldMapInstance().getRegion(100f, 100f, 0); asmoRegion.getObjects().put(asmo.getObjectId(), asmo); asmoRegion.activate(); asmo.setPosition(asmoPosition); ely = DummyPlayer.createElyo(); elyPosition = World.getInstance().createPosition(DummyWorldMapData.DEFAULT_MAP, 200f, 200f, 0f, (byte) 0, 0); MapRegion elyRegion = elyPosition.getWorldMapInstance().getRegion(200f, 200f, 0); elyRegion.getObjects().put(ely.getObjectId(), ely); elyRegion.activate(); ely.setPosition(elyPosition); PacketBroadcaster.getInstance(); DuelService.getInstance(); PlayerMoveTaskManager.getInstance(); MoveTaskManager.getInstance(); }
From source file:main.java.refinement_class.Useful.java
public static boolean validation(String schema_file, String xml_file) { Object obj = null;//www . ja v a 2 s. com // create a JAXBContext capable of handling classes generated into // JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class ); JAXBContext jc; try { jc = JAXBContext.newInstance(); // create an Unmarshaller Unmarshaller u = jc.createUnmarshaller(); SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { javax.xml.validation.Schema schema = sf.newSchema(new File(schema_file)); u.setSchema((javax.xml.validation.Schema) schema); u.setEventHandler(new ValidationEventHandler() { // allow unmarshalling to continue even if there are errors public boolean handleEvent(ValidationEvent ve) { // ignore warnings 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(); LOG.error(se.toString()); } } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); LOG.error(e.toString()); } return true; }
From source file:edu.lternet.pasta.common.XmlUtility.java
/** * Returns the provided XML string as a schema. * * @param xmlString an XML schema.//from w w w. j av a2 s .c o m * * @return a schema object that corresponds to the provided string. */ public static Schema xmlStringToSchema(String xmlString) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setErrorHandler(new XmlParsingErrorHandler(xmlString)); StreamSource source = new StreamSource(new StringReader(xmlString)); try { return factory.newSchema(source); } catch (SAXException e) { throw new IllegalStateException(e); // shouldn't be reached } }
From source file:info.novatec.ita.check.config.StereotypeCheckReader.java
/** * Read and validate the given file to a configuration for stereotype check. * /*from w w w.j a va2 s . co m*/ * @param file * The file to read. * @param additionalCheckCfg * a previously read configuration which may override parts of * the configuration read by the file. * @param readingAdditionalCfg * Are we reading the additionalCfg. * @return the configuration. * @throws XMLStreamException * @throws IllegalArgumentException * @throws SAXException * @throws IOException */ private static StereotypeCheckConfiguration read(File file, String checkstyleStereotypeXsd, StereotypeCheckConfiguration additionalCheckCfg, boolean readingAdditionalCfg) throws XMLStreamException, IllegalArgumentException, SAXException, IOException { // Validate with StreamSource because Stax Validation is not provided // with every implementation of JAXP SchemaFactory schemafactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemafactory .newSchema(StereotypeCheckReader.class.getClassLoader().getResource(checkstyleStereotypeXsd)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(file)); // Parse with Stax XMLStreamReader reader = XMLInputFactory.newInstance() .createXMLStreamReader(new BufferedInputStream(new FileInputStream(file))); StereotypeCheckConfigurationReader delegate = new StereotypeCheckConfigurationReader(reader, additionalCheckCfg, readingAdditionalCfg); while (delegate.hasNext()) { delegate.next(); } return delegate.getConfig(); }