List of usage examples for javax.xml.parsers DocumentBuilderFactory setFeature
public abstract void setFeature(String name, boolean value) throws ParserConfigurationException;
From source file:org.adeptnet.auth.saml.SAMLClient.java
private DocumentBuilder createDocumentBuilder(boolean validating, boolean disAllowDocTypeDeclarations) throws ParserConfigurationException { final DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); if (disAllowDocTypeDeclarations) { dfactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); }//from w ww . j a va 2 s.com dfactory.setValidating(validating); dfactory.setNamespaceAware(true); return dfactory.newDocumentBuilder(); }
From source file:org.alfresco.repo.content.metadata.xml.XPathMetadataExtracter.java
/** * Default constructor/* w ww. ja v a2 s. co m*/ */ public XPathMetadataExtracter() { super(new HashSet<String>(Arrays.asList(SUPPORTED_MIMETYPES))); try { DocumentBuilderFactory normalFactory = DocumentBuilderFactory.newInstance(); documentBuilder = normalFactory.newDocumentBuilder(); DocumentBuilderFactory dtdIgnoringFactory = DocumentBuilderFactory.newInstance(); dtdIgnoringFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); dtdIgnoringFactory.setFeature("http://xml.org/sax/features/validation", false); dtdIgnoringDocumentBuilder = dtdIgnoringFactory.newDocumentBuilder(); xpathFactory = XPathFactory.newInstance(); } catch (Throwable e) { throw new AlfrescoRuntimeException("Failed to initialize XML metadata extractor", e); } }
From source file:org.apache.nifi.minifi.FlowParser.java
/** * Generates a {@link Document} from the flow configuration file provided *//*w ww.j a v a2 s .c om*/ public Document parse(final File flowConfigurationFile) { if (flowConfigurationFile == null) { logger.debug("Flow Configuration file was null"); return null; } // if the flow doesn't exist or is 0 bytes, then return null final Path flowPath = flowConfigurationFile.toPath(); try { if (!Files.exists(flowPath) || Files.size(flowPath) == 0) { logger.warn("Flow Configuration does not exist or was empty"); return null; } } catch (IOException e) { logger.error("An error occurred determining the size of the Flow Configuration file"); return null; } // otherwise create the appropriate input streams to read the file try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ); final InputStream gzipIn = new GZIPInputStream(in)) { final byte[] flowBytes = IOUtils.toByteArray(gzipIn); if (flowBytes == null || flowBytes.length == 0) { logger.warn("Could not extract root group id because Flow Configuration File was empty"); return null; } final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); // parse the flow final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); docBuilder.setErrorHandler(new LoggingXmlParserErrorHandler("Flow Configuration", logger)); final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes)); return document; } catch (final SAXException | ParserConfigurationException | IOException ex) { logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex }); return null; } }
From source file:org.apache.olingo.client.core.serialization.ClientODataDeserializerImpl.java
private List<List<String>> getAllSchemaNameSpace(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException { List<List<String>> schemaNameSpaces = new ArrayList<List<String>>(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setFeature("http://xml.org/sax/features/namespaces", true); dbFactory.setFeature("http://apache.org/xml/features/validation/schema", false); dbFactory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); dbFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); dbFactory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputStream); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName(SCHEMA); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); List<String> nameSpaces = new ArrayList<String>(); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; NamedNodeMap attributes = eElement.getAttributes(); int len = attributes.getLength(); for (int i = 0; i < len; i++) { // check for all atributes begining with name xmlns or xmlns: String attrName = attributes.item(i).getNodeName(); if (XMLNS.equals(attrName) || attrName.startsWith(XMLNS + ":")) { nameSpaces.add(attributes.item(i).getNodeValue()); }//from w ww. j a v a 2 s . c om } } schemaNameSpaces.add(nameSpaces); } return schemaNameSpaces; }
From source file:org.apache.oozie.cli.OozieCLI.java
private Properties parse(InputStream is, Properties conf) throws IOException { try {/*from w w w.j av a2 s . co m*/ DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(true); // support for includes in the xml file docBuilderFactory.setXIncludeAware(true); // ignore all comments inside the xml file docBuilderFactory.setIgnoringComments(true); docBuilderFactory.setExpandEntityReferences(false); docBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); Document doc = builder.parse(is); return parseDocument(doc, conf); } catch (SAXException e) { throw new IOException(e); } catch (ParserConfigurationException e) { throw new IOException(e); } }
From source file:org.apache.rahas.TrustUtil.java
/** * Create DocumentBuilderFactory with the XXE and XEE prevention measurements * * @return DocumentBuilderFactory instance *///from w w w . ja va 2 s .co m public static DocumentBuilderFactory getSecuredDocumentBuilderFactory() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); try { dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false); dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false); dbf.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (ParserConfigurationException e) { logger.error("Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE + " or " + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or " + Constants.LOAD_EXTERNAL_DTD_FEATURE + "or secure-processing."); } SecurityManager securityManager = new SecurityManager(); securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT); dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager); return dbf; }
From source file:org.apache.rampart.util.Axis2Util.java
/** * Create DocumentBuilderFactory with the XXE prevention measurements * * @return DocumentBuilderFactory instance *///from w w w. j a va2s. co m public static DocumentBuilderFactory getSecuredDocumentBuilderFactory() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); try { dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false); dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false); dbf.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (ParserConfigurationException e) { logger.error("Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE + " or " + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or " + Constants.LOAD_EXTERNAL_DTD_FEATURE); } SecurityManager securityManager = new SecurityManager(); securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT); dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager); return dbf; }
From source file:org.apache.ranger.utils.install.XmlConfigChanger.java
public void run() throws ParserConfigurationException, SAXException, IOException, TransformerException { loadInstallProperties();/*from w ww .j av a 2 s. c om*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(inpFile); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(confFile)); String line = null; @SuppressWarnings("unused") int lineNo = 0; Properties variables = new Properties(); while ((line = reader.readLine()) != null) { lineNo++; line = line.trim(); if (line.isEmpty()) continue; if (line.startsWith("#")) { continue; } if (line.contains("#")) { int len = line.indexOf("#"); line = line.substring(0, len); } String[] tokens = line.split("\\s+"); String propName = tokens[0]; String propValue = null; try { if (propnameContainsVariables(propName)) { propName = replaceProp(propName, variables); } propValue = replaceProp(tokens[1], installProperties); } catch (ValidationException e) { // throw new RuntimeException("Unable to replace tokens in the line: \n[" + line + "]\n in file [" + confFile.getAbsolutePath() + "] line number:[" + lineNo + "]" ); throw new RuntimeException(e); } String actionType = tokens[2]; String options = (tokens.length > 3 ? tokens[3] : null); boolean createIfNotExists = (options != null && options.contains("create-if-not-exists")); if ("add".equals(actionType)) { addProperty(propName, propValue); } else if ("mod".equals(actionType)) { modProperty(propName, propValue, createIfNotExists); } else if ("del".equals(actionType)) { delProperty(propName); } else if ("append".equals(actionType)) { String curVal = getProperty(propName); if (curVal == null) { if (createIfNotExists) { addProperty(propName, propValue); } } else { String appendDelimitor = (tokens.length > 4 ? tokens[4] : " "); if (!curVal.contains(propValue)) { String newVal = null; if (curVal.length() == 0) { newVal = propValue; } else { newVal = curVal + appendDelimitor + propValue; } modProperty(propName, newVal, createIfNotExists); } } } else if ("delval".equals(actionType)) { String curVal = getProperty(propName); if (curVal != null) { String appendDelimitor = (tokens.length > 4 ? tokens[4] : " "); if (curVal.contains(propValue)) { String[] valTokens = curVal.split(appendDelimitor); StringBuilder sb = new StringBuilder(); for (String v : valTokens) { if (!v.equals(propValue)) { if (sb.length() > 0) { sb.append(appendDelimitor); } sb.append(v); } } String newVal = sb.toString(); modProperty(propName, newVal, createIfNotExists); } } } else if ("var".equals(actionType)) { variables.put(propName, propValue); } else { throw new RuntimeException( "Unknown Command Found: [" + actionType + "], Supported Types: add modify del append"); } } TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer transformer = tfactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); DOMSource source = new DOMSource(doc); FileOutputStream out = new FileOutputStream(outFile); StreamResult result = new StreamResult(out); transformer.transform(source, result); out.close(); } finally { if (reader != null) { reader.close(); } } }
From source file:org.apache.syncope.core.logic.init.CamelRouteLoader.java
private void loadRoutes(final String domain, final DataSource dataSource, final Resource resource, final AnyTypeKind anyTypeKind) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); boolean shouldLoadRoutes = jdbcTemplate.queryForList( String.format("SELECT * FROM %s WHERE ANYTYPEKIND = ?", CamelRoute.class.getSimpleName()), new Object[] { anyTypeKind.name() }).isEmpty(); if (shouldLoadRoutes) { try {/* ww w . j a va2s .c o m*/ TransformerFactory tf = null; DOMImplementationLS domImpl = null; NodeList routeNodes; if (IS_JBOSS) { tf = TransformerFactory.newInstance(); tf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(resource.getInputStream()); routeNodes = doc.getDocumentElement().getElementsByTagName("route"); } else { DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance(); domImpl = (DOMImplementationLS) reg.getDOMImplementation("LS"); LSInput lsinput = domImpl.createLSInput(); lsinput.setByteStream(resource.getInputStream()); LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); routeNodes = parser.parse(lsinput).getDocumentElement().getElementsByTagName("route"); } for (int s = 0; s < routeNodes.getLength(); s++) { Node routeElement = routeNodes.item(s); String routeContent = IS_JBOSS ? nodeToString(routeNodes.item(s), tf) : nodeToString(routeNodes.item(s), domImpl); String routeId = ((Element) routeElement).getAttribute("id"); jdbcTemplate.update( String.format("INSERT INTO %s(ID, ANYTYPEKIND, CONTENT) VALUES (?, ?, ?)", CamelRoute.class.getSimpleName()), new Object[] { routeId, anyTypeKind.name(), routeContent }); LOG.info("[{}] Route successfully loaded: {}", domain, routeId); } } catch (Exception e) { LOG.error("[{}] Route load failed", domain, e); } } }
From source file:org.apache.syncope.installer.utilities.MavenUtils.java
public static File createSettingsWithProxy(final String path, final String proxyHost, final String proxyPort, final String proxyUser, final String proxyPassword) throws IOException, ParserConfigurationException, TransformerException, SAXException { final File settingsXML = new File(System.getProperty(MAVEN_HOME_PROPERTY) + (System.getProperty(MAVEN_HOME_PROPERTY).endsWith("/") ? "conf/settings.xml" : "/conf/settings.xml")); final File tempSettingsXML = new File( path + (path.endsWith("/") ? "settings_temp.xml" : "/settings_temp.xml")); if (settingsXML.canRead() && !tempSettingsXML.exists()) { tempSettingsXML.createNewFile(); final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true); final DocumentBuilder builder = dbf.newDocumentBuilder(); // parse settings.xml final Document settings = builder.parse(settingsXML); final Element proxies = (Element) settings.getDocumentElement().getElementsByTagName("proxies").item(0); final Element proxy = settings.createElement("proxy"); final Element id = settings.createElement("id"); final Element active = settings.createElement("active"); final Element protocol = settings.createElement("protocol"); final Element host = settings.createElement("host"); final Element port = settings.createElement("port"); final Element nonProxyHosts = settings.createElement("nonProxyHosts"); id.appendChild(settings.createTextNode("optional")); active.appendChild(settings.createTextNode("true")); protocol.appendChild(settings.createTextNode("http")); host.appendChild(settings.createTextNode(proxyHost)); port.appendChild(settings.createTextNode(proxyPort)); proxy.appendChild(id);/* ww w. jav a 2s . c o m*/ proxy.appendChild(active); proxy.appendChild(protocol); // create username and password tags only if required if (proxyUser != null && !proxyUser.isEmpty() && proxyPassword != null) { final Element username = settings.createElement("username"); final Element password = settings.createElement("password"); username.appendChild(settings.createTextNode(proxyUser)); password.appendChild(settings.createTextNode(proxyPassword)); proxy.appendChild(username); proxy.appendChild(password); } proxy.appendChild(host); proxy.appendChild(port); proxy.appendChild(nonProxyHosts); proxies.appendChild(proxy); FileSystemUtils.writeXML(settings, Files.newOutputStream(tempSettingsXML.toPath())); } return tempSettingsXML; }