List of usage examples for javax.xml.parsers DocumentBuilderFactory setFeature
public abstract void setFeature(String name, boolean value) throws ParserConfigurationException;
From source file:hydrograph.ui.propertywindow.widgets.customwidgets.schema.ELTSchemaGridWidget.java
private boolean verifyExtSchemaSync(List<GridRow> schemaInGrid) { List<GridRow> schemasFromFile = new ArrayList<GridRow>(); File schemaFile = getPath(extSchemaPathText, SCHEMA_FILE_EXTENSION, true, SCHEMA_FILE_EXTENSION, XML_FILE_EXTENSION);// w w w .j ava 2 s . c om if (schemaFile == null) { return false; } Fields fields; boolean verifiedSchema = true; try (InputStream xml = new FileInputStream(schemaFile); InputStream xsd = new FileInputStream(SCHEMA_CONFIG_XSD_PATH);) { if (validateXML(xml, xsd)) { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setExpandEntityReferences(false); builderFactory.setNamespaceAware(true); builderFactory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION, true); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(schemaFile); JAXBContext jaxbContext = JAXBContext.newInstance(hydrograph.ui.common.schema.Schema.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); hydrograph.ui.common.schema.Schema schema = (hydrograph.ui.common.schema.Schema) jaxbUnmarshaller .unmarshal(document); fields = schema.getFields(); ArrayList<Field> fieldsList = (ArrayList<Field>) fields.getField(); GridRow gridRow = null; if (Messages.GENERIC_GRID_ROW.equals(gridRowType)) { for (Field field : fieldsList) { gridRow = new BasicSchemaGridRow(); populateCommonFields(gridRow, field); schemasFromFile.add(gridRow); } } else if (Messages.XPATH_GRID_ROW.equals(gridRowType)) { for (Field field : fieldsList) { gridRow = new XPathGridRow(); populateCommonFields(gridRow, field); String xpath = field.getAbsoluteOrRelativeXpath(); ((XPathGridRow) gridRow).setXPath(StringUtils.isNotBlank(xpath) ? xpath : ""); schemasFromFile.add(gridRow); } } else if (Messages.FIXEDWIDTH_GRID_ROW.equals(gridRowType)) { for (Field field : fieldsList) { gridRow = new FixedWidthGridRow(); populateCommonFields(gridRow, field); if (field.getLength() != null) ((FixedWidthGridRow) gridRow).setLength(String.valueOf(field.getLength())); else ((FixedWidthGridRow) gridRow).setLength(""); schemasFromFile.add(gridRow); } } else if (Messages.MIXEDSCHEME_GRID_ROW.equals(gridRowType)) { for (Field field : fieldsList) { gridRow = new MixedSchemeGridRow(); populateCommonFields(gridRow, field); if (field.getLength() != null) ((MixedSchemeGridRow) gridRow).setLength(String.valueOf(field.getLength())); else ((MixedSchemeGridRow) gridRow).setLength(""); ((MixedSchemeGridRow) gridRow).setDelimiter(field.getDelimiter()); schemasFromFile.add(gridRow); } } else if (Messages.GENERATE_RECORD_GRID_ROW.equals(gridRowType)) { for (Field field : fieldsList) { gridRow = new GenerateRecordSchemaGridRow(); populateCommonFields(gridRow, field); if (field.getLength() != null) ((GenerateRecordSchemaGridRow) gridRow) .setLength(String.valueOf(field.getLength())); else ((GenerateRecordSchemaGridRow) gridRow).setLength(""); if (field.getDefault() != null) ((GenerateRecordSchemaGridRow) gridRow) .setDefaultValue((String.valueOf(field.getDefault()))); else ((GenerateRecordSchemaGridRow) gridRow).setDefaultValue((String.valueOf(""))); if (field.getRangeFrom() != null) ((GenerateRecordSchemaGridRow) gridRow) .setRangeFrom(String.valueOf(field.getRangeFrom())); else ((GenerateRecordSchemaGridRow) gridRow).setRangeFrom(""); if (field.getRangeFrom() != null) ((GenerateRecordSchemaGridRow) gridRow) .setRangeTo(String.valueOf(field.getRangeTo())); else ((GenerateRecordSchemaGridRow) gridRow).setRangeTo(""); schemasFromFile.add(gridRow); } } } catch (JAXBException | ParserConfigurationException | SAXException | IOException e) { logger.error(Messages.EXPORTED_SCHEMA_SYNC_ERROR, e); } } if (!equalLists(schemaInGrid, schemasFromFile, new GridComparator())) { verifiedSchema = false; //MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Information", Messages.EXPORTED_SCHEMA_NOT_IN_SYNC); MessageBox dialog = new MessageBox(Display.getCurrent().getActiveShell(), SWT.ICON_INFORMATION | SWT.OK); dialog.setText(Messages.INFORMATION); dialog.setMessage(Messages.EXPORTED_SCHEMA_NOT_IN_SYNC); } } catch (FileNotFoundException e) { logger.error(Messages.EXPORTED_SCHEMA_SYNC_ERROR, e); } catch (IOException e) { logger.error(Messages.EXPORTED_SCHEMA_SYNC_ERROR, e); } return verifiedSchema; }
From source file:com.ext.portlet.epsos.EpsosHelperService.java
public static String getPortalTranslation(String key, String language) { String translation = ""; language = language.replaceAll("_", "-"); try {/*from w ww . ja va2 s . c o m*/ ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL url = cl.getResource("content/language/application/" + language + "/SpiritEhrPortal.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(url.getFile()); doc.getDocumentElement().normalize(); XPath xpath = XPathFactory.newInstance().newXPath(); translation = xpath.evaluate("//*[@key='" + key + "']", doc); if (Validator.isNull(translation)) translation = key; } catch (Exception e) { Log.error(e.getMessage()); } return translation; }
From source file:com.ext.portlet.epsos.EpsosHelperService.java
public static String getConsentText(String language) { String translation = ""; language = language.replaceAll("_", "-"); try {// w w w . j a v a2 s.c o m ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL url = cl.getResource("content/language/consent/Consent_LegalText_" + language + ".xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(url.getFile()); doc.getDocumentElement().normalize(); XPath xpath = XPathFactory.newInstance().newXPath(); String xpathExpression = "/Consent/LegalText"; NodeList nodes = (NodeList) xpath.evaluate(xpathExpression, doc, XPathConstants.NODESET); translation = nodes.item(0).getTextContent(); } catch (Exception e) { Log.error("Error getting consent text for country " + language); } return translation; }
From source file:de.interactive_instruments.ShapeChange.Options.java
public void loadConfiguration() throws ShapeChangeAbortException { InputStream configStream = null; if (configFile == null) { // load minimal configuration, if no configuration file has been // provided configFile = "/config/minimal.xml"; configStream = getClass().getResourceAsStream(configFile); if (configStream == null) { configFile = "src/main/resources" + configFile; File file = new File(configFile); if (file.exists()) try { configStream = new FileInputStream(file); } catch (FileNotFoundException e1) { throw new ShapeChangeAbortException("Minimal configuration file not found: " + configFile); }//from w w w .j av a 2s . com else { URL url; String configURL = "http://shapechange.net/resources/config/minimal.xml"; try { url = new URL(configURL); configStream = url.openStream(); } catch (MalformedURLException e) { throw new ShapeChangeAbortException("Minimal configuration file not accessible from: " + configURL + " (malformed URL)"); } catch (IOException e) { throw new ShapeChangeAbortException( "Minimal configuration file not accessible from: " + configURL + " (IO error)"); } } } } else { File file = new File(configFile); if (file == null || !file.exists()) { try { configStream = (new URL(configFile)).openStream(); } catch (MalformedURLException e) { throw new ShapeChangeAbortException( "No configuration file found at " + configFile + " (malformed URL)"); } catch (IOException e) { throw new ShapeChangeAbortException( "No configuration file found at " + configFile + " (IO exception)"); } } else { try { configStream = new FileInputStream(file); } catch (FileNotFoundException e) { throw new ShapeChangeAbortException("No configuration file found at " + configFile); } } if (configStream == null) { throw new ShapeChangeAbortException("No configuration file found at " + configFile); } } DocumentBuilder builder = null; ShapeChangeErrorHandler handler = null; try { System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); factory.setFeature("http://apache.org/xml/features/validation/schema", true); factory.setIgnoringElementContentWhitespace(true); factory.setIgnoringComments(true); factory.setXIncludeAware(true); factory.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false); builder = factory.newDocumentBuilder(); handler = new ShapeChangeErrorHandler(); builder.setErrorHandler(handler); } catch (FactoryConfigurationError e) { throw new ShapeChangeAbortException("Unable to get a document builder factory."); } catch (ParserConfigurationException e) { throw new ShapeChangeAbortException("XML Parser was unable to be configured."); } // parse file try { Document document = builder.parse(configStream); if (handler.errorsFound()) { throw new ShapeChangeAbortException("Invalid configuration file."); } // parse input element specific content NodeList nl = document.getElementsByTagName("input"); Element inputElement = (Element) nl.item(0); if (inputElement.hasAttribute("id")) { inputId = inputElement.getAttribute("id").trim(); if (inputId.length() == 0) { inputId = null; } } else { inputId = Options.INPUTELEMENTID; } Map<String, String> inputParameters = new HashMap<String, String>(); nl = inputElement.getElementsByTagName("parameter"); for (int j = 0; j < nl.getLength(); j++) { Element e = (Element) nl.item(j); String key = e.getAttribute("name"); String val = e.getAttribute("value"); inputParameters.put(key, val); } Map<String, String> stereotypeAliases = new HashMap<String, String>(); nl = inputElement.getElementsByTagName("StereotypeAlias"); for (int j = 0; j < nl.getLength(); j++) { Element e = (Element) nl.item(j); String key = e.getAttribute("alias"); String val = e.getAttribute("wellknown"); // case shall be ignored key = key.toLowerCase(); val = val.toLowerCase(); stereotypeAliases.put(key, val); } Map<String, String> tagAliases = new HashMap<String, String>(); nl = inputElement.getElementsByTagName("TagAlias"); for (int j = 0; j < nl.getLength(); j++) { Element e = (Element) nl.item(j); String key = e.getAttribute("alias"); String val = e.getAttribute("wellknown"); // case not to be ignored for tagged values at the moment // key = key.toLowerCase(); // val = val.toLowerCase(); tagAliases.put(key, val); } Map<String, String> descriptorSources = new HashMap<String, String>(); nl = inputElement.getElementsByTagName("DescriptorSource"); for (int j = 0; j < nl.getLength(); j++) { Element e = (Element) nl.item(j); String key = e.getAttribute("descriptor"); String val = e.getAttribute("source"); // case shall be ignored for descriptor and source key = key.toLowerCase(); val = val.toLowerCase(); if (val.equals("sc:extract")) { String s = e.getAttribute("token"); val += "#" + (s == null ? "" : s); } else if (val.equals("tag")) { String s = e.getAttribute("tag"); val += "#" + (s == null ? "" : s); } descriptorSources.put(key, val); } Map<String, PackageInfoConfiguration> packageInfos = parsePackageInfos(inputElement); this.inputConfig = new InputConfiguration(inputId, inputParameters, stereotypeAliases, tagAliases, descriptorSources, packageInfos); // parse dialog specific parameters nl = document.getElementsByTagName("dialog"); if (nl != null && nl.getLength() != 0) { for (int k = 0; k < nl.getLength(); k++) { Node node = nl.item(k); if (node.getNodeType() == Node.ELEMENT_NODE) { Element dialogElement = (Element) node; this.dialogParameters = parseParameters(dialogElement, "parameter"); } } } // parse log specific parameters nl = document.getElementsByTagName("log"); if (nl != null && nl.getLength() != 0) { for (int k = 0; k < nl.getLength(); k++) { Node node = nl.item(k); if (node.getNodeType() == Node.ELEMENT_NODE) { Element logElement = (Element) node; this.logParameters = parseParameters(logElement, "parameter"); } } } // add standard rules, just so that configured rules can be // validated addStandardRules(); // Load transformer configurations (if any are provided in the // configuration file) Map<String, TransformerConfiguration> transformerConfigs = parseTransformerConfigurations(document); // Load target configurations this.targetConfigs = parseTargetConfigurations(document); this.resetFields(); // this.resetUponLoadFlag = false; // TBD discuss if there's a better way to support rule and // requirements matching for the input model // TBD apparently the matching requires all // applicable encoding rules to be known up front for (TargetConfiguration tgtConfig : targetConfigs) { // System.out.println(tgtConfig); String className = tgtConfig.getClassName(); String mode = tgtConfig.getProcessMode().name(); // set targets and their mode; if a target occurs multiple // times, keep the enabled one(s) if (!this.fTargets.containsKey(className)) { addTarget(className, mode); } else { if (this.fTargets.get(className).equals(ProcessMode.disabled)) { // set targets and their mode; if a target occurs // multiple times, keep the enabled one(s) addTarget(className, mode); } } // ensure that we have all the rules from all non-disabled // targets // we repeat this for the same target (if it is not disabled) to // ensure that we get the union of all encoding rules if (!tgtConfig.getProcessMode().equals(ProcessMode.disabled)) { for (ProcessRuleSet prs : tgtConfig.getRuleSets().values()) { String nam = prs.getName(); String ext = prs.getExtendedRuleSetName(); addExtendsEncRule(nam, ext); if (prs.hasAdditionalRules()) { for (String rule : prs.getAdditionalRules()) { addRule(rule, nam); } } } } /* * looks like we also need parameters like defaultEncodingRule * !!! IF THERE ARE DIFFERENT DEFAULT ENCODING RULES FOR * DIFFERENT TARGETS (WITH SAME CLASS) THIS WONT WORK!!! */ for (String paramName : tgtConfig.getParameters().keySet()) { setParameter(className, paramName, tgtConfig.getParameters().get(paramName)); } // in order for the input model load not to produce warnings, // we also need to load the map entries if (tgtConfig instanceof TargetXmlSchemaConfiguration) { TargetXmlSchemaConfiguration config = (TargetXmlSchemaConfiguration) tgtConfig; // add xml schema namespace information for (XmlNamespace xns : config.getXmlNamespaces()) { addNamespace(xns.getNsabr(), xns.getNs(), xns.getLocation()); // if (xns.getLocation() != null) { addSchemaLocation(xns.getNs(), xns.getLocation()); // } } // add xsd map entries for (XsdMapEntry xsdme : config.getXsdMapEntries()) { for (String xsdEncodingRule : xsdme.getEncodingRules()) { String type = xsdme.getType(); String xmlPropertyType = xsdme.getXmlPropertyType(); String xmlElement = xsdme.getXmlElement(); String xmlTypeContent = xsdme.getXmlTypeContent(); String xmlTypeNilReason = xsdme.getXmlTypeNilReason(); String xmlType = xsdme.getXmlType(); String xmlTypeType = xsdme.getXmlTypeType(); String xmlAttribute = xsdme.getXmlAttribute(); String xmlAttributeGroup = xsdme.getXmlAttributeGroup(); if (xmlPropertyType != null) { if (xmlPropertyType.equals("_P_") && xmlElement != null) { addTypeMapEntry(type, xsdEncodingRule, "propertyType", xmlElement); } else if (xmlPropertyType.equals("_MP_") && xmlElement != null) { addTypeMapEntry(type, xsdEncodingRule, "metadataPropertyType", xmlElement); } else { addTypeMapEntry(type, xsdEncodingRule, "direct", xmlPropertyType, xmlTypeType + "/" + xmlTypeContent, xmlTypeNilReason); } } if (xmlElement != null) { addElementMapEntry(type, xsdEncodingRule, "direct", xmlElement); } if (xmlType != null) { addBaseMapEntry(type, xsdEncodingRule, "direct", xmlType, xmlTypeType + "/" + xmlTypeContent); } if (xmlAttribute != null) { addAttributeMapEntry(type, xsdEncodingRule, xmlAttribute); } if (xmlAttributeGroup != null) { addAttributeGroupMapEntry(type, xsdEncodingRule, xmlAttributeGroup); } } } } else { // add map entries for Target (no need to do this for // transformers) for (ProcessMapEntry pme : tgtConfig.getMapEntries()) { addTargetTypeMapEntry(tgtConfig.getClassName(), pme.getType(), pme.getRule(), pme.getTargetType(), pme.getParam()); } } } // create "tree" for (TargetConfiguration tgtConfig : targetConfigs) { for (String inputIdref : tgtConfig.getInputIds()) { if (inputIdref.equals(getInputId())) { this.inputTargetConfigs.add(tgtConfig); } else { transformerConfigs.get(inputIdref).addTarget(tgtConfig); } } } for (TransformerConfiguration trfConfig : transformerConfigs.values()) { String inputIdref = trfConfig.getInputId(); if (inputIdref.equals(getInputId())) { this.inputTransformerConfigs.add(trfConfig); } else { transformerConfigs.get(inputIdref).addTransformer(trfConfig); } } // Determine constraint creation handling parameters: String classTypesToCreateConstraintsFor = parameter("classTypesToCreateConstraintsFor"); if (classTypesToCreateConstraintsFor != null) { classTypesToCreateConstraintsFor = classTypesToCreateConstraintsFor.trim(); if (classTypesToCreateConstraintsFor.length() > 0) { String[] stereotypes = classTypesToCreateConstraintsFor.split("\\W*,\\W*"); this.classTypesToCreateConstraintsFor = new HashSet<Integer>(); for (String stereotype : stereotypes) { String sForCons = stereotype.toLowerCase(); if (sForCons.equals("enumeration")) { this.classTypesToCreateConstraintsFor.add(new Integer(ENUMERATION)); } else if (sForCons.equals("codelist")) { this.classTypesToCreateConstraintsFor.add(new Integer(CODELIST)); } else if (sForCons.equals("schluesseltabelle")) { this.classTypesToCreateConstraintsFor.add(new Integer(OKSTRAKEY)); } else if (sForCons.equals("fachid")) { this.classTypesToCreateConstraintsFor.add(new Integer(OKSTRAFID)); } else if (sForCons.equals("datatype")) { this.classTypesToCreateConstraintsFor.add(new Integer(DATATYPE)); } else if (sForCons.equals("union")) { this.classTypesToCreateConstraintsFor.add(new Integer(UNION)); } else if (sForCons.equals("featureconcept")) { this.classTypesToCreateConstraintsFor.add(new Integer(FEATURECONCEPT)); } else if (sForCons.equals("attributeconcept")) { this.classTypesToCreateConstraintsFor.add(new Integer(ATTRIBUTECONCEPT)); } else if (sForCons.equals("valueconcept")) { this.classTypesToCreateConstraintsFor.add(new Integer(VALUECONCEPT)); } else if (sForCons.equals("interface")) { this.classTypesToCreateConstraintsFor.add(new Integer(MIXIN)); } else if (sForCons.equals("basictype")) { this.classTypesToCreateConstraintsFor.add(new Integer(BASICTYPE)); } else if (sForCons.equals("adeelement")) { this.classTypesToCreateConstraintsFor.add(new Integer(FEATURE)); } else if (sForCons.equals("featuretype")) { this.classTypesToCreateConstraintsFor.add(new Integer(FEATURE)); } else if (sForCons.equals("type")) { this.classTypesToCreateConstraintsFor.add(new Integer(OBJECT)); } else { this.classTypesToCreateConstraintsFor.add(new Integer(UNKNOWN)); } } } } String constraintCreationForProperties = parameter("constraintCreationForProperties"); if (constraintCreationForProperties != null) { if (constraintCreationForProperties.trim().equalsIgnoreCase("false")) { this.constraintCreationForProperties = false; } } /* * TODO add documentation */ String ignoreEncodingRuleTaggedValues = parameter("ignoreEncodingRuleTaggedValues"); if (ignoreEncodingRuleTaggedValues != null) { if (ignoreEncodingRuleTaggedValues.trim().equalsIgnoreCase("true")) { this.ignoreEncodingRuleTaggedValues = true; } } String useStringInterning_value = parameter(PARAM_USE_STRING_INTERNING); if (useStringInterning_value != null && useStringInterning_value.trim().equalsIgnoreCase("true")) { this.useStringInterning = true; } String loadGlobalIds_value = this.parameter(PARAM_LOAD_GLOBAL_IDENTIFIERS); if (loadGlobalIds_value != null && loadGlobalIds_value.trim().equalsIgnoreCase("true")) { this.loadGlobalIds = true; } String language_value = inputConfig.getParameters().get(PARAM_LANGUAGE); if (language_value != null && !language_value.trim().isEmpty()) { this.language = language_value.trim().toLowerCase(); } } catch (SAXException e) { String m = e.getMessage(); if (m != null) { throw new ShapeChangeAbortException( "Error while loading configuration file: " + System.getProperty("line.separator") + m); } else { e.printStackTrace(System.err); throw new ShapeChangeAbortException("Error while loading configuration file: " + System.getProperty("line.separator") + System.err); } } catch (IOException e) { String m = e.getMessage(); if (m != null) { throw new ShapeChangeAbortException( "Error while loading configuration file: " + System.getProperty("line.separator") + m); } else { e.printStackTrace(System.err); throw new ShapeChangeAbortException("Error while loading configuration file: " + System.getProperty("line.separator") + System.err); } } MapEntry nsme = namespace("gml"); if (nsme != null) { GML_NS = nsme.rule; } }
From source file:com.ext.portlet.epsos.EpsosHelperService.java
public String getLanguagesFromCS() { String listOfLangs = ""; try {/*from w w w. j av a 2s .com*/ ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL url = cl.getResource("content/language/languages.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(url.getFile()); doc.getDocumentElement().normalize(); NodeList nodeLst = doc.getElementsByTagName("entry"); String seperator = ""; for (int s = 0; s < nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); if (listOfLangs.length() > 1) { seperator = ","; } Element link = (Element) nodeLst.item(s); String a1 = link.getAttribute("key"); if (getCountryIdsFromCS(a1).get(0) != null) { listOfLangs = listOfLangs + seperator + a1; } } } catch (Exception e) { Log.error(e.getMessage()); } return listOfLangs; }
From source file:net.sourceforge.pmd.lang.xml.ast.XmlParser.java
protected Document parseDocument(Reader reader) throws ParseException { nodeCache.clear();/*from w w w .j a va 2 s . com*/ try { String xmlData = IOUtils.toString(reader); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(parserOptions.isNamespaceAware()); dbf.setValidating(parserOptions.isValidating()); dbf.setIgnoringComments(parserOptions.isIgnoringComments()); dbf.setIgnoringElementContentWhitespace(parserOptions.isIgnoringElementContentWhitespace()); dbf.setExpandEntityReferences(parserOptions.isExpandEntityReferences()); dbf.setCoalescing(parserOptions.isCoalescing()); dbf.setXIncludeAware(parserOptions.isXincludeAware()); dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); DocumentBuilder documentBuilder = dbf.newDocumentBuilder(); documentBuilder.setEntityResolver(parserOptions.getEntityResolver()); Document document = documentBuilder.parse(new InputSource(new StringReader(xmlData))); DOMLineNumbers lineNumbers = new DOMLineNumbers(document, xmlData); lineNumbers.determine(); return document; } catch (ParserConfigurationException | SAXException | IOException e) { throw new ParseException(e); } }
From source file:net.sourceforge.pmd.RuleSetFactory.java
private DocumentBuilder createDocumentBuilder() throws ParserConfigurationException { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try {// w w w .j a v a 2 s . c om /* * parser hardening * https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#JAXP_DocumentBuilderFactory.2C_SAXParserFactory_and_DOM4J */ // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); // If you can't completely disable DTDs, then at least do the following: // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities // JDK7+ - http://xml.org/sax/features/external-general-entities dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities // JDK7+ - http://xml.org/sax/features/external-parameter-entities dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); // Disable external DTDs as well dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks" dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); } catch (final ParserConfigurationException e) { // an unsupported feature... too bad, but won't fail execution due to this LOG.log(Level.WARNING, "Ignored unsupported XML Parser Feature for parsing rulesets", e); } return dbf.newDocumentBuilder(); }
From source file:nl.armatiek.xslweb.utils.XMLUtils.java
public static DocumentBuilder getDocumentBuilder(boolean validate, boolean namespaceAware, boolean xincludeAware) throws XSLWebException { try {// w w w .j a va 2 s . c o m DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); if (xincludeAware) { docFactory.setFeature("http://apache.org/xml/features/xinclude", true); docFactory.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false); docFactory.setFeature("http://apache.org/xml/features/xinclude/fixup-language", false); docFactory.setXIncludeAware(true); } docFactory.setNamespaceAware(namespaceAware); docFactory.setValidating(validate); docFactory.setExpandEntityReferences(true); if (validate) { docFactory.setFeature("http://apache.org/xml/features/validation/dynamic", true); docFactory.setFeature("http://apache.org/xml/features/validation/schema", true); } docFactory.setIgnoringElementContentWhitespace(true); return docFactory.newDocumentBuilder(); } catch (Exception e) { throw new XSLWebException(e); } }
From source file:nl.imvertor.common.file.XmlFile.java
/** * Build a DOM Document representation of some external XML file. * //from ww w.ja v a 2 s . co m * @return * @throws Exception */ private Document buildDom(File file) throws Exception { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); InputSource in = new InputSource(file.getAbsolutePath()); docFactory.setValidating(validate); docFactory.setXIncludeAware(xinclude); docFactory.setFeature(VALIDATION_FEATURE_ID, validate); docFactory.setFeature(NAMESPACES_FEATURE_ID, namespace); docFactory.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schema); docFactory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemacheck); docFactory.setFeature(EXTERNAL_GENERAL_ENTITIES_ID, external); docFactory.setFeature(EXTERNAL_PARAMETER_ENTITIES_ID, external); DocumentBuilder db = docFactory.newDocumentBuilder(); return db.parse(in); }