List of usage examples for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI
String W3C_XML_SCHEMA_NS_URI
To view the source code for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI.
Click Source Link
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 om 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.amalto.core.storage.hibernate.FullTextQueryHandler.java
private StorageResults createResults(ScrollableResults scrollableResults) { CloseableIterator<DataRecord> iterator; if (selectedFields.isEmpty()) { iterator = new ScrollableIterator(mappings, storageClassLoader, scrollableResults, callbacks); } else {//w w w .j a v a 2s. c om iterator = new ScrollableIterator(mappings, storageClassLoader, scrollableResults, callbacks) { @Override public DataRecord next() { DataRecord next = super.next(); ComplexTypeMetadata explicitProjectionType = new ComplexTypeMetadataImpl(StringUtils.EMPTY, Storage.PROJECTION_TYPE, false); DataRecord nextRecord = new DataRecord(explicitProjectionType, UnsupportedDataRecordMetadata.INSTANCE); for (TypedExpression selectedField : selectedFields) { if (selectedField instanceof Field) { FieldMetadata field = ((Field) selectedField).getFieldMetadata(); TypeMapping mapping = mappings.getMappingFromDatabase(field.getContainingType()); if (mapping != null && mapping.getUser(field) != null) { field = mapping.getUser(field); } explicitProjectionType.addField(field); if (field instanceof ReferenceFieldMetadata) { nextRecord.set(field, getReferencedId(next, (ReferenceFieldMetadata) field)); } else { nextRecord.set(field, next.get(field)); } } else if (selectedField instanceof Alias) { SimpleTypeMetadata fieldType = new SimpleTypeMetadata( XMLConstants.W3C_XML_SCHEMA_NS_URI, selectedField.getTypeName()); Alias alias = (Alias) selectedField; SimpleTypeFieldMetadata newField = new SimpleTypeFieldMetadata(explicitProjectionType, false, false, false, alias.getAliasName(), fieldType, Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(), StringUtils.EMPTY); explicitProjectionType.addField(newField); TypedExpression typedExpression = alias.getTypedExpression(); if (typedExpression instanceof StringConstant) { nextRecord.set(newField, ((StringConstant) typedExpression).getValue()); } else if (typedExpression instanceof Field) { nextRecord.set(newField, next.get(((Field) typedExpression).getFieldMetadata())); } else if (typedExpression instanceof Type) { FieldMetadata fieldMetadata = ((Type) typedExpression).getField() .getFieldMetadata(); nextRecord.set(newField, ((DataRecord) next.get(fieldMetadata.getName())).getType().getName()); } else if (typedExpression instanceof MetadataField) { nextRecord.set(newField, ((MetadataField) typedExpression).getReader().readValue(next)); } else { throw new IllegalArgumentException( "Aliased expression '" + typedExpression + "' is not supported."); } } else if (selectedField instanceof MetadataField) { SimpleTypeMetadata fieldType = new SimpleTypeMetadata( XMLConstants.W3C_XML_SCHEMA_NS_URI, selectedField.getTypeName()); SimpleTypeFieldMetadata newField = new SimpleTypeFieldMetadata(explicitProjectionType, false, false, false, ((MetadataField) selectedField).getFieldName(), fieldType, Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(), StringUtils.EMPTY); explicitProjectionType.addField(newField); nextRecord.set(newField, ((MetadataField) selectedField).getReader().readValue(next)); } } explicitProjectionType.freeze(); return nextRecord; } }; } return new FullTextStorageResults(pageSize, query.getResultSize(), iterator); }
From source file:hydrograph.ui.propertywindow.widgets.customwidgets.schema.GridRowLoader.java
private boolean validateXML(InputStream xml, InputStream xsd) { try {/*from w w w . j a va 2 s . c om*/ SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); javax.xml.validation.Schema schema = factory.newSchema(new StreamSource(xsd)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xml)); return true; } catch (SAXException | IOException ex) { MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error", Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage()); logger.error(Messages.IMPORT_XML_FORMAT_ERROR); return false; } }
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;/* w w w .j av a2 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:com.evolveum.midpoint.prism.parser.PrismBeanInspector.java
private QName findFieldTypeNameUncached(Field field, Class fieldType, String schemaNamespace) { QName propTypeQname = null;/*from w w w.j a va2s.c o m*/ XmlSchemaType xmlSchemaType = null; if (field != null) { xmlSchemaType = field.getAnnotation(XmlSchemaType.class); } if (xmlSchemaType != null) { String propTypeLocalPart = xmlSchemaType.name(); if (propTypeLocalPart != null) { String propTypeNamespace = xmlSchemaType.namespace(); if (propTypeNamespace == null) { propTypeNamespace = XMLConstants.W3C_XML_SCHEMA_NS_URI; } propTypeQname = new QName(propTypeNamespace, propTypeLocalPart); } } if (propTypeQname == null) { propTypeQname = XsdTypeMapper.getJavaToXsdMapping(fieldType); } if (propTypeQname == null) { XmlType xmlType = (XmlType) fieldType.getAnnotation(XmlType.class); if (xmlType != null) { String propTypeLocalPart = xmlType.name(); if (propTypeLocalPart != null) { String propTypeNamespace = xmlType.namespace(); if (propTypeNamespace == null || propTypeNamespace.equals(PrismBeanConverter.DEFAULT_PLACEHOLDER)) { if (prismContext != null) { // hopefully this is always the case! PrismSchema schema = prismContext.getSchemaRegistry() .findSchemaByCompileTimeClass(fieldType); if (schema != null && schema.getNamespace() != null) { propTypeNamespace = schema.getNamespace(); } } if (propTypeNamespace == null) { // schemaNamespace is only a poor indicator of required namespace (consider e.g. having c:UserType in apit:ObjectListType) // so we use it only if we couldn't find anything else propTypeNamespace = schemaNamespace; } } propTypeQname = new QName(propTypeNamespace, propTypeLocalPart); } } } return propTypeQname; }
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 a v a 2 s . c om*/ * * @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:com.amalto.core.storage.hibernate.HibernateStorage.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override/* ww w . java2s . c o m*/ public synchronized void prepare(MetadataRepository repository, Set<Expression> optimizedExpressions, boolean force, boolean dropExistingData) { if (!force && isPrepared) { return; // No op operation } if (isPrepared) { close(); internalInit(); } if (dataSource == null) { throw new IllegalArgumentException("Datasource is not set."); //$NON-NLS-1$ } // No support for data models including inheritance AND for g* XSD simple types AND fields that start with // X_TALEND_ try { repository.accept(METADATA_CHECKER); userMetadataRepository = repository; } catch (Exception e) { throw new RuntimeException("Exception occurred during unsupported features check.", e); //$NON-NLS-1$ } // Loads additional types for staging area. if (storageType == StorageType.STAGING) { userMetadataRepository = repository.copy(); // See TMDM-6938: prevents staging types to appear in master // storage. userMetadataRepository .load(MetadataRepositoryAdmin.class.getResourceAsStream("stagingInternalTypes.xsd")); //$NON-NLS-1$ } // Create class loader for storage's dynamically created classes. ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); Class<? extends StorageClassLoader> clazz; try { try { clazz = (Class<? extends StorageClassLoader>) Class.forName(ALTERNATE_CLASS_LOADER); } catch (ClassNotFoundException e) { clazz = (Class<? extends StorageClassLoader>) Class.forName(CLASS_LOADER); } Constructor<? extends StorageClassLoader> constructor = clazz.getConstructor(ClassLoader.class, String.class, StorageType.class); storageClassLoader = constructor.newInstance(contextClassLoader, storageName, storageType); storageClassLoader.setDataSourceConfiguration(dataSource); storageClassLoader.generateHibernateConfig(); // Checks if configuration can be generated. } catch (Exception e) { throw new RuntimeException("Could not create storage class loader", e); //$NON-NLS-1$ } if (dropExistingData) { LOGGER.info("Cleaning existing database content."); //$NON-NLS-1$ StorageCleaner cleaner = new JDBCStorageCleaner(new FullTextIndexCleaner()); cleaner.clean(this); } else { LOGGER.info("*NOT* cleaning existing database content."); //$NON-NLS-1$ } if (autoPrepare) { LOGGER.info("Preparing database before schema generation."); //$NON-NLS-1$ StorageInitializer initializer = new JDBCStorageInitializer(); if (initializer.supportInitialization(this)) { if (!initializer.isInitialized(this)) { initializer.initialize(this); } else { LOGGER.info("Database is already prepared."); //$NON-NLS-1$ } } else { LOGGER.info("Datasource is not configured for automatic initialization."); //$NON-NLS-1$ } } else { LOGGER.info("*NOT* preparing database before schema generation."); //$NON-NLS-1$ } try { Thread.currentThread().setContextClassLoader(storageClassLoader); // Mapping of data model types to RDBMS (i.e. 'flatten' representation of types). MetadataRepository internalRepository; try { InternalRepository typeEnhancer = getTypeEnhancer(); internalRepository = userMetadataRepository.accept(typeEnhancer); mappingRepository = typeEnhancer.getMappings(); } catch (Exception e) { throw new RuntimeException("Exception occurred during type mapping creation.", e); //$NON-NLS-1$ } // Set fields to be indexed in database. Set<FieldMetadata> databaseIndexedFields = new HashSet<FieldMetadata>(); switch (storageType) { case MASTER: // Adds indexes on user defined fields for (Expression optimizedExpression : optimizedExpressions) { Collection<FieldMetadata> indexedFields = RecommendedIndexes.get(optimizedExpression); for (FieldMetadata indexedField : indexedFields) { // TMDM-5896: Don't index Composite Key fields if (indexedField instanceof CompoundFieldMetadata) { continue; } // TMDM-5311: Don't index TEXT fields TypeMetadata indexedFieldType = indexedField.getType(); if (!isIndexable(indexedFieldType)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Ignore index on field '" + indexedField.getName() //$NON-NLS-1$ + "' because value is stored in TEXT."); //$NON-NLS-1$ } continue; } // Go up the containment tree in case containing type is anonymous. ComplexTypeMetadata containingType = indexedField.getContainingType().getEntity(); TypeMapping mapping = mappingRepository.getMappingFromUser(containingType); FieldMetadata databaseField = mapping.getDatabase(indexedField); if (databaseField == null) { LOGGER.error("Could not index field '" + indexedField + "' (" + indexedField.getPath() //$NON-NLS-1$ //$NON-NLS-2$ + "), ignoring index."); //$NON-NLS-1$ continue; } else if (!isIndexable(databaseField.getType())) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Ignore index on field '" + indexedField.getName() //$NON-NLS-1$ + "' because value (in database mapping) is stored in TEXT."); //$NON-NLS-1$ } continue; // Don't take into indexed fields long text fields } // Database specific behaviors switch (dataSource.getDialectName()) { case SQL_SERVER: // TMDM-8144: Don't index field name on SQL Server when size > 900 String maxLengthStr = indexedField.getType() .<String>getData(MetadataRepository.DATA_MAX_LENGTH); if (maxLengthStr == null) { // go up the type inheritance tree to find max length annotation TypeMetadata type = indexedField.getType(); while (!XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(type.getNamespace()) && !type.getSuperTypes().isEmpty()) { type = type.getSuperTypes().iterator().next(); maxLengthStr = type.<String>getData(MetadataRepository.DATA_MAX_LENGTH); if (maxLengthStr != null) { break; } } } if (maxLengthStr != null) { Integer maxLength = Integer.parseInt(maxLengthStr); if (maxLength > 900) { LOGGER.warn("Skip index on field '" + indexedField.getPath() //$NON-NLS-1$ + "' (too long value)."); //$NON-NLS-1$ continue; } } break; case H2: case MYSQL: case POSTGRES: case DB2: case ORACLE_10G: default: // Nothing to do for these databases break; } databaseIndexedFields.add(databaseField); if (!databaseField.getContainingType().isInstantiable()) { Collection<ComplexTypeMetadata> roots = RecommendedIndexes .getRoots(optimizedExpression); for (ComplexTypeMetadata root : roots) { List<FieldMetadata> path = StorageMetadataUtils.path( mappingRepository.getMappingFromUser(root).getDatabase(), databaseField); if (path.size() > 1) { databaseIndexedFields.addAll(path.subList(0, path.size() - 1)); } else { LOGGER.warn("Failed to properly index field '" + databaseField + "'."); //$NON-NLS-1$ //$NON-NLS-2$ } } } } } break; case STAGING: if (!optimizedExpressions.isEmpty()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Ignoring " + optimizedExpressions.size() //$NON-NLS-1$ + " to optimize (disabled on staging area)."); //$NON-NLS-1$ } } // Adds "staging status" / "staging block key" / "staging task id" as indexed fields for (TypeMapping typeMapping : mappingRepository.getAllTypeMappings()) { ComplexTypeMetadata database = typeMapping.getDatabase(); if (database.hasField(METADATA_STAGING_STATUS)) { databaseIndexedFields.add(database.getField(METADATA_STAGING_STATUS)); } if (database.hasField(METADATA_STAGING_BLOCK_KEY)) { databaseIndexedFields.add(database.getField(METADATA_STAGING_BLOCK_KEY)); } if (database.hasField(METADATA_TASK_ID)) { databaseIndexedFields.add(database.getField(METADATA_TASK_ID)); } } break; case SYSTEM: // Nothing to index on SYSTEM break; } // Don't add FK in indexes if using H2 if (dataSource.getDialectName() == RDBMSDataSource.DataSourceDialect.H2) { Iterator<FieldMetadata> indexedFields = databaseIndexedFields.iterator(); while (indexedFields.hasNext()) { FieldMetadata field = indexedFields.next(); if (field instanceof ReferenceFieldMetadata || field.isKey()) { indexedFields.remove(); // H2 doesn't like indexes on PKs or FKs. } } } switch (dataSource.getDialectName()) { case ORACLE_10G: tableResolver = new OracleStorageTableResolver(databaseIndexedFields, dataSource.getNameMaxLength()); break; default: tableResolver = new StorageTableResolver(databaseIndexedFields, dataSource.getNameMaxLength()); } storageClassLoader.setTableResolver(tableResolver); // Master, Staging and System share same class creator. switch (storageType) { case MASTER: case STAGING: case SYSTEM: hibernateClassCreator = new ClassCreator(storageClassLoader); break; } // Create Hibernate classes (after some modifications to the types). try { internalRepository.accept(hibernateClassCreator); } catch (Exception e) { throw new RuntimeException("Exception occurred during dynamic classes creation.", e); //$NON-NLS-1$ } // Last step: configuration of Hibernate try { // Hibernate needs to have dynamic classes in context class loader during configuration. InputStream ehCacheConfig = storageClassLoader .getResourceAsStream(StorageClassLoader.EHCACHE_XML_CONFIG); if (ehCacheConfig != null) { CacheManager.create(ehCacheConfig); } configuration.configure(StorageClassLoader.HIBERNATE_CONFIG); batchSize = Integer.parseInt(configuration.getProperty(Environment.STATEMENT_BATCH_SIZE)); // Sets default schema for Oracle Properties properties = configuration.getProperties(); if (dataSource.getDialectName() == RDBMSDataSource.DataSourceDialect.ORACLE_10G) { properties.setProperty(Environment.DEFAULT_SCHEMA, dataSource.getUserName()); } // Logs DDL *before* initialization in case initialization fails (useful for debugging). if (LOGGER.isTraceEnabled()) { traceDDL(); } // Customize schema generation according to datasource content. RDBMSDataSource.SchemaGeneration schemaGeneration = dataSource.getSchemaGeneration(); List exceptions = Collections.emptyList(); switch (schemaGeneration) { case CREATE: SchemaExport schemaExport = new SchemaExport(configuration); schemaExport.create(false, true); // Exception may happen during recreation (hibernate may perform statements on tables that does // not exist): these exceptions are supposed to be harmless (but log them to DEBUG just in case). if (LOGGER.isDebugEnabled()) { LOGGER.debug("Exception(s) occurred during schema creation:"); //$NON-NLS-1$ for (Object exceptionObject : schemaExport.getExceptions()) { LOGGER.debug(((Exception) exceptionObject).getMessage()); } } break; case VALIDATE: SchemaValidator schemaValidator = new SchemaValidator(configuration); schemaValidator.validate(); // This is supposed to throw exception on validation issue. break; case UPDATE: SchemaUpdate schemaUpdate = new SchemaUpdate(configuration); schemaUpdate.execute(false, true); exceptions = schemaUpdate.getExceptions(); break; } // Throw an exception if schema update met issue(s). if (!exceptions.isEmpty()) { StringBuilder sb = new StringBuilder(); sb.append("Could not prepare database schema: "); //$NON-NLS-1$ Iterator iterator = exceptions.iterator(); while (iterator.hasNext()) { Exception exception = (Exception) iterator.next(); if (exception instanceof SQLException) { SQLException currentSQLException = (SQLException) exception; while (currentSQLException != null) { sb.append(currentSQLException.getMessage()); sb.append('\n'); currentSQLException = currentSQLException.getNextException(); } } else if (exception != null) { sb.append(exception.getMessage()); } if (iterator.hasNext()) { sb.append('\n'); } } throw new IllegalStateException(sb.toString()); } // Initialize Hibernate Environment.verifyProperties(properties); ConfigurationHelper.resolvePlaceHolders(properties); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties) .build(); factory = configuration.buildSessionFactory(serviceRegistry); MDMTransactionSessionContext.declareStorage(this, factory); } catch (Exception e) { throw new RuntimeException("Exception occurred during Hibernate initialization.", e); //$NON-NLS-1$ } // All set: set prepared flag to true. isPrepared = true; LOGGER.info("Storage '" + storageName + "' (" + storageType + ") is ready."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } catch (Throwable t) { try { // This prevent PermGen OOME in case of multiple failures to start. close(); } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Error occurred during clean up following failed prepare", e); //$NON-NLS-1$ } } throw new RuntimeException("Could not prepare '" + storageName + "'.", t); //$NON-NLS-1$ //$NON-NLS-2$ } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } }
From source file:AndroidUninstallStock.java
public static DocumentBuilderFactory getXmlDocFactory() throws SAXException { DocumentBuilderFactory xmlfactory = DocumentBuilderFactory.newInstance(); xmlfactory.setIgnoringComments(true); xmlfactory.setCoalescing(true);//www . j ava 2 s . com // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4867706 xmlfactory.setIgnoringElementContentWhitespace(true); xmlfactory.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(AndroidUninstallStock.class.getResource("AndroidListSoft.xsd"))); xmlfactory.setValidating(false); // not DTD return xmlfactory; }
From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java
/** * * Validates given document agains an XSD schema * * @param document//w ww .j av a 2 s. c o m * @param xsd * @return */ public static List<String> validateAgainstXSD(Document document, InputStream xsd) throws Exception { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver(MetsLSResolver.getInstance()); Schema schema = factory.newSchema(new StreamSource(xsd)); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource domSource = new DOMSource(document); StreamResult sResult = new StreamResult(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); sResult.setOutputStream(bos); transformer.transform(domSource, sResult); InputStream is = new ByteArrayInputStream(bos.toByteArray()); DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); dbfactory.setValidating(false); dbfactory.setNamespaceAware(true); dbfactory.setSchema(schema); DocumentBuilder documentBuilder = dbfactory.newDocumentBuilder(); ValidationErrorHandler errorHandler = new ValidationErrorHandler(); documentBuilder.setErrorHandler(errorHandler); documentBuilder.parse(is); return errorHandler.getValidationErrors(); }
From source file:nl.armatiek.xslweb.configuration.WebApp.java
public Schema trySchemaCache(Collection<String> schemaPaths, ErrorListener errorListener) throws Exception { String key = StringUtils.join(schemaPaths, ";"); Schema schema = schemaCache.get(key); if (schema == null) { logger.info("Compiling and caching schema(s) \"" + key + "\" ..."); try {//from w ww.j a v a 2s . c o m ArrayList<Source> schemaSources = new ArrayList<Source>(); for (String path : schemaPaths) { File file = new File(path); if (!file.isFile()) { throw new FileNotFoundException( "XML Schema file \"" + file.getAbsolutePath() + "\" not found"); } schemaSources.add(new StreamSource(file)); } SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setErrorHandler(new ValidatorErrorHandler("Schema file(s)")); schema = schemaFactory.newSchema(schemaSources.toArray(new Source[schemaSources.size()])); } catch (Exception e) { logger.error("Error compiling schema(s) \"" + key + "\"", e); throw e; } if (!developmentMode) { schemaCache.put(key, schema); } } return schema; }