List of usage examples for javax.xml.parsers DocumentBuilderFactory setSchema
public void setSchema(Schema schema)
From source file:org.apache.nifi.fingerprint.FingerprintFactory.java
public FingerprintFactory(final StringEncryptor encryptor) { this.encryptor = encryptor; final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema; try {//from w w w . jav a 2 s . c o m schema = schemaFactory.newSchema(FingerprintFactory.class.getResource(FLOW_CONFIG_XSD)); } catch (final Exception e) { throw new RuntimeException("Failed to parse schema for file flow configuration.", e); } try { documentBuilderFactory.setSchema(schema); flowConfigDocBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (final Exception e) { throw new RuntimeException("Failed to create document builder for flow configuration.", e); } }
From source file:org.apache.nifi.fingerprint.FingerprintFactoryTest.java
private DocumentBuilder getValidatingDocumentBuilder() { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema; try {/*from w w w. ja va 2 s .co m*/ schema = schemaFactory.newSchema(FingerprintFactory.class.getResource(FLOW_CONFIG_XSD)); } catch (final Exception e) { throw new RuntimeException("Failed to parse schema for file flow configuration.", e); } try { documentBuilderFactory.setSchema(schema); DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder(); docBuilder.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException e) throws SAXException { throw e; } @Override public void error(SAXParseException e) throws SAXException { throw e; } @Override public void fatalError(SAXParseException e) throws SAXException { throw e; } }); return docBuilder; } catch (final Exception e) { throw new RuntimeException("Failed to create document builder for flow configuration.", e); } }
From source file:org.forgerock.maven.plugins.LinkTester.java
@Override() public void execute() throws MojoExecutionException, MojoFailureException { if (outputFile != null) { if (!outputFile.isAbsolute()) { outputFile = new File(project.getBasedir(), outputFile.getPath()); }/*from w w w. ja v a 2s.c o m*/ if (outputFile.exists()) { debug("Deleting existing outputFile: " + outputFile); outputFile.delete(); } try { outputFile.createNewFile(); fileWriter = new FileWriter(outputFile); } catch (IOException ioe) { error("Error while creating output file", ioe); } } initializeSkipUrlPatterns(); //Initialize XML parsers and XPath expressions DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setExpandEntityReferences(false); dbf.setXIncludeAware(xIncludeAware); if (validating) { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { Schema schema = sf.newSchema(new URL(DOCBOOK_XSD)); dbf.setSchema(schema); } catch (MalformedURLException murle) { error("Invalid URL provided as schema source", murle); } catch (SAXException saxe) { error("Parsing error occurred while constructing schema for validation", saxe); } } DocumentBuilder db; try { db = dbf.newDocumentBuilder(); db.setErrorHandler(new LoggingErrorHandler(this)); } catch (ParserConfigurationException pce) { throw new MojoExecutionException("Unable to create new DocumentBuilder", pce); } XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); xpath.setNamespaceContext(new XmlNamespaceContext()); XPathExpression expr; try { expr = xpath.compile("//@xml:id"); } catch (XPathExpressionException xpee) { throw new MojoExecutionException("Unable to compile Xpath expression", xpee); } if (docSources != null) { for (DocSource docSource : docSources) { processDocSource(docSource, db, expr); } } try { if (!skipOlinks) { //we can only check olinks after going through all the documents, otherwise we would see false //positives, because of the not yet processed files for (Map.Entry<String, Collection<String>> entry : (Set<Map.Entry<String, Collection<String>>>) olinks .entrySet()) { for (String val : entry.getValue()) { checkOlink(entry.getKey(), val); } } } if (!failedUrls.isEmpty()) { error("The following files had invalid URLs:\n" + failedUrls.toString()); } if (!timedOutUrls.isEmpty()) { warn("The following files had unavailable URLs (connection or read timed out):\n" + timedOutUrls.toString()); } if (failedUrls.isEmpty() && timedOutUrls.isEmpty() && !failure) { //there are no failed URLs and the parser didn't encounter any errors either info("DocBook links successfully tested, no errors reported."); } } finally { flushReport(); } if (failOnError) { if (failure || !failedUrls.isEmpty()) { throw new MojoFailureException("One or more error occurred during plugin execution"); } } }
From source file:org.fosstrak.epcis.repository.capture.CaptureOperationsModule.java
/** * Parses the input into a DOM. If a schema is given, the input is also * validated against this schema. The schema may be null. *///from www. j a v a 2 s . c om private Document parseInput(InputStream in, Schema schema) throws InternalBusinessException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); factory.setSchema(schema); try { DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException e) throws SAXException { LOG.warn("warning while parsing XML input: " + e.getMessage()); } public void fatalError(SAXParseException e) throws SAXException { LOG.error("non-recovarable error while parsing XML input: " + e.getMessage()); throw e; } public void error(SAXParseException e) throws SAXException { LOG.error("error while parsing XML input: " + e.getMessage()); throw e; } }); Document document = builder.parse(in); LOG.debug("payload successfully parsed as XML document"); if (LOG.isDebugEnabled()) { logDocument(document); } return document; } catch (ParserConfigurationException e) { throw new InternalBusinessException("unable to configure document builder to parse XML input", e); } }
From source file:org.infoscoop.api.rest.v1.controller.admin.TabLayoutsController.java
/** * validatation and parse XMLString for tabLayouts. * @param xml/*from www . ja v a2s. com*/ * @return */ private Document parseTabLayoutsXML(String xml) { try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL path = Thread.currentThread().getContextClassLoader().getResource("tabLayouts.xsd"); File f = new File(path.toURI()); Schema schema = factory.newSchema(f); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setSchema(schema); dbf.setNamespaceAware(true); DocumentBuilder parser = dbf.newDocumentBuilder(); Document doc = parser.parse(new InputSource(new StringReader(xml))); Validator validator = schema.newValidator(); validator.validate(new DOMSource(doc)); return doc; } catch (SAXException e) { // instance document is invalid throw new RuntimeException(e); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.jmingo.parser.xml.dom.DocumentBuilderFactoryCreator.java
/** * Creates DocumentBuilderFactory./* www . jav a 2 s. co m*/ * * @param parserConfiguration {@link ParserConfiguration} * @return DocumentBuilderFactory a factory API that enables applications to obtain a * parser that produces DOM object trees from XML documents * @throws ParserConfigurationException {@link ParserConfigurationException} */ public static DocumentBuilderFactory createDocumentBuilderFactory(ParserConfiguration parserConfiguration) throws ParserConfigurationException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setValidating(parserConfiguration.isValidate()); documentBuilderFactory.setNamespaceAware(parserConfiguration.isNamespaceAware()); documentBuilderFactory.setFeature(ParserConstants.DYNAMIC_VALIDATION, true); List<Source> sourceList = createSchemaSources(parserConfiguration.getXsdSchemaPaths()); if (CollectionUtils.isNotEmpty(sourceList)) { documentBuilderFactory.setSchema(createSchema(sourceList)); } return documentBuilderFactory; }
From source file:org.mifos.framework.components.mifosmenu.MenuParser.java
/** * Method to parse xml and return crude menu * * @return array of crude Menu objects// w w w . j a va2s. com */ public static Menu[] parse() throws SystemException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); SchemaFactory schfactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schfactory.setErrorHandler(null); Schema schema = schfactory.newSchema( new StreamSource(MifosResourceUtil.getClassPathResourceAsStream(FilePaths.MENUSCHEMA))); factory.setNamespaceAware(false); factory.setValidating(false); factory.setSchema(schema); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(MifosResourceUtil.getClassPathResourceAsStream(FilePaths.MENUPATH)); NodeList tabNodeList = document.getElementsByTagName(MenuConstants.TOPMENUTAB); Menu leftMenus[] = new Menu[tabNodeList.getLength()]; for (int i = 0; i < tabNodeList.getLength(); i++) { leftMenus[i] = new Menu(); leftMenus[i].setTopMenuTabName(((Element) tabNodeList.item(i)).getAttribute(MenuConstants.NAME)); leftMenus[i].setMenuGroups(createMenuGroup(tabNodeList.item(i))); String menuHeading = ((Element) tabNodeList.item(i)) .getElementsByTagName(MenuConstants.LEFTMENULABEL).item(0).getFirstChild().getTextContent() .trim(); leftMenus[i].setMenuHeading(menuHeading); } return leftMenus; } catch (SAXParseException spe) { throw new MenuParseException(spe); } catch (SAXException sxe) { throw new MenuParseException(sxe); } catch (ParserConfigurationException pce) { throw new MenuParseException(pce); } catch (IOException ioe) { throw new MenuParseException(ioe); } }
From source file:org.sejda.core.context.XmlConfigurationStrategy.java
private void initializeSchemaValidation(DocumentBuilderFactory factory) throws SAXException { if (Boolean.getBoolean(Sejda.PERFORM_SCHEMA_VALIDATION_PROPERTY_NAME)) { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource( Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_SEJDA_CONFIG)) })); factory.setNamespaceAware(true); }/* w ww. j a v a 2 s.co m*/ }
From source file:org.terracotta.config.TCConfigurationParser.java
@SuppressWarnings("unchecked") private static TcConfiguration parseStream(InputStream in, ErrorHandler eh, String source, ClassLoader loader) throws IOException, SAXException { Collection<Source> schemaSources = new ArrayList<>(); for (ServiceConfigParser parser : loadConfigurationParserClasses(loader)) { schemaSources.add(parser.getXmlSchema()); serviceParsers.put(parser.getNamespace(), parser); }/* w w w . j a v a 2s. c om*/ schemaSources.add(new StreamSource(TERRACOTTA_XML_SCHEMA.openStream())); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); factory.setSchema(XSD_SCHEMA_FACTORY.newSchema(schemaSources.toArray(new Source[schemaSources.size()]))); final DocumentBuilder domBuilder; try { domBuilder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new AssertionError(e); } domBuilder.setErrorHandler(eh); final Element config = domBuilder.parse(in).getDocumentElement(); try { JAXBContext jc = JAXBContext.newInstance("org.terracotta.config", TCConfigurationParser.class.getClassLoader()); Unmarshaller u = jc.createUnmarshaller(); TcConfig tcConfig = u.unmarshal(config, TcConfig.class).getValue(); if (tcConfig.getServers() == null) { Servers servers = new Servers(); tcConfig.setServers(servers); } if (tcConfig.getServers().getServer().isEmpty()) { tcConfig.getServers().getServer().add(new Server()); } DefaultSubstitutor.applyDefaults(tcConfig); applyPlatformDefaults(tcConfig, source); Map<String, Map<String, ServiceOverride>> serviceOverrides = new HashMap<>(); for (Server server : tcConfig.getServers().getServer()) { if (server.getServiceOverrides() != null && server.getServiceOverrides().getServiceOverride() != null) { for (ServiceOverride serviceOverride : server.getServiceOverrides().getServiceOverride()) { String id = ((Service) serviceOverride.getOverrides()).getId(); if (serviceOverrides.get(id) == null) { serviceOverrides.put(id, new HashMap<>()); } serviceOverrides.get(id).put(server.getName(), serviceOverride); } } } Map<String, List<ServiceProviderConfiguration>> serviceConfigurations = new HashMap<>(); if (tcConfig.getServices() != null && tcConfig.getServices().getService() != null) { //now parse the service configuration. for (Service service : tcConfig.getServices().getService()) { Element element = service.getAny(); if (element != null) { URI namespace = URI.create(element.getNamespaceURI()); ServiceConfigParser parser = serviceParsers.get(namespace); if (parser == null) { throw new TCConfigurationSetupException("Can't find parser for service " + namespace); } ServiceProviderConfiguration serviceProviderConfiguration = parser.parse(element, source); for (Server server : tcConfig.getServers().getServer()) { if (serviceConfigurations.get(server.getName()) == null) { serviceConfigurations.put(server.getName(), new ArrayList<>()); } if (serviceOverrides.get(service.getId()) != null && serviceOverrides.get(service.getId()).containsKey(server.getName())) { Element overrideElement = serviceOverrides.get(service.getId()) .get(server.getName()).getAny(); if (overrideElement != null) { serviceConfigurations.get(server.getName()) .add(parser.parse(overrideElement, source)); } } else { serviceConfigurations.get(server.getName()).add(serviceProviderConfiguration); } } } } } return new TcConfiguration(tcConfig, source, serviceConfigurations); } catch (JAXBException e) { throw new TCConfigurationSetupException(e); } }