List of usage examples for javax.xml.parsers DocumentBuilderFactory setNamespaceAware
public void setNamespaceAware(boolean awareness)
From source file:com.xwiki.authentication.sts.STSTokenValidator.java
/** * getDocument(String doc)/* w w w . java 2s.c om*/ * Parse document from string * @param doc String string containing info for document builder parser * @return Document - parsed from input string document */ private static Document getDocument(String doc) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder documentbuilder = factory.newDocumentBuilder(); return documentbuilder.parse(new InputSource(new StringReader(doc))); }
From source file:com.zimbra.cs.service.AutoDiscoverServlet.java
private static String createResponseDoc(String displayName, String email, String serviceUrl) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document xmlDoc = builder.newDocument(); Element root = xmlDoc.createElementNS(NS, "Autodiscover"); root.setAttribute("xmlns", NS); root.setAttribute("xmlns:xsi", XSI_NS); root.setAttribute("xmlns:xsd", XSD_NS); xmlDoc.appendChild(root);// w ww .ja va2 s. c om //Add the response element. Element response = xmlDoc.createElementNS(NS_MOBILE, "Response"); root.appendChild(response); //Add culture to to response Element culture = xmlDoc.createElement("Culture"); culture.appendChild(xmlDoc.createTextNode("en:en")); response.appendChild(culture); //User Element user = xmlDoc.createElement("User"); Element displayNameElm = xmlDoc.createElement("DisplayName"); displayNameElm.appendChild(xmlDoc.createTextNode(displayName)); user.appendChild(displayNameElm); Element emailAddr = xmlDoc.createElement("EMailAddress"); emailAddr.appendChild(xmlDoc.createTextNode(email)); user.appendChild(emailAddr); response.appendChild(user); //Action Element action = xmlDoc.createElement("Action"); Element settings = xmlDoc.createElement("Settings"); Element server = xmlDoc.createElement("Server"); Element type = xmlDoc.createElement("Type"); type.appendChild(xmlDoc.createTextNode("MobileSync")); server.appendChild(type); Element url = xmlDoc.createElement("Url"); url.appendChild(xmlDoc.createTextNode(serviceUrl)); server.appendChild(url); Element name = xmlDoc.createElement("Name"); name.appendChild(xmlDoc.createTextNode(serviceUrl)); server.appendChild(name); settings.appendChild(server); action.appendChild(settings); response.appendChild(action); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(xmlDoc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source, result); writer.flush(); String xml = writer.toString(); writer.close(); //manually generate xmlns for Autodiscover and Response element, this works //for testexchangeconnectivity.com, but iOS and Android don't like Response's xmlns // StringBuilder str = new StringBuilder(); // str.append("<?xml version=\"1.0\"?>\n"); // str.append("<Autodiscover xmlns:xsd=\"").append(XSD_NS).append("\""); // str.append(" xmlns:xsi=\"").append(XSI_NS).append("\""); // str.append(" xmlns=\"").append(NS).append("\">\n"); // int respIndex = xml.indexOf("<Response>"); // str.append("<Response xmlns=\"").append(NS_MOBILE).append("\">"); // str.append(xml.substring(respIndex + "<Response>".length(), xml.length())); // return str.toString(); return "<?xml version=\"1.0\"?>\n" + xml; }
From source file:com.puppycrawl.tools.checkstyle.XDocsPagesTest.java
private static Document getRawXml(String fileName, String code, String unserializedSource) throws ParserConfigurationException { try {//from ww w . j a v a 2 s . c om final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); final DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new InputSource(new StringReader(code))); } catch (IOException | SAXException e) { Assert.fail(fileName + " has invalid xml (" + e.getMessage() + "): " + unserializedSource); } return null; }
From source file:com.zimbra.cs.service.AutoDiscoverServlet.java
private static String createResponseDocForEws(String displayName, String email, String serviceUrl, Account acct) throws Exception { Provisioning prov = Provisioning.getInstance(); Server server = prov.getServer(acct); String cn = server.getCn();/* w w w. jav a 2 s. c o m*/ String name = server.getName(); String acctId = acct.getId(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document xmlDoc = builder.newDocument(); Element root = xmlDoc.createElementNS(NS, "Autodiscover"); root.setAttribute("xmlns", NS); root.setAttribute("xmlns:xsi", XSI_NS); root.setAttribute("xmlns:xsd", XSD_NS); xmlDoc.appendChild(root); //Add the response element. Element response = xmlDoc.createElementNS(NS_OUTLOOK, "Response"); root.appendChild(response); //User Element user = xmlDoc.createElement("User"); Element displayNameElm = xmlDoc.createElement("DisplayName"); displayNameElm.appendChild(xmlDoc.createTextNode(displayName)); user.appendChild(displayNameElm); Element emailAddr = xmlDoc.createElement("EmailAddress"); emailAddr.appendChild(xmlDoc.createTextNode(email)); user.appendChild(emailAddr); Element depId = xmlDoc.createElement("DeploymentId"); depId.appendChild(xmlDoc.createTextNode(acctId)); user.appendChild(depId); response.appendChild(user); //Action Element account = xmlDoc.createElement("Account"); Element acctType = xmlDoc.createElement("AccountType"); acctType.appendChild(xmlDoc.createTextNode("email")); account.appendChild(acctType); response.appendChild(account); Element action = xmlDoc.createElement("Action"); action.appendChild(xmlDoc.createTextNode("settings")); account.appendChild(action); Element protocol = xmlDoc.createElement("Protocol"); account.appendChild(protocol); Element type = xmlDoc.createElement("Type"); type.appendChild(xmlDoc.createTextNode("EXCH")); protocol.appendChild(type); Element ews = xmlDoc.createElement("EwsUrl"); protocol.appendChild(ews); ews.appendChild(xmlDoc.createTextNode(serviceUrl)); Element as = xmlDoc.createElement("ASUrl"); protocol.appendChild(as); as.appendChild(xmlDoc.createTextNode(serviceUrl)); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(xmlDoc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source, result); writer.flush(); String xml = writer.toString(); writer.close(); return "<?xml version=\"1.0\"?>\n" + xml; }
From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java
/** * TransCellAccessToken????.//from w w w. j a va 2 s . co m * @param token * @return TransCellAccessToken(?) * @throws AbstractOAuth2Token.TokenParseException ? * @throws AbstractOAuth2Token.TokenDsigException ??? * @throws AbstractOAuth2Token.TokenRootCrtException CA? */ public static TransCellAccessToken parse(final String token) throws AbstractOAuth2Token.TokenParseException, AbstractOAuth2Token.TokenDsigException, AbstractOAuth2Token.TokenRootCrtException { try { byte[] samlBytes = DcCoreUtils.decodeBase64Url(token); ByteArrayInputStream bais = new ByteArrayInputStream(samlBytes); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // ???????????? throw new RuntimeException(e); } Document doc = builder.parse(bais); Element assertion = doc.getDocumentElement(); Element issuer = (Element) (doc.getElementsByTagName("Issuer").item(0)); Element subject = (Element) (assertion.getElementsByTagName("Subject").item(0)); Element subjectNameID = (Element) (subject.getElementsByTagName("NameID").item(0)); String id = assertion.getAttribute("ID"); String issuedAtStr = assertion.getAttribute("IssueInstant"); DateTime dt = new DateTime(issuedAtStr); NodeList audienceList = assertion.getElementsByTagName("Audience"); Element aud1 = (Element) (audienceList.item(0)); String target = aud1.getTextContent(); String schema = null; if (audienceList.getLength() > 1) { Element aud2 = (Element) (audienceList.item(1)); schema = aud2.getTextContent(); } List<Role> roles = new ArrayList<Role>(); NodeList attrList = assertion.getElementsByTagName("AttributeValue"); for (int i = 0; i < attrList.getLength(); i++) { Element attv = (Element) (attrList.item(i)); roles.add(new Role(new URL(attv.getTextContent()))); } NodeList nl = assertion.getElementsByTagName("Signature"); if (nl.getLength() == 0) { throw new TokenParseException("Cannot find Signature element"); } Element signatureElement = (Element) nl.item(0); // ???????TokenDsigException?? // Create a DOMValidateContext and specify a KeySelector // and document context. X509KeySelector x509KeySelector = new X509KeySelector(issuer.getTextContent()); DOMValidateContext valContext = new DOMValidateContext(x509KeySelector, signatureElement); // Unmarshal the XMLSignature. XMLSignature signature; try { signature = xmlSignatureFactory.unmarshalXMLSignature(valContext); } catch (MarshalException e) { throw new TokenDsigException(e.getMessage(), e); } // CA?? try { x509KeySelector.readRoot(x509RootCertificateFileNames); } catch (CertificateException e) { // CA????????500 throw new TokenRootCrtException(e.getMessage(), e); } // Validate the XMLSignature x509. boolean coreValidity; try { coreValidity = signature.validate(valContext); } catch (XMLSignatureException e) { if (e.getCause().getClass() == new KeySelectorException().getClass()) { throw new TokenDsigException(e.getCause().getMessage(), e.getCause()); } throw new TokenDsigException(e.getMessage(), e); } // http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation // Check core validation status. if (!coreValidity) { // ?? boolean isDsigValid; try { isDsigValid = signature.getSignatureValue().validate(valContext); } catch (XMLSignatureException e) { throw new TokenDsigException(e.getMessage(), e); } if (!isDsigValid) { throw new TokenDsigException("Failed signature validation"); } // Iterator i = signature.getSignedInfo().getReferences().iterator(); for (int j = 0; i.hasNext(); j++) { boolean refValid; try { refValid = ((Reference) i.next()).validate(valContext); } catch (XMLSignatureException e) { throw new TokenDsigException(e.getMessage(), e); } if (!refValid) { throw new TokenDsigException("Failed to validate reference [" + j + "]"); } } throw new TokenDsigException("Signature failed core validation. unkwnon reason."); } return new TransCellAccessToken(id, dt.getMillis(), issuer.getTextContent(), subjectNameID.getTextContent(), target, roles, schema); } catch (UnsupportedEncodingException e) { throw new TokenParseException(e.getMessage(), e); } catch (SAXException e) { throw new TokenParseException(e.getMessage(), e); } catch (IOException e) { throw new TokenParseException(e.getMessage(), e); } }
From source file:com.github.anba.es6draft.util.Resources.java
/** * Reads the xml-structure from {@link Reader} and returns the corresponding {@link Document}. *///from w w w .ja v a 2 s.c o m public static Document xml(Reader xml) throws IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // turn off any validation or namespace features factory.setNamespaceAware(false); factory.setValidating(false); List<String> features = Arrays.asList("http://xml.org/sax/features/namespaces", "http://xml.org/sax/features/validation", "http://apache.org/xml/features/nonvalidating/load-dtd-grammar", "http://apache.org/xml/features/nonvalidating/load-external-dtd"); for (String feature : features) { try { factory.setFeature(feature, false); } catch (ParserConfigurationException e) { // ignore invalid feature names } } try { return factory.newDocumentBuilder().parse(new InputSource(xml)); } catch (ParserConfigurationException | SAXException e) { throw new IOException(e); } }
From source file:de.mpg.escidoc.services.test.search.TestBase.java
/** * Parse the given xml String into a org.w3c.dom.Document. * //ww w .jav a2 s . c o m * @param xml The xml String * @param namespaceAwareness Enable/disable namespace awareness (default is false) * @return The Document * @throws Exception */ protected static Document getDocument(final String xml, final boolean namespaceAwareness) throws Exception { String charset = "UTF-8"; Document result = null; DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(namespaceAwareness); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); result = docBuilder.parse(new ByteArrayInputStream(xml.getBytes(charset))); result.getDocumentElement().normalize(); return result; }
From source file:io.personium.common.auth.token.TransCellAccessToken.java
/** * TransCellAccessToken????.//from www . j ava 2 s. c o m * @param token * @return TransCellAccessToken(?) * @throws AbstractOAuth2Token.TokenParseException ? * @throws AbstractOAuth2Token.TokenDsigException ??? * @throws AbstractOAuth2Token.TokenRootCrtException CA? */ public static TransCellAccessToken parse(final String token) throws AbstractOAuth2Token.TokenParseException, AbstractOAuth2Token.TokenDsigException, AbstractOAuth2Token.TokenRootCrtException { try { byte[] samlBytes = PersoniumCoreUtils.decodeBase64Url(token); ByteArrayInputStream bais = new ByteArrayInputStream(samlBytes); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // ???????????? throw new RuntimeException(e); } Document doc = builder.parse(bais); Element assertion = doc.getDocumentElement(); Element issuer = (Element) (doc.getElementsByTagName("Issuer").item(0)); Element subject = (Element) (assertion.getElementsByTagName("Subject").item(0)); Element subjectNameID = (Element) (subject.getElementsByTagName("NameID").item(0)); String id = assertion.getAttribute("ID"); String issuedAtStr = assertion.getAttribute("IssueInstant"); DateTime dt = new DateTime(issuedAtStr); NodeList audienceList = assertion.getElementsByTagName("Audience"); Element aud1 = (Element) (audienceList.item(0)); String target = aud1.getTextContent(); String schema = null; if (audienceList.getLength() > 1) { Element aud2 = (Element) (audienceList.item(1)); schema = aud2.getTextContent(); } List<Role> roles = new ArrayList<Role>(); NodeList attrList = assertion.getElementsByTagName("AttributeValue"); for (int i = 0; i < attrList.getLength(); i++) { Element attv = (Element) (attrList.item(i)); roles.add(new Role(new URL(attv.getTextContent()))); } NodeList nl = assertion.getElementsByTagName("Signature"); if (nl.getLength() == 0) { throw new TokenParseException("Cannot find Signature element"); } Element signatureElement = (Element) nl.item(0); // ???????TokenDsigException?? // Create a DOMValidateContext and specify a KeySelector // and document context. X509KeySelector x509KeySelector = new X509KeySelector(issuer.getTextContent()); DOMValidateContext valContext = new DOMValidateContext(x509KeySelector, signatureElement); // Unmarshal the XMLSignature. XMLSignature signature; try { signature = xmlSignatureFactory.unmarshalXMLSignature(valContext); } catch (MarshalException e) { throw new TokenDsigException(e.getMessage(), e); } // CA?? try { x509KeySelector.readRoot(x509RootCertificateFileNames); } catch (CertificateException e) { // CA????????500 throw new TokenRootCrtException(e.getMessage(), e); } // Validate the XMLSignature x509. boolean coreValidity; try { coreValidity = signature.validate(valContext); } catch (XMLSignatureException e) { if (e.getCause().getClass() == new KeySelectorException().getClass()) { throw new TokenDsigException(e.getCause().getMessage(), e.getCause()); } throw new TokenDsigException(e.getMessage(), e); } // http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation // Check core validation status. if (!coreValidity) { // ?? boolean isDsigValid; try { isDsigValid = signature.getSignatureValue().validate(valContext); } catch (XMLSignatureException e) { throw new TokenDsigException(e.getMessage(), e); } if (!isDsigValid) { throw new TokenDsigException("Failed signature validation"); } // Iterator i = signature.getSignedInfo().getReferences().iterator(); for (int j = 0; i.hasNext(); j++) { boolean refValid; try { refValid = ((Reference) i.next()).validate(valContext); } catch (XMLSignatureException e) { throw new TokenDsigException(e.getMessage(), e); } if (!refValid) { throw new TokenDsigException("Failed to validate reference [" + j + "]"); } } throw new TokenDsigException("Signature failed core validation. unkwnon reason."); } return new TransCellAccessToken(id, dt.getMillis(), issuer.getTextContent(), subjectNameID.getTextContent(), target, roles, schema); } catch (UnsupportedEncodingException e) { throw new TokenParseException(e.getMessage(), e); } catch (SAXException e) { throw new TokenParseException(e.getMessage(), e); } catch (IOException e) { throw new TokenParseException(e.getMessage(), e); } }
From source file:com.ephesoft.dcma.util.XMLUtil.java
private static DocumentBuilder getBuilder(boolean isXPATH) throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); if (isXPATH) { factory.setNamespaceAware(true); }//from w w w . j ava 2s. c o m return factory.newDocumentBuilder(); }
From source file:module.signature.util.XAdESValidator.java
/** * @author joantune/*w w w . ja v a 2 s .c o m*/ * * Makes sure that the document which was signed is equal to the one * that was sent. It also checks to see if the signers are the * correct persons or not NOTE: It does note validate the validity * of the signature itself, only that what was sent was the same * that was receveived. * * To validate, see: * * @see XAdESValidator#validateXMLSignature(byte[]) * @param receivedContent * the received signature * @param originalContent * the byte array of what was sent to the signer * @param usersPermitted * Users that are permitted to be on the signature * @param usersExcluded * Users which must not be on the list of signers, or null/empty * list if none is excluded * @param allUsersPermittedShouldBeThere * if true, all of the users of <i>usersPermitted</i> must be on * the list of signers * @throws SignatureDataException * if any error has been observed, thus the validation fails */ public static void validateSentAndReceivedContent(String receivedContent, byte[] originalContent, Set<User> usersPermitted, Set<User> usersExcluded, boolean allUsersPermittedShouldBeThere) throws SignatureDataException { //let's validate the content. That is, what we received against what we sent and make sure it hasn't changed if (schemaXSD == null) { loadXAdESSchemas(); } //we know that we are receiving a XaDES-T signature boolean validSignature = false; try { //let's extract the signatureContent and compare it against what we sent //let's decode and interpret the XML file //making the objects to interpret the XML document DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder parser = dbf.newDocumentBuilder(); ErrorHandler eh = new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } @Override public void error(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } }; //let's decode the document byte[] signatureDecoded = Base64.decode(receivedContent); ByteArrayInputStream bais = new ByteArrayInputStream(signatureDecoded); // let's parse the document parser.setErrorHandler(eh); Document document = parser.parse(bais); NodeList fileContentNodeList = document.getElementsByTagName("FileContent"); //Even if we have more than one signature, we should only have one file content!! if not, let's throw an exception here if (fileContentNodeList.getLength() > 1) { throw new SignatureDataException("too.many.file.content.nodes.malformed.signature.document", true, null); } if (fileContentNodeList.getLength() < 1) { throw new SignatureDataException("no.file.content.nodes.in.received.signature", true, null); } Node fileContentNode = fileContentNodeList.item(0).getFirstChild(); //now finally, we can compare the content of this node with the one that we generated //debug lines: byte[] receivedDecodedByteContent = Base64.decode(fileContentNode.getNodeValue()); //ok, so let's parse this again to strings and then we can better compare them and maybe know exactly why they are different String originalEncodedContent = Base64.encodeBytes(originalContent); String originalDecodedContent = new String(Base64.decode(originalEncodedContent), Charset.forName("UTF-8")); String receivedDecodedContent = new String(receivedDecodedByteContent, Charset.forName("UTF-8")); //now let's //make sure the signature is from the right person //TODO uncomment the following line: // validateSigner(document, usersPermitted, usersExcluded, allUsersPermittedShouldBeThere); if (!StringUtils.equals(StringUtils.trimToEmpty(originalDecodedContent), StringUtils.trimToEmpty(receivedDecodedContent))) { // } throw new SignatureDataException("signature.content.sent.and.received.are.different"); } else { validSignature = true; } //TODO FENIX-196 assert if one should be notified of these errors } catch (IOException e1) { // e1.printStackTrace(); throw new SignatureDataException("error.decoding.base64.sig", e1); } catch (SAXException e) { // e.printStackTrace(); throw new SignatureDataException("error.parsing.received.signature.file", e); } catch (ParserConfigurationException e) { // e.printStackTrace(); throw new SignatureDataException("error.parsing.received.signature.file.parser.configuration", e); } if (!validSignature) { throw new SignatureDataException("invalid.signature.content"); } }