List of usage examples for javax.xml.parsers DocumentBuilderFactory setIgnoringComments
public void setIgnoringComments(boolean ignoreComments)
From source file:org.rimudb.configuration.AbstractXmlLoader.java
private Document loadXML(InputStream is) throws Exception { // Load document DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);//from ww w. j a v a 2 s.co m factory.setIgnoringElementContentWhitespace(true); factory.setIgnoringComments(true); factory.setValidating(false); // Don't use DTD validation DocumentBuilder docBuilder = factory.newDocumentBuilder(); ErrorHandler eh = new StrictErrorHandler(); docBuilder.setErrorHandler(eh); InputSource inputSource = new InputSource(is); inputSource.setPublicId(RimuDBNamespace.URI); inputSource.setSystemId(RimuDBNamespace.URI); Document document = docBuilder.parse(is); is.close(); // Determine the XML schema version from the XML document without validating Element root = document.getDocumentElement(); setDocumentSchema(lookupSchemaVersion(root)); // Validate the XML document and determine the XML Schema version if (isValidateXML()) { if (getDocumentSchema() != null) { // Validate the document against the schema found in the document SAXParseException saxParseException = validate(document, getDocumentSchema()); if (saxParseException != null) { throw saxParseException; } } else { setDocumentSchema(lookupSchemaByValidation(document)); } } return document; }
From source file:org.sakaiproject.announcement.impl.BaseAnnouncementService.java
/** * Final initialization, once all dependencies are set. *///ww w. ja va 2s .c o m public void init() { try { super.init(); // register a transient notification for announcements NotificationEdit edit = m_notificationService.addTransientNotification(); // set functions edit.setFunction(eventId(SECURE_ADD)); edit.addFunction(eventId(SECURE_UPDATE_OWN)); edit.addFunction(eventId(SECURE_UPDATE_ANY)); // set the filter to any announcement resource (see messageReference()) edit.setResourceFilter(getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_MESSAGE); // set the action edit.setAction(siteEmailNotificationAnnc); // register functions functionManager.registerFunction(eventId(SECURE_READ)); functionManager.registerFunction(eventId(SECURE_ADD)); functionManager.registerFunction(eventId(SECURE_REMOVE_ANY)); functionManager.registerFunction(eventId(SECURE_REMOVE_OWN)); functionManager.registerFunction(eventId(SECURE_UPDATE_ANY)); functionManager.registerFunction(eventId(SECURE_UPDATE_OWN)); functionManager.registerFunction(eventId(SECURE_ALL_GROUPS)); // Sakai v2.4: UI end says hidden, 'under the covers' says draft // Done so import from old sites causes drafts to 'become' hidden in new sites functionManager.registerFunction(eventId(SECURE_READ_DRAFT)); // entity producer registration m_entityManager.registerEntityProducer(this, REFERENCE_ROOT); // create DocumentBuilder for RSS Feed DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(true); // ignore comments factory.setNamespaceAware(true); // namespace aware should be true factory.setValidating(false); // we're not validating docBuilder = factory.newDocumentBuilder(); TransformerFactory tFactory = TransformerFactory.newInstance(); docTransformer = tFactory.newTransformer(); M_log.info("init()"); } catch (Throwable t) { M_log.warn("init(): ", t); } }
From source file:org.shirdrn.tinyframework.core.conf.Context.java
private void loadResource(Properties properties, Object name, boolean quiet) { try {/*www.ja v a 2 s . c om*/ DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); //ignore all comments inside the xml file docBuilderFactory.setIgnoringComments(true); //allow includes in the xml file docBuilderFactory.setNamespaceAware(true); try { docBuilderFactory.setXIncludeAware(true); } catch (UnsupportedOperationException e) { LOG.error("Failed to set setXIncludeAware(true) for parser " + docBuilderFactory + ":" + e, e); } DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); Document doc = null; Element root = null; if (name instanceof URL) { // an URL resource URL url = (URL) name; if (url != null) { if (!quiet) { LOG.info("parsing " + url); } doc = builder.parse(url.toString()); } } else if (name instanceof String) { // a CLASSPATH resource URL url = getResource((String) name); if (url != null) { if (!quiet) { LOG.info("parsing " + url); } doc = builder.parse(url.toString()); } } else if (name instanceof InputStream) { try { doc = builder.parse((InputStream) name); } finally { ((InputStream) name).close(); } } else if (name instanceof Element) { root = (Element) name; } if (doc == null && root == null) { if (quiet) return; throw new RuntimeException(name + " not found"); } if (root == null) { root = doc.getDocumentElement(); } if (!"configuration".equals(root.getTagName())) LOG.fatal("bad conf file: top-level element not <configuration>"); NodeList props = root.getChildNodes(); for (int i = 0; i < props.getLength(); i++) { Node propNode = props.item(i); if (!(propNode instanceof Element)) continue; Element prop = (Element) propNode; if ("configuration".equals(prop.getTagName())) { loadResource(properties, prop, quiet); continue; } if (!"property".equals(prop.getTagName())) LOG.warn("bad conf file: element not <property>"); NodeList fields = prop.getChildNodes(); String attr = null; String value = null; boolean finalParameter = false; for (int j = 0; j < fields.getLength(); j++) { Node fieldNode = fields.item(j); if (!(fieldNode instanceof Element)) continue; Element field = (Element) fieldNode; if ("name".equals(field.getTagName()) && field.hasChildNodes()) attr = ((Text) field.getFirstChild()).getData().trim(); if ("value".equals(field.getTagName()) && field.hasChildNodes()) value = ((Text) field.getFirstChild()).getData(); if ("final".equals(field.getTagName()) && field.hasChildNodes()) finalParameter = "true".equals(((Text) field.getFirstChild()).getData()); } // Ignore this parameter if it has already been marked as 'final' if (attr != null && value != null) { if (!finalParameters.contains(attr)) { properties.setProperty(attr, value); if (finalParameter) finalParameters.add(attr); } else { LOG.warn(name + ":a attempt to override final parameter: " + attr + "; Ignoring."); } } } } catch (IOException e) { LOG.fatal("error parsing conf file: " + e); throw new RuntimeException(e); } catch (DOMException e) { LOG.fatal("error parsing conf file: " + e); throw new RuntimeException(e); } catch (SAXException e) { LOG.fatal("error parsing conf file: " + e); throw new RuntimeException(e); } catch (ParserConfigurationException e) { LOG.fatal("error parsing conf file: " + e); throw new RuntimeException(e); } }
From source file:org.silverpeas.util.xml.transform.XPathTransformer.java
public void transform(XmlConfiguration configuration) { InputStream in = null;//w w w . j a v a 2 s .co m Document doc = null; String xmlFile = configuration.getFileName(); try { console.printMessage(xmlFile); in = new BufferedInputStream(new FileInputStream(xmlFile)); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setValidating(false); docFactory.setIgnoringElementContentWhitespace(false); docFactory.setIgnoringComments(false); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); docBuilder.setEntityResolver(new ClasspathEntityResolver(null)); doc = docBuilder.parse(in); applyTransformation(configuration, doc); } catch (SAXException ex) { Logger.getLogger(XPathTransformer.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(XPathTransformer.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ioex) { Logger.getLogger(XPathTransformer.class.getName()).log(Level.SEVERE, null, ioex); } finally { IOUtils.closeQuietly(in); } if (doc != null) { saveDoc(xmlFile, doc); } }
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); }/*from ww w . j av a 2s. c o m*/ 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); } }
From source file:org.topazproject.mulgara.itql.XmlHelper.java
/** * Helper to parse an XML string into a DOM. * * @param xml the xml string//from w w w .j av a 2 s . c o m * @return the document * @throws AnswerException if an error occured parsing the xml */ public static Document parseXml(String xml) throws AnswerException { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setIgnoringComments(true); builderFactory.setCoalescing(true); DocumentBuilder builder; try { builder = builderFactory.newDocumentBuilder(); } catch (ParserConfigurationException pce) { throw new RuntimeException(pce); // can this happen? } try { return builder.parse(new InputSource(new StringReader(xml))); } catch (IOException ioe) { throw new Error(ioe); // can't happen } catch (SAXException se) { throw new AnswerException("Unexpected response: '" + xml + "'", se); } }
From source file:org.topazproject.mulgara.resolver.CacheInvalidator.java
/** * Create a new cache-invalidator instance. * /* w w w. j a va 2 s . c om*/ * @param config the configuration to use * @param base the prefix under which the current <var>config</var> was retrieved * @param sf the session-factory we belong to * @param dbURI the uri of our database * @throws Exception */ public CacheInvalidator(Configuration config, String base, SessionFactory sf, URI dbURI) throws Exception { super(0, getInvIval(config), "CacheInvalidator-Worker", false, logger); xaResource = new CIXAResource(); config = config.subset("cacheInvalidator"); base += ".cacheInvalidator"; // parse the rules file String rulesLoc = config.getString("rulesFile", null); if (rulesLoc == null) throw new IOException("Missing configuration entry '" + base + ".rulesFile"); URL loc = findResOrURL(rulesLoc); if (loc == null) throw new IOException("Rules-file '" + rulesLoc + "' not found"); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setIgnoringComments(true); builderFactory.setCoalescing(true); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Element rules = builder.parse(new InputSource(loc.toString())).getDocumentElement(); this.aliases = parseAliases(rules, dbURI); this.rules = parseRules(rules, aliases); // set up the Ehcache disableJULInfoMessages(); String ehcConfigLoc = config.getString("ehcacheConfig", null); boolean useSingleton = config.getBoolean("useSharedCacheManager", false); if (ehcConfigLoc != null) { loc = findResOrURL(ehcConfigLoc); if (loc == null) throw new IOException("Ehcache config file '" + ehcConfigLoc + "' not found"); cacheManager = useSingleton ? CacheManager.create(loc) : new CacheManager(loc); } else { cacheManager = useSingleton ? CacheManager.create() : new CacheManager(); } String qcName = config.getString("queryCache", DEF_QC_NAME); queryCache = cacheManager.getEhcache(qcName); if (queryCache != null) logger.info("Using cache '" + qcName + "' for the query caching"); else logger.info("No cache named '" + qcName + "' found - disabling query caching"); // delay session creation because at this point we're already in a session-creation call sessFactory = sf; // we're ready worker.start(); }
From source file:org.voyanttools.trombone.input.expand.XmlExpander.java
public List<StoredDocumentSource> getExpandedStoredDocumentSources(StoredDocumentSource storedDocumentSource) throws IOException { List<StoredDocumentSource> childStoredDocumentSources = new ArrayList<StoredDocumentSource>(); String xmlDocumentsXpath = parameters.getParameterValue("xmlDocumentsXpath", ""); // no format specified, so let's have a peek at the contents to see if we can determine a sub-format DocumentFormat guessedFormat = DocumentFormat.UNKNOWN; if (parameters.getParameterValue("inputFormat", "").isEmpty()) { InputStream is = null;//from w ww .j av a 2 s . c o m try { is = storedDocumentSourceStorage.getStoredDocumentSourceInputStream(storedDocumentSource.getId()); XmlRootExtractor xmlRootExtractor = new XmlRootExtractor(); QName qname = xmlRootExtractor.extractRootElement(is); String name = qname.getLocalPart(); if (name.equals("feed") && qname.getNamespaceURI().toLowerCase().contains("atom")) guessedFormat = DocumentFormat.ATOM; else if (name.equals("TEI")) guessedFormat = DocumentFormat.TEI; else if (name.equals("teiCorpus")) guessedFormat = DocumentFormat.TEICORPUS; else if (name.equals("rss")) guessedFormat = DocumentFormat.RSS; else if (name.equals("EEBO")) guessedFormat = DocumentFormat.EEBODREAM; } finally { if (is != null) is.close(); } } // check to see if we need to set xmlDocumentsXpath using defaults for format if (xmlDocumentsXpath.isEmpty() && (parameters.getParameterValue("inputFormat", "").isEmpty() == false || guessedFormat != DocumentFormat.UNKNOWN)) { if (guessedFormat == DocumentFormat.UNKNOWN) { guessedFormat = DocumentFormat .valueOf(parameters.getParameterValue("inputFormat", "").toUpperCase()); } Properties properties = new Properties(); String resourcePath = "/org/voyanttools/trombone/input-formats/" + guessedFormat.name().toLowerCase() + ".xml"; URL url = this.getClass().getResource(resourcePath); if (url != null) { File file = new File(url.getPath()); if (file.exists()) { FileInputStream in = null; try { in = new FileInputStream(file); properties.loadFromXML(in); } finally { if (in != null) { in.close(); } } } if (properties.containsKey("xmlDocumentsXpath")) { xmlDocumentsXpath = properties.getProperty("xmlDocumentsXpath"); } } } String xmlGroupByXpath = parameters.getParameterValue("xmlGroupByXpath", ""); if (xmlDocumentsXpath.isEmpty()) { childStoredDocumentSources.add(storedDocumentSource); return childStoredDocumentSources; } DocumentMetadata parentMetadata = storedDocumentSource.getMetadata(); String parentId = storedDocumentSource.getId(); String multipleExpandedStoredDocumentSourcesPrefix = DigestUtils .md5Hex(xmlDocumentsXpath + xmlGroupByXpath); childStoredDocumentSources = storedDocumentSourceStorage.getMultipleExpandedStoredDocumentSources(parentId, multipleExpandedStoredDocumentSourcesPrefix); if (childStoredDocumentSources != null && childStoredDocumentSources.isEmpty() == false) { return childStoredDocumentSources; } // for some reason XPathAPI doesn't work properly with the default // XPathFactory, so we'll use Saxon System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON, "net.sf.saxon.xpath.XPathFactoryImpl"); InputStream inputStream = null; Document doc; try { inputStream = storedDocumentSourceStorage .getStoredDocumentSourceInputStream(storedDocumentSource.getId()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/validation", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setIgnoringComments(true); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(inputStream); } catch (ParserConfigurationException e) { throw new IOException("Error with XML parser configuration for " + storedDocumentSource, e); } catch (SAXException e) { throw new IOException("Error with XML parsing for " + storedDocumentSource, e); } finally { if (inputStream != null) inputStream.close(); } List<NodeInputSource> nodeInputSources = getChildStoredDocumentSources(doc, xmlDocumentsXpath, parentId, parentMetadata); if (nodeInputSources.isEmpty() == false) { if (xmlGroupByXpath.isEmpty() == false) { Map<String, List<NodeInputSource>> groupedNodeInputSources = new HashMap<String, List<NodeInputSource>>(); for (NodeInputSource nodeInputSource : nodeInputSources) { List<String> keys; try { Node fragment = doc.createDocumentFragment(); fragment.appendChild(nodeInputSource.node); keys = XPathAPI.selectNodeListAsStrings(fragment, xmlGroupByXpath); } catch (XPathException e) { throw new IllegalArgumentException("Unable to use this XPath: " + xmlGroupByXpath, e); } if (keys.isEmpty() == false) { String key = StringUtils.join(keys, " "); if (groupedNodeInputSources.containsKey(key) == false) { groupedNodeInputSources.put(key, new ArrayList<NodeInputSource>()); } groupedNodeInputSources.get(key).add(nodeInputSource); } } for (Map.Entry<String, List<NodeInputSource>> mappedNodeInputSources : groupedNodeInputSources .entrySet()) { List<NodeInputSource> mappedNodeInputSourcesList = mappedNodeInputSources.getValue(); // if (mappedNodeInputSourcesList.size()==1) { // just one, so use it // childStoredDocumentSources.add(getStoredDocumentSource(mappedNodeInputSourcesList.get(0))); // } // else { // multiple, we need to wrap with root node String key = mappedNodeInputSources.getKey(); Node newParentNode = doc.getDocumentElement().cloneNode(false); for (NodeInputSource nodeInputSource : mappedNodeInputSourcesList) { newParentNode.appendChild(nodeInputSource.node); } NodeInputSource newNodeInputSource = getChildStoredDocumentSource(newParentNode, parentId, parentMetadata, parentId + ";group:" + key); newNodeInputSource.documentMetadata.setTitle(key); childStoredDocumentSources.add(getStoredDocumentSource(newNodeInputSource)); // } } } else { for (NodeInputSource nodeInputSource : nodeInputSources) { childStoredDocumentSources.add(getStoredDocumentSource(nodeInputSource)); } } } // each node is a separate document // if (xmlDocumentsXpaths.length == 1) { // childStoredDocumentSources.addAll(getChildStoredDocumentSources( // doc, xmlDocumentsXpaths[0], parentId, parentMetadata)); // } // // // each xpath is a separate document // else { // childStoredDocumentSources.addAll(getChildStoredDocumentSources( // doc, xmlDocumentsXpaths, parentId, parentMetadata)); // } storedDocumentSourceStorage.setMultipleExpandedStoredDocumentSources(parentId, childStoredDocumentSources, multipleExpandedStoredDocumentSourcesPrefix); return childStoredDocumentSources; }
From source file:org.wso2.balana.ConfigurationStore.java
/** * Private helper that parses the file and sets up the DOM tree. *//*from w ww . j a va 2s . c o m*/ private Node getRootNode(File configFile) throws ParsingException { DocumentBuilderFactory dbFactory = Utils.getSecuredDocumentBuilderFactory(); dbFactory.setIgnoringComments(true); dbFactory.setNamespaceAware(false); dbFactory.setValidating(false); DocumentBuilder db = null; try { db = dbFactory.newDocumentBuilder(); } catch (ParserConfigurationException pce) { throw new ParsingException("couldn't get a document builder", pce); } Document doc = null; InputStream stream = null; try { stream = new FileInputStream(configFile); doc = db.parse(stream); } catch (IOException ioe) { throw new ParsingException("failed to load the file ", ioe); } catch (SAXException saxe) { throw new ParsingException("error parsing the XML tree", saxe); } catch (IllegalArgumentException iae) { throw new ParsingException("no data to parse", iae); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { logger.error("Error while closing input stream"); } } } Element root = doc.getDocumentElement(); if (!root.getTagName().equals("config")) throw new ParsingException("unknown document type: " + root.getTagName()); return root; }
From source file:org.wso2.balana.ctx.InputParser.java
/** * Tries to Parse the given output as a Context document. * //from www . j av a2 s . c o m * @param input the stream to parse * @param rootTage either "Request" or "Response" * * @return the root node of the request/response * * @throws ParsingException if a problem occurred parsing the document */ public static Node parseInput(InputStream input, String rootTag) throws ParsingException { NodeList nodes = null; try { DocumentBuilderFactory factory = Utils.getSecuredDocumentBuilderFactory(); factory.setIgnoringComments(true); DocumentBuilder builder = null; // as of 1.2, we always are namespace aware factory.setNamespaceAware(true); if (ipReference == null) { // we're not validating factory.setValidating(false); builder = factory.newDocumentBuilder(); } else { // we are validating factory.setValidating(true); factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); factory.setAttribute(JAXP_SCHEMA_SOURCE, ipReference.schemaFile); builder = factory.newDocumentBuilder(); builder.setErrorHandler(ipReference); } Document doc = builder.parse(input); nodes = doc.getElementsByTagName(rootTag); } catch (Exception e) { throw new ParsingException("Error tring to parse " + rootTag + "Type", e); } if (nodes.getLength() != 1) throw new ParsingException("Only one " + rootTag + "Type allowed " + "at the root of a Context doc"); return nodes.item(0); }