List of usage examples for javax.xml.parsers DocumentBuilderFactory setFeature
public abstract void setFeature(String name, boolean value) throws ParserConfigurationException;
From source file:org.slc.sli.api.security.saml.SamlHelper.java
@PostConstruct public void init() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);/* www. ja v a2 s .c om*/ factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); domBuilder = factory.newDocumentBuilder(); transform = TransformerFactory.newInstance().newTransformer(); transform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); }
From source file:org.slc.sli.sandbox.idp.saml.SamlRequestDecoder.java
public SamlRequest decode(String encodedSamlRequest) { byte[] decodedCompressed = Base64.decodeBase64(encodedSamlRequest); Inflater inflater = new Inflater(true); InflaterInputStream xmlInputStream = new InflaterInputStream(new ByteArrayInputStream(decodedCompressed), inflater);//from w ww.java2s .c o m Document doc; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); DocumentBuilder docBuilder = factory.newDocumentBuilder(); doc = docBuilder.parse(xmlInputStream); } catch (ParserConfigurationException e) { throw new SamlProcessException(e); } catch (SAXException e) { throw new SamlProcessException(e); } catch (IOException e) { throw new SamlProcessException(e); } Element element = doc.getDocumentElement(); String id = element.getAttribute("ID"); boolean forceAuthn = Boolean.valueOf(element.getAttribute("ForceAuthn")); String simpleIDPDestination = element.getAttribute("Destination"); NodeList nodes = element.getElementsByTagName("saml:Issuer"); String issuer = null; if (nodes.getLength() > 0) { Node item = nodes.item(0); issuer = item.getFirstChild().getNodeValue(); } else { throw new IllegalArgumentException("No Issuer element on AuthnRequest"); } if (id == null) { throw new IllegalArgumentException("No ID attribute on AuthnRequest."); } String responseDestination = cot.get(issuer); if (responseDestination == null) { throw new IllegalArgumentException("Issuer of AuthnRequest is unknown."); } return new SamlRequest(responseDestination, simpleIDPDestination, id, forceAuthn); }
From source file:org.sonar.api.utils.XpathParser.java
public XpathParser() { DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance(); try {/* w w w . j a va2 s . co m*/ bf.setFeature("http://apache.org/xml/features/validation/schema", false); bf.setFeature("http://xml.org/sax/features/external-general-entities", false); bf.setFeature("http://xml.org/sax/features/validation", false); bf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); bf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); bf.setFeature("http://apache.org/xml/features/allow-java-encodings", true); } catch (ParserConfigurationException e) { Logger log = LoggerFactory.getLogger(this.getClass().getName()); log.error("Error occured during features set up.", e); } try { bf.setNamespaceAware(false); bf.setValidating(false); builder = bf.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new XmlParserException("can not create a XML parser", e); } }
From source file:org.sonar.plugins.php.codesniffer.PhpCodesnifferRulesRepositoryTest.java
/** * Assert xml are similar.//from w w w . j a va2 s. com * * @param xml * the xml * @param xmlFileToFind * the xml file to find * * @throws IOException * Signals that an I/O exception has occurred. * @throws SAXException * the SAX exception * @throws ParserConfigurationException * the parser configuration exception */ private void assertXmlAreSimilar(String xml, String xmlFileToFind) throws IOException, SAXException, ParserConfigurationException { XMLUnit.setIgnoreWhitespace(true); DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance(); bf.setValidating(false); bf.setNamespaceAware(false); bf.setFeature("http://apache.org/xml/features/validation/schema", false); bf.setFeature("http://xml.org/sax/features/external-general-entities", false); bf.setFeature("http://xml.org/sax/features/validation", false); bf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); bf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); bf.setFeature("http://apache.org/xml/features/allow-java-encodings", true); InputStream input = getClass().getResourceAsStream("/org/sonar/plugins/php/codesniffer/" + xmlFileToFind); String xmlToFind = IOUtils.toString(input, "UTF-8"); Diff diff = XMLUnit.compareXML(XMLUnit.buildDocument(bf.newDocumentBuilder(), new StringReader(xml)), XMLUnit.buildDocument(bf.newDocumentBuilder(), new StringReader(xmlToFind))); assertTrue(diff.toString(), diff.similar()); }
From source file:org.springframework.oxm.support.AbstractMarshaller.java
/** * Create a {@code DocumentBuilder} that this marshaller will use for creating * DOM documents when passed an empty {@code DOMSource}. * <p>The resulting {@code DocumentBuilderFactory} is cached, so this method * will only be called once./*ww w.j ava 2s.c o m*/ * @return the DocumentBuilderFactory * @throws ParserConfigurationException if thrown by JAXP methods */ protected DocumentBuilderFactory createDocumentBuilderFactory() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); factory.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities()); return factory; }
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 w w . j ava2 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.carbon.apimgt.core.impl.WSDL20ProcessorImpl.java
/** * {@inheritDoc}/*w w w .j a v a2 s . c o m*/ * Will return true if the provided WSDL is of 2.0 and can be successfully parsed by woden library. */ @Override public boolean init(byte[] wsdlContent) throws APIMgtWSDLException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); WSDLReader reader = getWsdlFactoryInstance().newWSDLReader(); reader.setFeature(WSDLReader.FEATURE_VALIDATION, false); Document dom = builder.parse(new ByteArrayInputStream(wsdlContent)); Element domElement = dom.getDocumentElement(); WSDLSource wsdlSource = reader.createWSDLSource(); wsdlSource.setSource(domElement); wsdlDescription = reader.readWSDL(wsdlSource); canProcess = true; if (log.isDebugEnabled()) { log.debug("Successfully initialized an instance of " + this.getClass().getSimpleName() + " with a single WSDL."); } } catch (WSDLException | ParserConfigurationException | SAXException | IOException e) { //This implementation class cannot process the WSDL. log.debug("Cannot process the WSDL by " + this.getClass().getName(), e); canProcess = false; } return canProcess; }
From source file:org.wso2.carbon.apimgt.handlers.utils.Utils.java
/** * This class build the iot-api-config.xml file. * * @param file The file object of iot-api-config.xml. * @return Document instance of the file * @throws APIMCertificateMGTException//from ww w .j a v a2 s . c om */ private static Document convertToDocument(File file) throws APIMCertificateMGTException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); try { factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder docBuilder = factory.newDocumentBuilder(); return docBuilder.parse(file); } catch (Exception e) { throw new APIMCertificateMGTException( "Error occurred while parsing file, while converting " + "to a org.w3c.dom.Document", e); } }
From source file:org.wso2.carbon.apimgt.impl.SAMLGroupIDExtractorImpl.java
public String getGroupingIdentifiers(String loginResponse) { if (log.isDebugEnabled()) { log.debug("Login response " + loginResponse); }/* www. j ava2 s. c om*/ ByteArrayInputStream samlResponseStream = null; DocumentBuilder docBuilder; String username = ""; String organization = ""; try { APIManagerConfiguration config = ServiceReferenceHolder.getInstance() .getAPIManagerConfigurationService().getAPIManagerConfiguration(); String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI); if (StringUtils.isBlank(claim)) { claim = "http://wso2.org/claims/organization"; } samlResponseStream = getByteArrayInputStream(loginResponse); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); builderFactory.setNamespaceAware(true); docBuilder = builderFactory.newDocumentBuilder(); Document document = docBuilder.parse(samlResponseStream); Element element = document.getDocumentElement(); UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element); Response response = (Response) unmarshaller.unmarshall(element); List<Assertion> assertions = response.getAssertions(); if (assertions != null && assertions.size() > 0) { Subject subject = assertions.get(0).getSubject(); if (subject != null) { if (subject.getNameID() != null) { username = subject.getNameID().getValue(); } } } RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService(); String tenantDomain = MultitenantUtils.getTenantDomain(username); int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId); UserStoreManager manager = realm.getUserStoreManager(); organization = manager.getUserClaimValue(MultitenantUtils.getTenantAwareUsername(username), claim, null); if (log.isDebugEnabled()) { log.debug("User organization " + organization); } if (organization != null) { organization = tenantDomain + "/" + organization.trim(); } } catch (ParserConfigurationException e) { String msg = "Error while parsing SAML Assertion"; log.error(msg, e); } catch (UnmarshallingException e) { String msg = "Error while unmarshalling the SAML Assertion"; log.error(msg, e); } catch (SAXException e) { String msg = "Parsing exception occur while unmarshalling the SAML Assertion"; log.error(msg, e); } catch (IOException e) { String msg = "IO exception happen while unmarshalling the SAML Assertion"; log.error(msg, e); } catch (UserStoreException e) { log.error("User store exception occurred for user" + username, e); } catch (org.wso2.carbon.user.api.UserStoreException e) { log.error("Error while checking user existence for " + username, e); } finally { if (samlResponseStream != null) { try { samlResponseStream.close(); } catch (IOException e) { //Ignore log.error("ERROR_CLOSING_STREAM"); } } } return organization; }
From source file:org.wso2.carbon.apimgt.impl.SAMLGroupIDExtractorImpl.java
@Override public String[] getGroupingIdentifierList(String loginResponse) { if (log.isDebugEnabled()) { log.debug("Login response " + loginResponse); }/*ww w . j av a2 s. co m*/ ByteArrayInputStream samlResponseStream = null; DocumentBuilder docBuilder; String username = ""; String organization = ""; String[] groupIdArray = null; try { APIManagerConfiguration config = ServiceReferenceHolder.getInstance() .getAPIManagerConfigurationService().getAPIManagerConfiguration(); String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI); if (StringUtils.isBlank(claim)) { claim = "http://wso2.org/claims/organization"; } samlResponseStream = getByteArrayInputStream(loginResponse); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); builderFactory.setNamespaceAware(true); docBuilder = builderFactory.newDocumentBuilder(); Document document = docBuilder.parse(samlResponseStream); Element element = document.getDocumentElement(); UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element); Response response = (Response) unmarshaller.unmarshall(element); List<Assertion> assertions = response.getAssertions(); if (assertions != null && assertions.size() > 0) { Subject subject = assertions.get(0).getSubject(); if (subject != null) { if (subject.getNameID() != null) { username = subject.getNameID().getValue(); } } } String isSAML2Enabled = System.getProperty(APIConstants.READ_ORGANIZATION_FROM_SAML_ASSERTION); if (!StringUtils.isEmpty(isSAML2Enabled) && Boolean.parseBoolean(isSAML2Enabled)) { organization = getOrganizationFromSamlAssertion(assertions); } else { RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService(); String tenantDomain = MultitenantUtils.getTenantDomain(username); int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId); UserStoreManager manager = realm.getUserStoreManager(); organization = manager.getUserClaimValue(MultitenantUtils.getTenantAwareUsername(username), claim, null); } if (log.isDebugEnabled()) { log.debug("User organization " + organization); } if (organization != null) { if (organization.contains(",")) { groupIdArray = organization.split(","); for (int i = 0; i < groupIdArray.length; i++) { groupIdArray[i] = groupIdArray[i].toString().trim(); } } else { organization = organization.trim(); groupIdArray = new String[] { organization }; } } else { // If claim is null then returning a empty string groupIdArray = new String[] {}; } } catch (ParserConfigurationException e) { String msg = "Error while parsing SAML Assertion"; log.error(msg, e); } catch (UnmarshallingException e) { String msg = "Error while unmarshalling the SAML Assertion"; log.error(msg, e); } catch (SAXException e) { String msg = "Parsing exception occur while unmarshalling the SAML Assertion"; log.error(msg, e); } catch (IOException e) { String msg = "IO exception happen while unmarshalling the SAML Assertion"; log.error(msg, e); } catch (UserStoreException e) { log.error("User store exception occurred for user" + username, e); } catch (org.wso2.carbon.user.api.UserStoreException e) { log.error("Error while checking user existence for " + username, e); } finally { if (samlResponseStream != null) { try { samlResponseStream.close(); } catch (IOException e) { //Ignore log.error("ERROR_CLOSING_STREAM"); } } } return groupIdArray; }