List of usage examples for javax.xml.soap SOAPPart getEnvelope
public abstract SOAPEnvelope getEnvelope() throws SOAPException;
From source file:it.cnr.icar.eric.common.SOAPMessenger.java
/** Send a SOAP request to the registry server. Main entry point for * this class. If credentials have been set on the registry connection, * they will be used to sign the request. * * @param requestString//from w w w . ja v a 2 s .com * String that will be placed in the body of the * SOAP message to be sent to the server * * @param attachments * HashMap consisting of entries each of which * corresponds to an attachment where the entry key is the ContentId * and the entry value is a javax.activation.DataHandler of the * attachment. A parameter value of null means no attachments. * * @return * RegistryResponseHolder that represents the response from the * server */ @SuppressWarnings("unchecked") public RegistryResponseHolder sendSoapRequest(String requestString, Map<?, ?> attachments) throws JAXRException { boolean logRequests = Boolean.valueOf( CommonProperties.getInstance().getProperty("eric.common.soapMessenger.logRequests", "false")) .booleanValue(); if (logRequests) { PrintStream requestLogPS = null; try { requestLogPS = new PrintStream( new FileOutputStream(java.io.File.createTempFile("SOAPMessenger_requestLog", ".xml"))); requestLogPS.println(requestString); } catch (IOException e) { e.printStackTrace(); } finally { if (requestLogPS != null) { requestLogPS.close(); } } } // ================================================================= // // Remove the XML Declaration, if any // if (requestString.startsWith("<?xml")) { // requestString = requestString.substring(requestString.indexOf("?>")+2).trim(); // } // // StringBuffer soapText = new StringBuffer( // "<soap-env:Envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\">"); // // soapText.append("<soap-env:Header>\n"); // // tell server about our superior SOAP Fault capabilities // soapText.append("<"); // soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName); // soapText.append(" xmlns='"); // soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_Namespace); // soapText.append("'>"); // soapText.append(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes); // soapText.append("</"); // soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName); // soapText.append(">\n"); // soapText.append("</soap-env:Header>\n"); // soapText.append("<soap-env:Body>\n"); // soapText.append(requestString); // soapText.append("</soap-env:Body>"); // soapText.append("</soap-env:Envelope>"); MessageFactory messageFactory; SOAPMessage message = null; SOAPPart sp = null; SOAPEnvelope se = null; SOAPBody sb = null; SOAPHeader sh = null; if (log.isTraceEnabled()) { log.trace("requestString=\"" + requestString + "\""); } try { messageFactory = MessageFactory.newInstance(); message = messageFactory.createMessage(); sp = message.getSOAPPart(); se = sp.getEnvelope(); sb = se.getBody(); sh = se.getHeader(); /* * <soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"> * <soap-env:Header> * <capabilities xmlns="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</capabilities> * * change with explicit namespace * <ns1:capabilities xmlns:ns1="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</ns1:capabilities> */ SOAPHeaderElement capabilityElement = sh .addHeaderElement(se.createName(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName, "ns1", BindingUtility.SOAP_CAPABILITY_HEADER_Namespace)); // capabilityElement.addAttribute( // se.createName("xmlns"), // BindingUtility.SOAP_CAPABILITY_HEADER_Namespace); capabilityElement.setTextContent(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes); /* * body */ // Remove the XML Declaration, if any if (requestString.startsWith("<?xml")) { requestString = requestString.substring(requestString.indexOf("?>") + 2).trim(); } // Generate DOM Document from request xml string DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); InputStream stream = new ByteArrayInputStream(requestString.getBytes("UTF-8")); // Inject request into body sb.addDocument(builderFactory.newDocumentBuilder().parse(stream)); // Is it never the case that there attachments but no credentials if ((attachments != null) && !attachments.isEmpty()) { addAttachments(message, attachments); } if (credentialInfo == null) { throw new JAXRException(resourceBundle.getString("message.credentialInfo")); } WSS4JSecurityUtilSAML.signSOAPEnvelopeOnClientSAML(se, credentialInfo); SOAPMessage response = send(message); // Check to see if the session has expired // by checking for an error response code // TODO: what error code to we look for? if (isSessionExpired(response)) { credentialInfo.sessionId = null; // sign the SOAPMessage this time // TODO: session - add method to do the signing // signSOAPMessage(msg); // send signed message // SOAPMessage response = send(msg); } // Process the main SOAPPart of the response //check for soapfault and throw RegistryException SOAPFault fault = response.getSOAPBody().getFault(); if (fault != null) { throw createRegistryException(fault); } Reader reader = processResponseBody(response, "Response"); RegistryResponseType ebResponse = null; try { Object obj = BindingUtility.getInstance().getJAXBContext().createUnmarshaller() .unmarshal(new InputSource(reader)); if (obj instanceof JAXBElement<?>) // if Element: take ComplexType from Element obj = ((JAXBElement<RegistryResponseType>) obj).getValue(); ebResponse = (RegistryResponseType) obj; } catch (Exception x) { log.error(CommonResourceBundle.getInstance().getString("message.FailedToUnmarshalServerResponse"), x); throw new JAXRException(resourceBundle.getString("message.invalidServerResponse")); } // Process the attachments of the response if any HashMap<String, Object> responseAttachments = processResponseAttachments(response); return new RegistryResponseHolder(ebResponse, responseAttachments); } catch (SAXException e) { throw new JAXRException(e); } catch (ParserConfigurationException e) { throw new JAXRException(e); } catch (UnsupportedEncodingException x) { throw new JAXRException(x); } catch (MessagingException x) { throw new JAXRException(x); } catch (FileNotFoundException x) { throw new JAXRException(x); } catch (IOException e) { throw new JAXRException(e); } catch (SOAPException x) { x.printStackTrace(); throw new JAXRException(resourceBundle.getString("message.cannotConnect"), x); } catch (TransformerConfigurationException x) { throw new JAXRException(x); } catch (TransformerException x) { throw new JAXRException(x); } }
From source file:be.fedict.hsm.ws.impl.WSSecuritySOAPHandler.java
private void handleInboundMessage(SOAPMessageContext context) throws WSSecurityException, SOAPException { LOG.debug("checking WS-Security header"); SOAPMessage soapMessage = context.getMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); WSSecurityEngine secEngine = new WSSecurityEngine(); Crypto crypto = new WSSecurityCrypto(); WSSConfig wssConfig = new WSSConfig(); wssConfig.setWsiBSPCompliant(true);/*from w w w. j a v a2 s .co m*/ secEngine.setWssConfig(wssConfig); List<WSSecurityEngineResult> results = secEngine.processSecurityHeader(soapPart, null, null, crypto); if (null == results) { this.securityAuditGeneratorBean.webServiceAuthenticationError(); throw new SecurityException("no WS-Security results"); } WSSecurityEngineResult timeStampActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.TS); if (null == timeStampActionResult) { this.securityAuditGeneratorBean.webServiceAuthenticationError(); throw new SecurityException("no WS-Security timestamp result"); } Timestamp receivedTimestamp = (Timestamp) timeStampActionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP); if (null == receivedTimestamp) { this.securityAuditGeneratorBean.webServiceAuthenticationError(); throw new SecurityException("no WS-Security timestamp"); } LOG.debug("WS-Security timestamp created: " + receivedTimestamp.getCreated()); LOG.debug("WS-Security timestamp expires: " + receivedTimestamp.getExpires()); String timeStampIdRef = "#" + receivedTimestamp.getID(); WSSecurityEngineResult bstActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.BST); if (null == bstActionResult) { this.securityAuditGeneratorBean.webServiceAuthenticationError(); throw new SecurityException("no WS-Security BinarySecurityToken"); } BinarySecurity binarySecurityToken = (BinarySecurity) bstActionResult .get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN); WSSecurityEngineResult signActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN); if (null == signActionResult) { this.securityAuditGeneratorBean.webServiceAuthenticationError(); throw new SecurityException("no valid XML signature"); } String signatureMethod = (String) signActionResult.get(WSSecurityEngineResult.TAG_SIGNATURE_METHOD); LOG.debug("signature method: " + signatureMethod); if (false == "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256".equals(signatureMethod)) { this.securityAuditGeneratorBean.webServiceAuthenticationError(); throw new SecurityException("signature algo should be RSA-SHA256"); } X509Certificate certificate = (X509Certificate) signActionResult .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE); LOG.debug("certificate subject: " + certificate.getSubjectX500Principal()); List<WSDataRef> wsDataRefs = (List<WSDataRef>) signActionResult .get(WSSecurityEngineResult.TAG_DATA_REF_URIS); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPBody soapBody = soapEnvelope.getBody(); String bodyIdRef = "#" + soapBody.getAttributeNS(WSU_NAMESPACE, "Id"); String bstIdRef = "#" + binarySecurityToken.getID(); boolean timestampDigested = false; boolean bodyDigested = false; boolean tokenDigested = false; for (WSDataRef wsDataRef : wsDataRefs) { String wsuId = wsDataRef.getWsuId(); LOG.debug("signed wsu:Id: " + wsuId); LOG.debug("digest algorithm: " + wsDataRef.getDigestAlgorithm()); if (false == "http://www.w3.org/2001/04/xmlenc#sha256".equals(wsDataRef.getDigestAlgorithm())) { this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate); throw new SecurityException("digest algorithm should be SHA256"); } if (timeStampIdRef.equals(wsuId)) { timestampDigested = true; } else if (bodyIdRef.equals(wsuId)) { bodyDigested = true; } else if (bstIdRef.equals(wsuId)) { tokenDigested = true; } } if (false == timestampDigested) { this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate); throw new SecurityException("timestamp not digested"); } if (false == bodyDigested) { this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate); throw new SecurityException("SOAP Body not digested"); } if (false == tokenDigested) { this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate); throw new SecurityException("BinarySecurityToken not digested"); } context.put(X509_ATTRIBUTE, certificate); }
From source file:org.apache.axis2.jaxws.message.util.impl.SAAJConverterImpl.java
public SOAPEnvelope toSAAJ(org.apache.axiom.soap.SOAPEnvelope omEnvelope) throws WebServiceException { if (log.isDebugEnabled()) { log.debug("Converting OM SOAPEnvelope to SAAJ SOAPEnvelope"); log.debug("The conversion occurs due to " + JavaUtils.stackToString()); }//from ww w .j av a2 s. co m SOAPEnvelope soapEnvelope = null; try { // Build the default envelope OMNamespace ns = omEnvelope.getNamespace(); MessageFactory mf = createMessageFactory(ns.getNamespaceURI()); SOAPMessage sm = mf.createMessage(); SOAPPart sp = sm.getSOAPPart(); soapEnvelope = sp.getEnvelope(); // The getSOAPEnvelope() call creates a default SOAPEnvelope with a SOAPHeader and SOAPBody. // The SOAPHeader and SOAPBody are removed (they will be added back in if they are present in the // OMEnvelope). SOAPBody soapBody = soapEnvelope.getBody(); if (soapBody != null) { soapBody.detachNode(); } SOAPHeader soapHeader = soapEnvelope.getHeader(); if (soapHeader != null) { soapHeader.detachNode(); } // We don't know if there is a real OM tree or just a backing XMLStreamReader. // The best way to walk the data is to get the XMLStreamReader and use this // to build the SOAPElements XMLStreamReader reader = omEnvelope.getXMLStreamReader(); NameCreator nc = new NameCreator(soapEnvelope); buildSOAPTree(nc, soapEnvelope, null, reader, false); } catch (WebServiceException e) { throw e; } catch (SOAPException e) { throw ExceptionFactory.makeWebServiceException(e); } return soapEnvelope; }
From source file:org.apache.ws.scout.transport.SaajTransport.java
private SOAPMessage createSOAPMessage(Element elem) throws Exception { String prefix = ""; MessageFactory msgFactory = MessageFactory.newInstance(); SOAPFactory factory = SOAPFactory.newInstance(); SOAPMessage message = msgFactory.createMessage(); message.getSOAPHeader().detachNode(); SOAPPart soapPart = message.getSOAPPart(); SOAPBody soapBody = soapPart.getEnvelope().getBody(); //Create the outer body element Name bodyName = factory.createName(elem.getNodeName(), prefix, UDDI_V2_NAMESPACE); SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName); bodyElement.addNamespaceDeclaration(prefix, UDDI_V2_NAMESPACE); appendAttributes(bodyElement, elem.getAttributes(), factory); appendElements(bodyElement, elem.getChildNodes(), factory); return message; }
From source file:org.codice.ddf.cxf.paos.PaosInInterceptor.java
@Override public void handleMessage(Message message) throws Fault { List authHeader = (List) ((Map) message.getExchange().getOutMessage().get(Message.PROTOCOL_HEADERS)) .get("Authorization"); String authorization = null;// ww w . j av a 2 s .com if (authHeader != null && authHeader.size() > 0) { authorization = (String) authHeader.get(0); } InputStream content = message.getContent(InputStream.class); String contentType = (String) message.get(Message.CONTENT_TYPE); if (contentType == null || !contentType.contains(APPLICATION_VND_PAOS_XML)) { return; } try { SOAPPart soapMessage = SamlProtocol .parseSoapMessage(IOUtils.toString(content, Charset.forName("UTF-8"))); Iterator iterator = soapMessage.getEnvelope().getHeader().examineAllHeaderElements(); IDPEntry idpEntry = null; String relayState = ""; String responseConsumerURL = ""; String messageId = ""; while (iterator.hasNext()) { Element soapHeaderElement = (SOAPHeaderElement) iterator.next(); if (RELAY_STATE.equals(soapHeaderElement.getLocalName())) { relayState = DOM2Writer.nodeToString(soapHeaderElement); } else if (REQUEST.equals(soapHeaderElement.getLocalName()) && soapHeaderElement.getNamespaceURI() .equals(URN_OASIS_NAMES_TC_SAML_2_0_PROFILES_SSO_ECP)) { try { soapHeaderElement = SamlProtocol.convertDomImplementation(soapHeaderElement); Request ecpRequest = (Request) OpenSAMLUtil.fromDom(soapHeaderElement); IDPList idpList = ecpRequest.getIDPList(); if (idpList == null) { throw new Fault(new AccessDeniedException( "Unable to complete SAML ECP connection. Unable to determine IdP server.")); } List<IDPEntry> idpEntrys = idpList.getIDPEntrys(); if (idpEntrys == null || idpEntrys.size() == 0) { throw new Fault(new AccessDeniedException( "Unable to complete SAML ECP connection. Unable to determine IdP server.")); } // choose the right entry, probably need to do something better than select the first // one // but the spec doesn't specify how this is supposed to be done idpEntry = idpEntrys.get(0); } catch (WSSecurityException e) { // TODO figure out IdP alternatively LOGGER.info( "Unable to determine IdP appropriately. ECP connection will fail. SP may be incorrectly configured. Contact the administrator for the remote system."); } } else if (REQUEST.equals(soapHeaderElement.getLocalName()) && soapHeaderElement.getNamespaceURI().equals(URN_LIBERTY_PAOS_2003_08)) { responseConsumerURL = soapHeaderElement.getAttribute(RESPONSE_CONSUMER_URL); messageId = soapHeaderElement.getAttribute(MESSAGE_ID); } } if (idpEntry == null) { throw new Fault(new AccessDeniedException( "Unable to complete SAML ECP connection. Unable to determine IdP server.")); } String token = createToken(authorization); checkAuthnRequest(soapMessage); Element authnRequestElement = SamlProtocol .getDomElement(soapMessage.getEnvelope().getBody().getFirstChild()); String loc = idpEntry.getLoc(); String soapRequest = buildSoapMessage(token, relayState, authnRequestElement, null); HttpResponseWrapper httpResponse = getHttpResponse(loc, soapRequest, null); InputStream httpResponseContent = httpResponse.content; SOAPPart idpSoapResponse = SamlProtocol .parseSoapMessage(IOUtils.toString(httpResponseContent, Charset.forName("UTF-8"))); Iterator responseHeaderElements = idpSoapResponse.getEnvelope().getHeader().examineAllHeaderElements(); String newRelayState = ""; while (responseHeaderElements.hasNext()) { SOAPHeaderElement soapHeaderElement = (SOAPHeaderElement) responseHeaderElements.next(); if (RESPONSE.equals(soapHeaderElement.getLocalName())) { String assertionConsumerServiceURL = soapHeaderElement .getAttribute(ASSERTION_CONSUMER_SERVICE_URL); if (!responseConsumerURL.equals(assertionConsumerServiceURL)) { String soapFault = buildSoapFault(ECP_RESPONSE, "The responseConsumerURL does not match the assertionConsumerServiceURL."); httpResponse = getHttpResponse(responseConsumerURL, soapFault, null); message.setContent(InputStream.class, httpResponse.content); return; } } else if (RELAY_STATE.equals(soapHeaderElement.getLocalName())) { newRelayState = DOM2Writer.nodeToString(soapHeaderElement); if (StringUtils.isNotEmpty(relayState) && !relayState.equals(newRelayState)) { LOGGER.debug("RelayState does not match between ECP request and response"); } if (StringUtils.isNotEmpty(relayState)) { newRelayState = relayState; } } } checkSamlpResponse(idpSoapResponse); Element samlpResponseElement = SamlProtocol .getDomElement(idpSoapResponse.getEnvelope().getBody().getFirstChild()); Response paosResponse = null; if (StringUtils.isNotEmpty(messageId)) { paosResponse = getPaosResponse(messageId); } String soapResponse = buildSoapMessage(null, newRelayState, samlpResponseElement, paosResponse); httpResponse = getHttpResponse(responseConsumerURL, soapResponse, message.getExchange().getOutMessage()); if (httpResponse.statusCode < 400) { httpResponseContent = httpResponse.content; message.setContent(InputStream.class, httpResponseContent); Map<String, List<String>> headers = new HashMap<>(); message.put(Message.PROTOCOL_HEADERS, headers); httpResponse.headers.forEach((entry) -> headers.put(entry.getKey(), // CXF Expects pairs of <String, List<String>> entry.getValue() instanceof List ? ((List<Object>) entry.getValue()).stream().map(String::valueOf) .collect(Collectors.toList()) : Lists.newArrayList(String.valueOf(entry.getValue())))); } else { throw new Fault( new AccessDeniedException("Unable to complete SAML ECP connection due to an error.")); } } catch (IOException e) { LOGGER.debug("Error encountered while performing ECP handshake.", e); } catch (XMLStreamException | SOAPException e) { throw new Fault(new AccessDeniedException( "Unable to complete SAML ECP connection. The server's response was not in the correct format.")); } catch (WSSecurityException e) { throw new Fault(new AccessDeniedException( "Unable to complete SAML ECP connection. Unable to send SOAP request messages.")); } }
From source file:org.codice.ddf.cxf.paos.PaosInInterceptor.java
private void checkAuthnRequest(SOAPPart soapRequest) throws IOException { XMLObject authnXmlObj = null; try {//w w w . java 2 s .com Node node = soapRequest.getEnvelope().getBody().getFirstChild(); authnXmlObj = SamlProtocol.getXmlObjectFromNode(node); } catch (WSSecurityException | SOAPException | XMLStreamException ex) { throw new IOException("Unable to convert AuthnRequest document to XMLObject."); } if (authnXmlObj == null) { throw new IOException("AuthnRequest object is not Found."); } if (!(authnXmlObj instanceof AuthnRequest)) { throw new IOException("SAMLRequest object is not AuthnRequest."); } }
From source file:org.codice.ddf.cxf.paos.PaosInInterceptor.java
private void checkSamlpResponse(SOAPPart soapRequest) throws IOException { XMLObject responseXmlObj = null; try {/* w w w . j a va2 s.co m*/ Node node = soapRequest.getEnvelope().getBody().getFirstChild(); responseXmlObj = SamlProtocol.getXmlObjectFromNode(node); } catch (WSSecurityException | SOAPException | XMLStreamException ex) { throw new IOException("Unable to convert Response document to XMLObject."); } if (responseXmlObj == null) { throw new IOException("Response object is not Found."); } if (!(responseXmlObj instanceof org.opensaml.saml.saml2.core.Response)) { throw new IOException("SAMLRequest object is not org.opensaml.saml.saml2.core.Response."); } }
From source file:org.energy_home.jemma.ah.internal.greenathome.GreenathomeAppliance.java
private static SOAPMessage createSOAPRequest(String date) throws Exception { MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage soapMessage = messageFactory.createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); String serverURI = "http://ws.i-em.eu/v4/"; // SOAP Envelope SOAPEnvelope envelope = soapPart.getEnvelope(); envelope.addNamespaceDeclaration("example", serverURI); // SOAP Body/* w w w .j av a 2s .co m*/ SOAPBody soapBody = envelope.getBody(); SOAPElement soapBodyElem = soapBody.addChildElement("Get72hPlantForecast", "example"); SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("plantID", "example"); soapBodyElem1.addTextNode("telecom_02"); SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("quantityID", "example"); soapBodyElem2.addTextNode("frc_pac"); SOAPElement soapBodyElem3 = soapBodyElem.addChildElement("timestamp", "example"); soapBodyElem3.addTextNode(date); SOAPElement soapBodyElem4 = soapBodyElem.addChildElement("langID", "example"); soapBodyElem4.addTextNode("en"); MimeHeaders headers = soapMessage.getMimeHeaders(); headers.addHeader("SOAPAction", serverURI + "Get72hPlantForecast"); soapMessage.saveChanges(); return soapMessage; }
From source file:org.jboss.jaxr.juddi.transport.SaajTransport.java
private SOAPMessage createSOAPMessage(Element elem) throws Exception { String prefix = "uddi"; MessageFactory msgFactory = MessageFactory.newInstance(); SOAPFactory factory = SOAPFactory.newInstance(); SOAPMessage message = msgFactory.createMessage(); message.getSOAPHeader().detachNode(); SOAPPart soapPart = message.getSOAPPart(); SOAPBody soapBody = soapPart.getEnvelope().getBody(); //Create the outer body element String uddins = IRegistry.UDDI_V2_NAMESPACE; Name bodyName = factory.createName(elem.getNodeName(), prefix, uddins); SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName); bodyElement.addNamespaceDeclaration(prefix, uddins); appendAttributes(bodyElement, elem.getAttributes(), factory); appendElements(bodyElement, elem.getChildNodes(), factory); return message; }