List of usage examples for org.w3c.dom Document importNode
public Node importNode(Node importedNode, boolean deep) throws DOMException;
From source file:de.mpg.escidoc.services.common.util.Util.java
public static Node querySSRNId(String conePersonUrl) { DocumentBuilder documentBuilder; HttpClient client = new HttpClient(); try {//from ww w . j a v a 2s.c o m documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("cone"); document.appendChild(element); GetMethod detailMethod = new GetMethod(conePersonUrl + "?format=rdf"); ProxyHelper.setProxy(client, conePersonUrl); client.executeMethod(detailMethod); if (detailMethod.getStatusCode() == 200) { Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream()); element.appendChild(document.importNode(details.getFirstChild(), true)); return document; } else { logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n" + detailMethod.getResponseBodyAsString()); return null; } } catch (Exception e) { logger.error("Error querying CoNE service. This is normal during unit tests. " + "Otherwise it should be clarified if any measures have to be taken."); return null; } }
From source file:com.enonic.esl.xml.XMLTool.java
public static Document createDocument(Element root) { Document doc = createDocument(); doc.appendChild(doc.importNode(root, true)); return doc;/*w w w .ja v a2s . c om*/ }
From source file:com.enonic.esl.xml.XMLTool.java
public static void replaceElement(Element oldElem, Element newElem) { Document doc = oldElem.getOwnerDocument(); Node importedNew = doc.importNode(newElem, true); oldElem.getParentNode().replaceChild(importedNew, oldElem); }
From source file:fr.cls.atoll.motu.processor.wps.StringList.java
public static void readXML(Element object) { // XMLReader parser = XMLReaderFactory.createXMLReader(); // InputSource inputSource = new InputSource() // parser.parse(input); try {/*from w w w. j ava 2 s . c om*/ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Source src = new DOMSource(object); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer tformer = tFactory.newTransformer(); Result result = new StreamResult(System.out); tformer.transform(src, result); // doc.getDocumentElement().normalize(); // System.out.println("Root element " + doc.getDocumentElement().getNodeName()); // NodeList nodeLst = doc.getElementsByTagName("employee"); // System.out.println("Information of all employees"); Element copyElement = (Element) object.cloneNode(true); Document doc = db.newDocument(); Node node = doc.importNode(copyElement, true); NodeList nodeList = doc.getElementsByTagName("Arc"); System.out.println(doc.getElementsByTagName("Curve")); // Node node = object; } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient.java
/** * Creates a mandate.// w w w. j a v a2 s .c o m * * @param reqElem the request. * @return a SZR-gateway response containing the result * @throws SZRGWException when an error occurs creating the mandate. */ public CreateMandateResponse createMandateResponse(Element reqElem) throws SZRGWClientException { //Logger.info("Connecting to SZR-gateway."); try { if (address == null) { throw new NullPointerException("Address (SZR-gateway ServiceURL) must not be null."); } HttpClient client = HttpClientWithProxySupport.getHttpClient(); PostMethod method = new PostMethod(address); method.setRequestHeader("SOAPAction", ""); // ssl settings if (sSLSocketFactory != null) { SZRGWSecureSocketFactory fac = new SZRGWSecureSocketFactory(sSLSocketFactory); Protocol.registerProtocol("https", new Protocol("https", fac, 443)); } // create soap body Element soapBody = getSOAPBody(); Document doc = soapBody.getOwnerDocument(); soapBody.appendChild(doc.importNode(reqElem, true)); Element requestElement = soapBody.getOwnerDocument().getDocumentElement(); //ParepUtils.saveElementToFile(requestElement, new File("c:/temp/szrRequest.xml")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ParepUtils.serializeElementAsDocument(requestElement, bos); method.setRequestBody(new ByteArrayInputStream(bos.toByteArray())); client.executeMethod(method); CreateMandateResponse response = new CreateMandateResponse(); bos = new ByteArrayOutputStream(); doc = ParepUtils.readDocFromIs(method.getResponseBodyAsStream()); //ParepUtils.saveElementToFile(doc.getDocumentElement(), new File("c:/temp/szrResponse.xml")); response.parse(doc.getDocumentElement()); return response; } catch (Exception e) { //e.printStackTrace(); throw new SZRGWClientException(e); } }
From source file:org.bigtester.ate.model.data.TestDatabaseInitializer.java
/** * Combine init xml files./*from w ww.j a v a 2 s . c o m*/ * * @return the input stream */ private InputStream combineInitXmlFiles() { if (getInitXmlFiles().isEmpty()) { throw GlobalUtils.createNotInitializedException("xml data files are not populated"); } else { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder dbuilder; try { dbuilder = dbf.newDocumentBuilder(); Document retDoc = dbuilder.newDocument(); Document doc0; doc0 = dbuilder.parse(getInitXmlFiles().get(0)); Node firstDataset = retDoc.importNode(doc0.getFirstChild(), true); retDoc.appendChild(firstDataset); for (int i = 1; i < getInitXmlFiles().size(); i++) { Document doc2 = dbuilder.parse(getInitXmlFiles().get(i)); Node root = doc2.getFirstChild(); NodeList list = root.getChildNodes(); for (int index = 0; index < list.getLength(); index++) { Node copiedNode = retDoc.importNode(list.item(index), true); retDoc.getDocumentElement().appendChild(copiedNode); } } DOMSource source = new DOMSource(retDoc); StringWriter xmlAsWriter = new StringWriter(); StreamResult result = new StreamResult(xmlAsWriter); TransformerFactory.newInstance().newTransformer().transform(source, result); // write changes return new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8")); } catch (SAXException | IOException | ParserConfigurationException e) { throw GlobalUtils.createNotInitializedException("xml data files are not correctly populated", e); } catch (TransformerException | TransformerFactoryConfigurationError transE) { throw GlobalUtils.createInternalError("xml transformer error!", transE); } } }
From source file:com.adaptris.util.text.xml.ReplaceNode.java
@Override public Document merge(Document original, Document newDoc) throws Exception { if (StringUtils.isEmpty(getXpathToNode())) { throw new Exception("No xpath node configured"); }//from w w w . j av a 2s . com Document resultDoc = original; Node node = createXPath().selectSingleNode(resultDoc, getXpathToNode()); if (node == null) { throw new Exception("Failed to resolve " + getXpathToNode()); } Node parent = node.getParentNode(); if (parent == null) { throw new Exception("Parent of " + getXpathToNode() + " is null"); } Node replacement = resultDoc.importNode(newDoc.getDocumentElement(), true); parent.replaceChild(replacement, node); return resultDoc; }
From source file:eu.eidas.encryption.SAMLAuthnResponseEncrypter.java
@Nonnull private Response performEncryption(@Nonnull Response samlResponseEncryptee, @Nonnull Credential credential) throws EncryptionException { try {// w w w . j a v a 2 s . c om // Set Data Encryption parameters EncryptionParameters encParams = new EncryptionParameters(); encParams.setAlgorithm(getDataEncAlgorithm()); // Set Key Encryption parameters KeyEncryptionParameters kekParams = new KeyEncryptionParameters(); kekParams.setEncryptionCredential(credential); kekParams.setAlgorithm(getKeyEncAlgorithm()); KeyInfoGeneratorFactory kigf = Configuration.getGlobalSecurityConfiguration() .getKeyInfoGeneratorManager().getDefaultManager().getFactory(credential); kekParams.setKeyInfoGenerator(kigf.newInstance()); // Setup Open SAML Encrypter Encrypter encrypter = new Encrypter(encParams, kekParams); encrypter.setKeyPlacement(Encrypter.KeyPlacement.INLINE); if (getJcaProviderName() != null) { encrypter.setJCAProviderName(getJcaProviderName()); } for (Assertion assertion : samlResponseEncryptee.getAssertions()) { if (assertion.getDOM() == null) { OpenSamlHelper.marshallToDom(assertion); } manageNamespaces(assertion); } List<EncryptedAssertion> encryptedAssertions = new ArrayList<>(); for (Assertion assertion : samlResponseEncryptee.getAssertions()) { EncryptedAssertion encryptedAssertion = encrypter.encrypt(assertion); encryptedAssertions.add(encryptedAssertion); } Element previousDom = samlResponseEncryptee.getDOM(); if (null == previousDom) { previousDom = OpenSamlHelper.marshallToDom(samlResponseEncryptee); } Document ownerDocument = previousDom.getOwnerDocument(); // Deep copy the previous DOM into a new one using importNode() Document newDocument = DocumentBuilderFactoryUtil.newDocument(); Node copiedRoot = newDocument.importNode(ownerDocument.getDocumentElement(), true); newDocument.appendChild(copiedRoot); Element newRootElement = newDocument.getDocumentElement(); NodeList assertionList = newRootElement.getElementsByTagNameNS( Assertion.DEFAULT_ELEMENT_NAME.getNamespaceURI(), Assertion.DEFAULT_ELEMENT_NAME.getLocalPart()); // Replace the encrypted assertions by the decrypted assertions in the new DOM tree: for (int i = 0, n = assertionList.getLength(); i < n; i++) { Node assertion = assertionList.item(i); EncryptedAssertion encryptedAssertion = encryptedAssertions.get(i); Element encryptedAssertionDOM = encryptedAssertion.getDOM(); Node copiedEncryptedAssertion; if (null == encryptedAssertionDOM) { encryptedAssertionDOM = OpenSamlHelper.marshallToDom(encryptedAssertion); } // we may use adoptNode() instead of importNode() because the unmarshaller rectifies the ID-ness: copiedEncryptedAssertion = newDocument.adoptNode(encryptedAssertionDOM); newRootElement.replaceChild(copiedEncryptedAssertion, assertion); } // Finally unmarshall the updated DOM into a new XMLObject graph: // The unmarshaller rectifies the ID-ness: // See org.opensaml.saml1.core.impl.AssertionUnmarshaller.unmarshall() // See org.opensaml.saml2.core.impl.AssertionUnmarshaller.processAttribute() // And org.opensaml.saml1.core.impl.ResponseAbstractTypeUnmarshaller.unmarshall() // And org.opensaml.saml2.core.impl.StatusResponseTypeUnmarshaller.processAttribute() Response encryptedResponse = (Response) OpenSamlHelper.unmarshallFromDom(newDocument); if (LOGGER.isTraceEnabled()) { try { LOGGER.trace("SAML Response XMLObject encrypted: " + EidasStringUtil.toString(DocumentBuilderFactoryUtil.marshall(newDocument, true))); } catch (TransformerException e) { LOGGER.error(e.getMessage(), e); } } return encryptedResponse; } catch (org.opensaml.xml.encryption.EncryptionException | ParserConfigurationException | MarshallException | UnmarshallException e) { throw new EncryptionException(e); } }
From source file:at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient.java
/** * Gets a identity link.// w w w . j a va 2 s. com * * @param reqElem the request. * @return a SZR-gateway response containing the result * @throws SZRGWException when an error occurs creating the mandate. */ public CreateIdentityLinkResponse createIdentityLinkResponse(Element reqElem) throws SZRGWClientException { try { if (address == null) { throw new NullPointerException("Address (SZR-gateway ServiceURL) must not be null."); } HttpClient client = new HttpClient(); PostMethod method = new PostMethod(address); method.setRequestHeader("SOAPAction", ""); // ssl settings if (sSLSocketFactory != null) { SZRGWSecureSocketFactory fac = new SZRGWSecureSocketFactory(sSLSocketFactory); Protocol.registerProtocol("https", new Protocol("https", fac, 443)); } // create soap body Element soapBody = getSOAPBody(); Document doc = soapBody.getOwnerDocument(); soapBody.appendChild(doc.importNode(reqElem, true)); Element requestElement = soapBody.getOwnerDocument().getDocumentElement(); //ParepUtils.saveElementToFile(requestElement, new File("c:/temp/szrRequest.xml")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ParepUtils.serializeElementAsDocument(requestElement, bos); method.setRequestBody(new ByteArrayInputStream(bos.toByteArray())); client.executeMethod(method); CreateIdentityLinkResponse response = new CreateIdentityLinkResponse(); bos = new ByteArrayOutputStream(); doc = ParepUtils.readDocFromIs(method.getResponseBodyAsStream()); //ParepUtils.saveElementToFile(doc.getDocumentElement(), new File("c:/temp/szrResponse.xml")); NodeList list = doc.getElementsByTagNameNS(SZRGWConstants.SZRGW_REQUEST_NS, "ErrorResponse"); if (list.getLength() > 0) { // set error response list = doc.getElementsByTagNameNS(SZRGWConstants.SZRGW_REQUEST_NS, "Info"); String error = DOMUtils.getText(list.item(0)); response.setError(error); } else { // set assertion DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document newdoc = builder.newDocument(); Element nameSpaceNode = newdoc.createElement("NameSpaceNode"); nameSpaceNode.setAttribute("xmlns:" + Constants.DSIG_PREFIX, Constants.DSIG_NS_URI); nameSpaceNode.setAttribute("xmlns:" + Constants.SAML_PREFIX, Constants.SAML_NS_URI); Element samlAssertion = (Element) XPathAPI.selectSingleNode(doc, "//saml:Assertion[1]", nameSpaceNode); if (samlAssertion == null) throw new SZRGWClientException("Could not found a saml:Assertion element in response."); else response.setAssertion(samlAssertion); } return response; } catch (Exception e) { throw new SZRGWClientException(e); } }
From source file:be.fedict.eid.idp.sp.protocol.ws_federation.AuthenticationResponseProcessor.java
/** * Process the incoming WS-Federation response. * // w w w.ja v a 2s. co m * @param recipient * recipient, should match SAML v2.0 assertions's * AudienceRestriction * @param context * optional expected context * @param requiresResponseSignature * do we expect a signature on the response or not, or * <code>null</code> if to be retrieved from the * {@link AuthenticationResponseService}. * @param request * the HTTP servlet request that holds the SAML2 response. * @return the {@link be.fedict.eid.idp.common.saml2.AuthenticationResponse} * @throws AuthenticationResponseProcessorException * case something went wrong */ public AuthenticationResponse process(String recipient, String context, Boolean requiresResponseSignature, HttpServletRequest request) throws AuthenticationResponseProcessorException { DateTime now = new DateTime(); SecretKey secretKey = null; PrivateKey privateKey = null; int maxOffset = 5; boolean expectAssertionSigned = null != requiresResponseSignature ? requiresResponseSignature : false; ValidationService validationService = null; if (null != this.service) { secretKey = this.service.getAttributeSecretKey(); privateKey = this.service.getAttributePrivateKey(); maxOffset = this.service.getMaximumTimeOffset(); expectAssertionSigned = this.service.requiresResponseSignature(); validationService = this.service.getValidationService(); } // force UTF8 encoding! try { request.setCharacterEncoding("UTF8"); } catch (UnsupportedEncodingException e) { throw new AuthenticationResponseProcessorException(e); } // check wa String wa = request.getParameter("wa"); if (null == wa) { throw new AuthenticationResponseProcessorException("Missing \"wa\" param."); } if (!wa.equals("wsignin1.0")) { throw new AuthenticationResponseProcessorException("Unexpected value for \"wa\" param."); } // validate optional ctx validateContext(context, request.getParameter("wctx")); // get wresult String wresult = request.getParameter("wresult"); LOG.debug("wresult=\"" + wresult + "\""); if (null == wresult) { throw new AuthenticationResponseProcessorException("Missing \"wresult\" param."); } Document responseDocument = Saml2Util.parseDocument(wresult); RequestSecurityTokenResponseCollection rstCollections = Saml2Util .unmarshall(responseDocument.getDocumentElement()); if (rstCollections.getRequestSecurityTokenResponses().size() != 1) { throw new AuthenticationResponseProcessorException("Expected exactly 1 RequestSecurityTokenResponse"); } RequestSecurityTokenResponse rstResponse = rstCollections.getRequestSecurityTokenResponses().get(0); // context validateContext(context, rstResponse.getContext()); // tokentype validateTokenType(rstResponse); // requesttype validateRequestType(rstResponse); // keytype validateKeyType(rstResponse); // validate security token Assertion assertion = validateSecurityToken(rstResponse); // validate assertion AuthenticationResponse authenticationResponse; try { authenticationResponse = Saml2Util.validateAssertion(assertion, now, maxOffset, recipient, recipient, null, secretKey, privateKey); } catch (AssertionValidationException e) { throw new AuthenticationResponseProcessorException(e); } // check if SP expects a signature and if there is one if (null == assertion.getSignature() && expectAssertionSigned) { throw new AuthenticationResponseProcessorException("Expected a signed assertion but was not so! "); } // validate assertion's signature if any if (null != assertion.getSignature()) { try { // fix for recent versions of Apache xmlsec assertion.getDOM().setIdAttribute("ID", true); List<X509Certificate> certificateChain = Saml2Util.validateSignature(assertion.getSignature()); if (null != validationService) { // have to reparse the document here NodeList assertionNodeList = Saml2Util.parseDocument(wresult) .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Assertion"); LOG.debug("number of SAML2 assertions: " + assertionNodeList.getLength()); if (1 != assertionNodeList.getLength()) { throw new AuthenticationResponseProcessorException("missing SAML2 Assertion"); } Element assertionElement = (Element) assertionNodeList.item(0); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document tokenDocument = documentBuilder.newDocument(); Node assertionTokenNode = tokenDocument.importNode(assertionElement, true); tokenDocument.appendChild(assertionTokenNode); String validationServiceLocation = validationService.getLocation(); String expectedAudience = validationService.getExpectedAudience(); SecurityTokenServiceClient securityTokenServiceClient = new SecurityTokenServiceClient( validationServiceLocation); securityTokenServiceClient.validateToken(tokenDocument.getDocumentElement(), expectedAudience); } if (null != this.service) { this.service.validateServiceCertificate(authenticationResponse.getAuthenticationPolicy(), certificateChain); } } catch (CertificateException e) { throw new AuthenticationResponseProcessorException(e); } catch (ValidationException e) { throw new AuthenticationResponseProcessorException(e); } catch (Exception e) { if ("javax.ejb.EJBException".equals(e.getClass().getName())) { Exception exception; try { Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException", new Class[] {}); exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {}); } catch (Exception e2) { LOG.debug("error: " + e.getMessage(), e); throw new AuthenticationResponseProcessorException( "error retrieving the root cause: " + e2.getMessage()); } throw new AuthenticationResponseProcessorException("Validation exception: " + (null != exception ? exception.getMessage() : e.getMessage())); } throw new AuthenticationResponseProcessorException(e); } } return authenticationResponse; }