List of usage examples for javax.xml.validation Schema newValidator
public abstract Validator newValidator();
From source file:org.keycloak.testsuite.adapter.servlet.AbstractSAMLServletsAdapterTest.java
private void validateXMLWithSchema(String xml, String schemaFileName) throws SAXException, IOException { URL schemaFile = getClass().getResource(schemaFileName); Source xmlFile = new StreamSource(new ByteArrayInputStream(xml.getBytes()), xml); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); try {/*from w ww .j av a 2s .c o m*/ validator.validate(xmlFile); System.out.println(xmlFile.getSystemId() + " is valid"); } catch (SAXException e) { System.out.println(xmlFile.getSystemId() + " is NOT valid"); System.out.println("Reason: " + e.getLocalizedMessage()); Assert.fail(); } }
From source file:com.googlecode.l10nmavenplugin.validators.property.HtmlValidator.java
/** * Initialize using XML schema//from w w w. java2 s.c om * * @param xhtmlSchema * @param logger */ public HtmlValidator(File xhtmlSchema, L10nValidatorLogger logger, L10nValidator<Property> spellCheckValidator, String[] htmlKeys, Formatter formattingParametersExtractor, InnerResourcesFormatter innerResourceFormatter) { super(logger, htmlKeys); this.spellCheckValidator = spellCheckValidator; this.formattingParametersExtractor = formattingParametersExtractor; this.innerResourceFormatter = innerResourceFormatter; try { // SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // Need to use XERCES so that XHTML5 schema passes validation SchemaFactory factory = new XMLSchemaFactory(); factory.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING, false); Schema schema = null; if (xhtmlSchema.exists()) { // Load custom schema schema = factory.newSchema(xhtmlSchema); } else { // Try to load a pre-defined schemas from classpath URL schemaURL = this.getClass().getClassLoader().getResource(xhtmlSchema.getName()); if (schemaURL == null) { logger.getLogger() .error("Could not load XML schema from file <" + xhtmlSchema.getAbsolutePath() + "> and <" + xhtmlSchema.getName() + "> is not a default schema either (" + Arrays.toString(PREDEFINED_XSD) + "), thus defaulting to " + XHTML1_TRANSITIONAL.getName()); schemaURL = this.getClass().getClassLoader().getResource(XHTML1_TRANSITIONAL.getName()); } schema = factory.newSchema(schemaURL); } xhtmlValidator = schema.newValidator(); // Initialize SAX parser SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); parser = saxParserFactory.newSAXParser(); } catch (SAXException e) { logger.getLogger().error("Could not initialize HtmlValidator", e); } catch (ParserConfigurationException e) { logger.getLogger().error("Could not initialize HtmlValidator", e); } }
From source file:integration.AbstractTest.java
/** * Parses the specified file and returns the document. * /*from w w w . j a v a2 s .c om*/ * @param file The file to parse. * @param schemaStreamArray The schema as array of stream sources used to validate the specified file. * @return * @throws Exception Thrown if an error occurred. */ protected Document parseFileWithStreamArray(File file, StreamSource[] schemaStreamArray) throws Exception { if (file == null) throw new IllegalArgumentException("No file to parse."); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); // This must be set to avoid error : cvc-elt.1: Cannot find the declaration of element 'OME'. SchemaFactory sFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); SchemaResolver theTestClassResolver = new SchemaResolver(); sFactory.setResourceResolver(theTestClassResolver); Schema theSchema = sFactory.newSchema(schemaStreamArray); /* // Version - one step parse and validate (print error to stdErr) dbf.setSchema(theSchema); DocumentBuilder builder = dbf.newDocumentBuilder(); Document theDoc = builder.parse(file); */ // Version - two step parse then validate (throws error as exception) DocumentBuilder builder = dbf.newDocumentBuilder(); Document theDoc = builder.parse(file); Validator validator = theSchema.newValidator(); validator.validate(new DOMSource(theDoc)); return theDoc; }
From source file:eu.eidas.auth.engine.EIDASSAMLEngine.java
public static String validateSchema(String samlRequestXML) throws EIDASSAMLEngineException { Document document;/*from www . j a va 2 s . c o m*/ javax.xml.validation.Schema schema = null; javax.xml.validation.Validator validator; try { BasicParserPool ppMgr = getNewBasicSecuredParserPool(); ppMgr.setNamespaceAware(true); InputStream inputStream = new ByteArrayInputStream(samlRequestXML.getBytes("UTF-8")); document = ppMgr.parse(inputStream); Element samlElemnt = document.getDocumentElement(); schema = SAMLSchemaBuilder.getSAML11Schema(); validator = schema.newValidator(); DOMSource domSrc = new DOMSource(samlElemnt); validator.validate(domSrc); } catch (XMLParserException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Validate schema exception", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Validate schema exception", e); if (e.getCause().toString().contains("DOCTYPE is disallowed")) { throw new EIDASSAMLEngineException( EIDASUtil.getConfig(EIDASErrors.DOC_TYPE_NOT_ALLOWED.errorCode()), EIDASErrors.DOC_TYPE_NOT_ALLOWED.errorCode(), "SAML request contains a DOCTYPE which is not allowed for security reason"); } else { throw new EIDASSAMLEngineException( EIDASUtil.getConfig(EIDASErrors.MESSAGE_VALIDATION_ERROR.errorCode()), EIDASErrors.MESSAGE_VALIDATION_ERROR.errorMessage(), e); } } catch (SAXException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Validate schema exception", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Validate schema exception", e); throw new EIDASSAMLEngineException( EIDASUtil.getConfig(EIDASErrors.MESSAGE_VALIDATION_ERROR.errorCode()), EIDASErrors.MESSAGE_VALIDATION_ERROR.errorMessage(), e); } catch (IOException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Validate schema exception", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Validate schema exception", e); throw new EIDASSAMLEngineException( EIDASUtil.getConfig(EIDASErrors.MESSAGE_VALIDATION_ERROR.errorCode()), EIDASErrors.MESSAGE_VALIDATION_ERROR.errorMessage(), e); } return samlRequestXML; }
From source file:csiro.pidsvc.mappingstore.Manager.java
/************************************************************************** * Generic processing methods.//from w w w.j av a 2 s .co m */ protected void validateRequest(String inputData, String xmlSchemaResourcePath) throws IOException, ValidationException { try { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setResourceResolver(new LSResourceResolver() { @Override public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { return new XsdSchemaResolver(type, namespaceURI, publicId, systemId, baseURI); } }); Schema schema = schemaFactory .newSchema(new StreamSource(getClass().getResourceAsStream(xmlSchemaResourcePath))); Validator validator = schema.newValidator(); _logger.trace("Validating XML Schema."); validator.validate(new StreamSource(new StringReader(inputData))); } catch (SAXException ex) { _logger.debug("Unknown format.", ex); throw new ValidationException("Unknown format.", ex); } }
From source file:nl.b3p.wms.capabilities.WMSCapabilitiesReader.java
/** Private method which validates a XML document at a given location. * * @param location String representing the location where the document can be found. * * @throws IOException/*from www .ja v a 2 s . c o m*/ * @throws SAXException */ // <editor-fold defaultstate="" desc="validate(String location) method."> private void validate(String location) throws IOException, SAXException { SchemaFactory factory = SchemaFactory.newInstance(SCHEMA_FACTORY); File schemaLocation = new File(SCHEMA_FILE); Schema schema = factory.newSchema(schemaLocation); Validator validator = schema.newValidator(); Source source = new StreamSource(new File(location)); validator.validate(source); }
From source file:cz.cas.lib.proarc.common.export.mets.structure.MetsElementVisitor.java
/** * Generates technical metadata using JHOVE * * @param metsElement//from w ww .j a va 2 s .com * @param fileNames * @param seq * @param fileTypes * @param mimeTypes * @param pageDiv * @throws MetsExportException */ private void generateTechMetadata(IMetsElement metsElement, HashMap<String, Object> fileNames, int seq, HashMap<String, FileGrp> fileGrpPage, HashMap<String, String> mimeTypes, DivType pageDiv, HashMap<String, String> outputFileNames, HashMap<String, FileMD5Info> md5InfosMap) throws MetsExportException { if (fileNames.get("TECHMDGRP") == null) { LOG.log(Level.FINE, "Generating tech"); Mets amdSecMets = new Mets(); amdSecMets.setLabel1(mets.getLabel1()); amdSecMets.setTYPE(mets.getTYPE()); StructMapType mapType = new StructMapType(); mapType.setTYPE(Const.DIV_PHYSICAL_ID); amdSecMets.getStructMap().add(mapType); AmdSecType amdSec = new AmdSecType(); amdSec.setID(metsElement.getElementID()); amdSecMets.getAmdSec().add(amdSec); DivType divType = new DivType(); if (Const.PERIODICAL_TITLE .equalsIgnoreCase(metsElement.getMetsContext().getRootElement().getElementType())) { divType.setTYPE("PERIODICAL_PAGE"); } else { divType.setTYPE("MONOGRAPH_PAGE"); } FileSec fileSec = new FileSec(); amdSecMets.setFileSec(fileSec); HashMap<String, FileGrp> amdSecFileGrpMap = new HashMap<String, MetsType.FileSec.FileGrp>(); for (String fileMap : fileGrpPage.keySet()) { FileGrp fileGrp = fileGrpPage.get(fileMap); if (fileGrp.getFile().size() > 0) { FileGrp fileGrpAmd = new FileGrp(); amdSecFileGrpMap.put(fileMap, fileGrpAmd); fileGrpAmd.setID(fileGrp.getID()); fileGrpAmd.setUSE(fileGrp.getUSE()); fileSec.getFileGrp().add(fileGrpAmd); for (FileType fileTypePage : fileGrp.getFile()) { FileType fileTypeAmdSec = new FileType(); fileTypeAmdSec.setCHECKSUM(fileTypePage.getCHECKSUM()); fileTypeAmdSec.setCHECKSUMTYPE(fileTypePage.getCHECKSUMTYPE()); fileTypeAmdSec.setCREATED(fileTypePage.getCREATED()); fileTypeAmdSec.setID(fileTypePage.getID()); fileTypeAmdSec.setMIMETYPE(fileTypePage.getMIMETYPE()); fileTypeAmdSec.setSEQ(fileTypePage.getSEQ()); fileTypeAmdSec.setSIZE(fileTypePage.getSIZE()); fileGrpAmd.getFile().add(fileTypeAmdSec); if (fileTypePage.getFLocat().get(0) != null) { FLocat flocatAmd = new FLocat(); FLocat pageFlocat = fileTypePage.getFLocat().get(0); if (pageFlocat.getHref() != null) { flocatAmd.setHref(".." + pageFlocat.getHref().substring(1)); } flocatAmd.setLOCTYPE(pageFlocat.getLOCTYPE()); fileTypeAmdSec.getFLocat().add(flocatAmd); } Fptr fptr = new Fptr(); fptr.setFILEID(fileTypeAmdSec); divType.getFptr().add(fptr); } } } HashMap<String, String> toGenerate = new HashMap<String, String>(); File rawFile = null; XMLGregorianCalendar rawCreated = null; Mix mixDevice = getScannerMix(metsElement); // RAW datastream for MIX_001 - only for Fedora PhotometricInterpretation photometricInterpretation = null; JHoveOutput jHoveOutputRaw = null; JHoveOutput jHoveOutputMC = null; if (metsElement.getMetsContext().getFedoraClient() != null) { try { DatastreamType rawDS = FoxmlUtils.findDatastream(metsElement.getSourceObject(), "RAW"); if (rawDS != null) { GetDatastreamDissemination dsRaw = FedoraClient .getDatastreamDissemination(metsElement.getOriginalPid(), "RAW"); try { rawCreated = rawDS.getDatastreamVersion().get(0).getCREATED(); InputStream is = dsRaw.execute(metsElement.getMetsContext().getFedoraClient()) .getEntityInputStream(); String rawExtendsion = MimeType .getExtension(rawDS.getDatastreamVersion().get(0).getMIMETYPE()); rawFile = new File(metsElement.getMetsContext().getOutputPath() + File.separator + metsElement.getMetsContext().getPackageID() + File.separator + "raw" + "." + rawExtendsion); FileMD5Info rawinfo; try { rawinfo = MetsUtils.getDigestAndCopy(is, new FileOutputStream(rawFile)); } catch (NoSuchAlgorithmException e) { throw new MetsExportException(metsElement.getOriginalPid(), "Unable to copy RAW image and get digest", false, e); } rawinfo.setMimeType(rawDS.getDatastreamVersion().get(0).getMIMETYPE()); rawinfo.setCreated(rawDS.getDatastreamVersion().get(0).getCREATED()); md5InfosMap.put("RAW", rawinfo); outputFileNames.put("RAW", rawFile.getAbsolutePath()); toGenerate.put("MIX_001", "RAW"); // If mix is present in fedora, then use this one if (metsElement.getMetsContext().getFedoraClient() != null) { jHoveOutputRaw = JhoveUtility.getMixFromFedora(metsElement, MixEditor.RAW_ID); } // If not present, then generate new if (jHoveOutputRaw == null) { jHoveOutputRaw = JhoveUtility.getMix(new File(rawFile.getAbsolutePath()), metsElement.getMetsContext(), mixDevice, rawCreated, null); if (jHoveOutputRaw.getMix() == null) { throw new MetsExportException(metsElement.getOriginalPid(), "Unable to generate Mix information for RAW image", false, null); } } else { // Merges the information from the device mix JhoveUtility.mergeMix(jHoveOutputRaw.getMix(), mixDevice); } if ((jHoveOutputRaw.getMix() != null) && (jHoveOutputRaw.getMix().getBasicImageInformation() != null) && (jHoveOutputRaw.getMix().getBasicImageInformation() .getBasicImageCharacteristics() != null) && (jHoveOutputRaw.getMix().getBasicImageInformation() .getBasicImageCharacteristics() .getPhotometricInterpretation() != null)) { photometricInterpretation = jHoveOutputRaw.getMix().getBasicImageInformation() .getBasicImageCharacteristics().getPhotometricInterpretation(); } fixPSMix(jHoveOutputRaw, metsElement.getOriginalPid(), rawCreated); } catch (FedoraClientException e) { throw new MetsExportException(metsElement.getOriginalPid(), "Unable to read raw datastream content", false, e); } } } catch (IOException ex) { throw new MetsExportException(metsElement.getOriginalPid(), "Error while getting RAW datastream " + metsElement.getOriginalPid(), false, ex); } } if (fileNames.get("MC_IMGGRP") != null) { toGenerate.put("MIX_002", "MC_IMGGRP"); String outputFileName = outputFileNames.get("MC_IMGGRP"); if (outputFileName != null) { String originalFile = MetsUtils.xPathEvaluateString(metsElement.getRelsExt(), "*[local-name()='RDF']/*[local-name()='Description']/*[local-name()='importFile']"); if (metsElement.getMetsContext().getFedoraClient() != null) { jHoveOutputMC = JhoveUtility.getMixFromFedora(metsElement, MixEditor.NDK_ARCHIVAL_ID); } if (jHoveOutputMC == null) { jHoveOutputMC = JhoveUtility.getMix(new File(outputFileName), metsElement.getMetsContext(), null, md5InfosMap.get("MC_IMGGRP").getCreated(), originalFile); if (jHoveOutputMC.getMix() == null) { throw new MetsExportException(metsElement.getOriginalPid(), "Unable to generate Mix information for MC image", false, null); } } fixMCMix(jHoveOutputMC, metsElement.getOriginalPid(), md5InfosMap.get("MC_IMGGRP").getCreated(), originalFile, photometricInterpretation); } } for (String name : toGenerate.keySet()) { String streamName = toGenerate.get(name); if (streamName != null) { MdSecType mdSec = new MdSecType(); mdSec.setID(name); MdWrap mdWrap = new MdWrap(); mdWrap.setMIMETYPE("text/xml"); mdWrap.setMDTYPE("NISOIMG"); XmlData xmlData = new XmlData(); Node mixNode = null; if ("RAW".equals(streamName)) { if (jHoveOutputRaw != null) { mixNode = jHoveOutputRaw.getMixNode(); if (md5InfosMap.get(streamName) != null) { md5InfosMap.get(streamName).setFormatVersion(jHoveOutputRaw.getFormatVersion()); } } } else if (("MC_IMGGRP".equals(streamName)) && (md5InfosMap.get("MC_IMGGRP") != null)) { if (jHoveOutputMC != null) { mixNode = jHoveOutputMC.getMixNode(); if (md5InfosMap.get(streamName) != null) { md5InfosMap.get(streamName).setFormatVersion(jHoveOutputMC.getFormatVersion()); } if (mixNode != null) { if ((amdSecFileGrpMap.get("MC_IMGGRP") != null) && (amdSecFileGrpMap.get("MC_IMGGRP").getFile().get(0) != null)) { amdSecFileGrpMap.get("MC_IMGGRP").getFile().get(0).getADMID().add(mdSec); } } } } if (mixNode != null) { xmlData.getAny().add(mixNode); } else { throw new MetsExportException(metsElement.getOriginalPid(), "Unable to generate image metadata (MIX) for " + streamName, false, null); } mdWrap.setXmlData(xmlData); mdSec.setMdWrap(mdWrap); amdSec.getTechMD().add(mdSec); } } if (rawFile != null) { outputFileNames.remove("RAW"); rawFile.delete(); } if (outputFileNames.get("ALTOGRP") != null) { File altoFile = new File(outputFileNames.get("ALTOGRP")); if (altoFile.exists()) { Schema altoSchema; try { altoSchema = AltoDatastream.getSchema(); } catch (SAXException e) { throw new MetsExportException("Unable to get ALTO schema", false); } try { altoSchema.newValidator().validate(new StreamSource(altoFile)); } catch (Exception exSax) { throw new MetsExportException(metsElement.getOriginalPid(), "Invalid ALTO", false, exSax); } md5InfosMap.get("ALTOGRP").setFormatVersion("2.0"); } } addPremisToAmdSec(amdSec, md5InfosMap, metsElement, amdSecFileGrpMap); mapType.setDiv(divType); saveAmdSec(metsElement, amdSecMets, fileNames, mimeTypes); FileType fileType = prepareFileType(seq, "TECHMDGRP", fileNames, mimeTypes, metsElement.getMetsContext(), outputFileNames, md5InfosMap); this.fileGrpMap.get("TECHMDGRP").getFile().add(fileType); Fptr fptr = new Fptr(); fptr.setFILEID(fileType); pageDiv.getFptr().add(fptr); } }
From source file:it.isislab.dmason.util.SystemManagement.Master.thrower.DMasonMaster.java
private static boolean validateXML(File configFile, InputStream xsdFile) throws IOException { Source schemaFile = new StreamSource(xsdFile); Source xmlFile = new StreamSource(configFile); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try {/* w w w . j a v a 2s . c o m*/ Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); validator.validate(xmlFile); return true; //System.out.println(xmlFile.getSystemId() + " is valid"); } catch (SAXException e) { //System.out.println(xmlFile.getSystemId() + " is NOT valid"); //System.out.println("Reason: " + e.getLocalizedMessage()); return false; } }
From source file:de.escidoc.core.test.EscidocTestBase.java
/** * Assert the provided XML data is valid against the provided schema. * //from ww w.ja v a 2 s. c o m * @param xmlData * The xml data to be asserted. * @param schema * The schema. * @throws Exception * If anything fails. */ public static void assertXmlValid(final String xmlData, final Schema schema) throws Exception { assertNotNull("No Xml data. ", xmlData); try { Validator validator = schema.newValidator(); InputStream in = new ByteArrayInputStream(xmlData.getBytes(DEFAULT_CHARSET)); validator.validate(new SAXSource(new InputSource(in))); } catch (final Exception e) { final StringBuffer errorMsg = new StringBuffer("XML invalid. "); errorMsg.append(e.getMessage()); if (LOGGER.isDebugEnabled()) { errorMsg.append(xmlData); errorMsg.append("============ End of invalid xml ============\n"); } fail(errorMsg.toString()); } assertXmlPrefixNotDeclared(xmlData); }
From source file:i5.las2peer.services.mobsos.surveys.SurveyService.java
/** * Initialize XML parser and validator for questionnaire forms and answers * //from w ww . j a va 2s.c o m * @throws SAXException * @throws ParserConfigurationException */ private void initXMLInfrastructure() throws SAXException, ParserConfigurationException { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new File(questionnaireSchemaPath)); validator = schema.newValidator(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setSchema(schema); dbf.setNamespaceAware(true); dbf.setValidating(false); parser = dbf.newDocumentBuilder(); }