List of usage examples for javax.xml.soap SOAPMessage getSOAPPart
public abstract SOAPPart getSOAPPart();
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 . c o 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.apache.ws.security.handler.WSS4JHandler.java
/** * Handles incoming web service requests and outgoing responses *//*from w ww .j a va 2 s. co m*/ public boolean doSender(MessageContext mc, RequestData reqData, boolean isRequest) throws WSSecurityException { reqData.getSignatureParts().removeAllElements(); reqData.getEncryptParts().removeAllElements(); reqData.setNoSerialization(false); /* * Get the action first. */ Vector actions = new Vector(); String action = (String) getOption(WSHandlerConstants.SEND + '.' + WSHandlerConstants.ACTION); if (action == null) { action = (String) getOption(WSHandlerConstants.ACTION); if (action == null) { action = (String) mc.getProperty(WSHandlerConstants.ACTION); } } if (action == null) { throw new JAXRPCException("WSS4JHandler: No action defined"); } int doAction = WSSecurityUtil.decodeAction(action, actions); if (doAction == WSConstants.NO_SECURITY) { return true; } /* * For every action we need a username, so get this now. The username * defined in the deployment descriptor takes precedence. */ reqData.setUsername((String) getOption(WSHandlerConstants.USER)); if (reqData.getUsername() == null || reqData.getUsername().equals("")) { reqData.setUsername((String) mc.getProperty(WSHandlerConstants.USER)); mc.removeProperty(WSHandlerConstants.USER); } /* * Now we perform some set-up for UsernameToken and Signature * functions. No need to do it for encryption only. Check if username * is available and then get a password. */ if (((doAction & (WSConstants.SIGN | WSConstants.UT | WSConstants.UT_SIGN)) != 0) && (reqData.getUsername() == null || reqData.getUsername().equals(""))) { /* * We need a username - if none throw an JAXRPCException. For encryption * there is a specific parameter to get a username. */ throw new JAXRPCException("WSS4JHandler: Empty username for specified action"); } if (doDebug) { log.debug("Action: " + doAction); log.debug("Actor: " + reqData.getActor()); } /* * Now get the SOAP part from the request message and convert it into a * Document. * * This forces Axis to serialize the SOAP request into FORM_STRING. * This string is converted into a document. * * During the FORM_STRING serialization Axis performs multi-ref of * complex data types (if requested), generates and inserts references * for attachments and so on. The resulting Document MUST be the * complete and final SOAP request as Axis would send it over the wire. * Therefore this must shall be the last (or only) handler in a chain. * * Now we can perform our security operations on this request. */ Document doc = null; SOAPMessage message = ((SOAPMessageContext) mc).getMessage(); Boolean propFormOptimization = (Boolean) mc.getProperty("axis.form.optimization"); log.debug("Form optimization: " + propFormOptimization); /* * If the message context property contains a document then this is a * chained handler. */ SOAPPart sPart = message.getSOAPPart(); if ((doc = (Document) mc.getProperty(WSHandlerConstants.SND_SECURITY)) == null) { try { doc = messageToDocument(message); } catch (Exception e) { if (doDebug) { log.debug(e.getMessage(), e); } throw new JAXRPCException("WSS4JHandler: cannot get SOAP envlope from message", e); } } if (doDebug) { log.debug("WSS4JHandler: orginal SOAP request: "); log.debug(org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc)); } doSenderAction(doAction, doc, reqData, actions, isRequest); /* * If required convert the resulting document into a message first. The * outputDOM() method performs the necessary c14n call. After that we * extract it as a string for further processing. * * Set the resulting byte array as the new SOAP message. * * If noSerialization is false, this handler shall be the last (or only) * one in a handler chain. If noSerialization is true, just set the * processed Document in the transfer property. The next Axis WSS4J * handler takes it and performs additional security processing steps. * */ if (reqData.isNoSerialization()) { mc.setProperty(WSHandlerConstants.SND_SECURITY, doc); } else { ByteArrayOutputStream os = new ByteArrayOutputStream(); XMLUtils.outputDOM(doc, os, true); if (doDebug) { String osStr = null; try { osStr = os.toString("UTF-8"); } catch (UnsupportedEncodingException e) { if (doDebug) { log.debug(e.getMessage(), e); } osStr = os.toString(); } log.debug("Send request:"); log.debug(osStr); } try { sPart.setContent(new StreamSource(new ByteArrayInputStream(os.toByteArray()))); } catch (SOAPException se) { if (doDebug) { log.debug(se.getMessage(), se); } throw new JAXRPCException("Couldn't set content on SOAPPart" + se.getMessage(), se); } mc.removeProperty(WSHandlerConstants.SND_SECURITY); } if (doDebug) { log.debug("WSS4JHandler: exit invoke()"); } return true; }
From source file:org.apache.ws.security.handler.WSS4JHandler.java
/** * handle responses/*from w w w . j a v a 2 s . c o m*/ * * @param mc * @param reqData * @return true on successful processing * @throws WSSecurityException */ public boolean doReceiver(MessageContext mc, RequestData reqData, boolean isRequest) throws WSSecurityException { Vector actions = new Vector(); String action = (String) getOption(WSHandlerConstants.RECEIVE + '.' + WSHandlerConstants.ACTION); if (action == null) { action = (String) getOption(WSHandlerConstants.ACTION); if (action == null) { action = (String) mc.getProperty(WSHandlerConstants.ACTION); } } if (action == null) { throw new JAXRPCException("WSS4JHandler: No action defined"); } int doAction = WSSecurityUtil.decodeAction(action, actions); String actor = (String) getOption(WSHandlerConstants.ACTOR); SOAPMessage message = ((SOAPMessageContext) mc).getMessage(); SOAPPart sPart = message.getSOAPPart(); Document doc = null; try { doc = messageToDocument(message); } catch (Exception ex) { if (doDebug) { log.debug(ex.getMessage(), ex); } throw new JAXRPCException("WSS4JHandler: cannot convert into document", ex); } /* * Check if it's a fault. Don't process faults. * */ SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc.getDocumentElement()); if (WSSecurityUtil.findElement(doc.getDocumentElement(), "Fault", soapConstants.getEnvelopeURI()) != null) { return false; } /* * To check a UsernameToken or to decrypt an encrypted message we need * a password. */ CallbackHandler cbHandler = null; if ((doAction & (WSConstants.ENCR | WSConstants.UT)) != 0) { cbHandler = getPasswordCB(reqData); } /* * Get and check the Signature specific parameters first because they * may be used for encryption too. */ doReceiverAction(doAction, reqData); Vector wsResult = null; try { wsResult = secEngine.processSecurityHeader(doc, actor, cbHandler, reqData.getSigCrypto(), reqData.getDecCrypto()); } catch (WSSecurityException ex) { if (doDebug) { log.debug(ex.getMessage(), ex); } throw new JAXRPCException("WSS4JHandler: security processing failed", ex); } if (wsResult == null) { // no security header found if (doAction == WSConstants.NO_SECURITY) { return true; } else { throw new JAXRPCException("WSS4JHandler: Request does not contain required Security header"); } } if (reqData.getWssConfig().isEnableSignatureConfirmation() && !isRequest) { checkSignatureConfirmation(reqData, wsResult); } /* * If we had some security processing, get the original * SOAP part of Axis' message and replace it with new SOAP * part. This new part may contain decrypted elements. */ ByteArrayOutputStream os = new ByteArrayOutputStream(); XMLUtils.outputDOM(doc, os, true); try { sPart.setContent(new StreamSource(new ByteArrayInputStream(os.toByteArray()))); } catch (SOAPException se) { if (doDebug) { log.debug(se.getMessage(), se); } throw new JAXRPCException("Couldn't set content on SOAPPart" + se.getMessage(), se); } if (doDebug) { log.debug("Processed received SOAP request"); } /* * After setting the new current message, probably modified because * of decryption, we need to locate the security header. That is, * we force Axis (with getSOAPEnvelope()) to parse the string, build * the new header. Then we examine, look up the security header * and set the header as processed. * * Please note: find all header elements that contain the same * actor that was given to processSecurityHeader(). Then * check if there is a security header with this actor. */ SOAPHeader sHeader = null; try { sHeader = message.getSOAPPart().getEnvelope().getHeader(); } catch (Exception ex) { if (doDebug) { log.debug(ex.getMessage(), ex); } throw new JAXRPCException("WSS4JHandler: cannot get SOAP header after security processing", ex); } Iterator headers = sHeader.examineHeaderElements(actor); SOAPHeaderElement headerElement = null; while (headers.hasNext()) { SOAPHeaderElement hE = (SOAPHeaderElement) headers.next(); if (hE.getElementName().getLocalName().equals(WSConstants.WSSE_LN) && ((Node) hE).getNamespaceURI().equals(WSConstants.WSSE_NS)) { headerElement = hE; break; } } /* JAXRPC conversion changes */ headerElement.setMustUnderstand(false); // is this sufficient? /* * Now we can check the certificate used to sign the message. * In the following implementation the certificate is only trusted * if either it itself or the certificate of the issuer is installed * in the keystore. * * Note: the method verifyTrust(X509Certificate) allows custom * implementations with other validation algorithms for subclasses. */ // Extract the signature action result from the action vector WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.SIGN); if (actionResult != null) { X509Certificate returnCert = (X509Certificate) actionResult .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE); if (returnCert != null && !verifyTrust(returnCert, reqData)) { throw new JAXRPCException("WSS4JHandler: The certificate used for the signature is not trusted"); } } /* * Perform further checks on the timestamp that was transmitted in the header. * In the following implementation the timestamp is valid if it was * created after (now-ttl), where ttl is set on server side, not by the client. * * Note: the method verifyTimestamp(Timestamp) allows custom * implementations with other validation algorithms for subclasses. */ // Extract the timestamp action result from the action vector actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.TS); if (actionResult != null) { Timestamp timestamp = (Timestamp) actionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP); if (timestamp != null && reqData.getWssConfig().isTimeStampStrict() && !verifyTimestamp(timestamp, decodeTimeToLive(reqData))) { throw new JAXRPCException("WSS4JHandler: The timestamp could not be validated"); } } /* * now check the security actions: do they match, in right order? */ if (!checkReceiverResults(wsResult, actions)) { throw new JAXRPCException("WSS4JHandler: security processing failed (actions mismatch)"); } /* * All ok up to this point. Now construct and setup the * security result structure. The service may fetch this * and check it. */ Vector results = null; if ((results = (Vector) mc.getProperty(WSHandlerConstants.RECV_RESULTS)) == null) { results = new Vector(); mc.setProperty(WSHandlerConstants.RECV_RESULTS, results); } WSHandlerResult rResult = new WSHandlerResult(actor, wsResult); results.add(0, rResult); if (doDebug) { log.debug("WSS4JHandler: exit invoke()"); } return true; }
From source file:org.apache.ws.security.handler.WSS4JHandler.java
/** * Utility method to convert SOAPMessage to org.w3c.dom.Document *//*from w ww .j a va2s.c o m*/ public static Document messageToDocument(SOAPMessage message) { try { Source content = message.getSOAPPart().getContent(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = dbf.newDocumentBuilder(); return builder.parse(org.apache.ws.security.util.XMLUtils.sourceToInputSource(content)); } catch (Exception ex) { if (doDebug) { log.debug(ex.getMessage(), ex); } throw new JAXRPCException("messageToDocument: cannot convert SOAPMessage into Document", ex); } }
From source file:org.belio.service.gateway.SafcomGateway.java
/** * Method used to print the SOAP Response *//*from w w w . j a v a 2s. co m*/ private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); Source sourceContent = soapResponse.getSOAPPart().getContent(); // System.out.print("\nResponse SOAP Message = "); StreamResult result = new StreamResult(new StringWriter()); transformer.transform(sourceContent, result); String xmlString = result.getWriter().toString(); Launcher.LOG.info(xmlString); }
From source file:org.codice.ddf.security.interceptor.AnonymousInterceptor.java
@Override public void handleMessage(SoapMessage message) throws Fault { if (anonymousAccessDenied) { LOGGER.debug("AnonymousAccess not enabled - no message checking performed."); return;//from www . j a v a2s . c om } if (message != null) { SoapVersion version = message.getVersion(); SOAPMessage soapMessage = getSOAPMessage(message); SOAPFactory soapFactory = null; SOAPElement securityHeader = null; //Check if security header exists; if not, execute AnonymousInterceptor logic String actor = (String) getOption(WSHandlerConstants.ACTOR); if (actor == null) { actor = (String) message.getContextualProperty(SecurityConstants.ACTOR); } Element existingSecurityHeader = null; try { LOGGER.debug("Checking for security header."); existingSecurityHeader = WSSecurityUtil.getSecurityHeader(soapMessage.getSOAPPart(), actor); } catch (WSSecurityException e1) { LOGGER.debug("Issue with getting security header", e1); } if (existingSecurityHeader == null) { LOGGER.debug("Current request has no security header, continuing with AnonymousInterceptor"); AssertionInfoMap assertionInfoMap = message.get(AssertionInfoMap.class); // if there is a policy we need to follow or we are ignoring policies, prepare the SOAP message if ((assertionInfoMap != null) || overrideEndpointPolicies) { RequestData reqData = new CXFRequestData(); WSSConfig config = (WSSConfig) message.getContextualProperty(WSSConfig.class.getName()); WSSecurityEngine engine = null; if (config != null) { engine = new WSSecurityEngine(); engine.setWssConfig(config); } if (engine == null) { engine = new WSSecurityEngine(); config = engine.getWssConfig(); } reqData.setWssConfig(config); try { soapFactory = SOAPFactory.newInstance(); } catch (SOAPException e) { LOGGER.error("Could not create a SOAPFactory.", e); return; // can't add anything if we can't create it } if (soapFactory != null) { //Create security header try { securityHeader = soapFactory.createElement(WSConstants.WSSE_LN, WSConstants.WSSE_PREFIX, WSConstants.WSSE_NS); securityHeader.addAttribute( new QName(WSConstants.URI_SOAP11_ENV, WSConstants.ATTR_MUST_UNDERSTAND), "1"); } catch (SOAPException e) { LOGGER.error("Unable to create security header for anonymous user.", e); return; // can't create the security - just return } } } EffectivePolicy effectivePolicy = message.get(EffectivePolicy.class); Exchange exchange = message.getExchange(); BindingOperationInfo bindingOperationInfo = exchange.getBindingOperationInfo(); Endpoint endpoint = exchange.get(Endpoint.class); if (null == endpoint) { return; } EndpointInfo endpointInfo = endpoint.getEndpointInfo(); Bus bus = exchange.get(Bus.class); PolicyEngine policyEngine = bus.getExtension(PolicyEngine.class); if (effectivePolicy == null) { if (policyEngine != null) { if (MessageUtils.isRequestor(message)) { effectivePolicy = policyEngine.getEffectiveClientResponsePolicy(endpointInfo, bindingOperationInfo, message); } else { effectivePolicy = policyEngine.getEffectiveServerRequestPolicy(endpointInfo, bindingOperationInfo, message); } } } //Auto analyze endpoint policies //Token Assertions String tokenAssertion = null; String tokenType = null; //Security Binding Assertions boolean layoutLax = false; boolean layoutStrict = false; boolean layoutLaxTimestampFirst = false; boolean layoutLaxTimestampLast = false; boolean requireClientCert = false; QName secBindingAssertion = null; //Supporting Token Assertions QName supportingTokenAssertion = null; boolean policyRequirementsSupported = false; // if there is a policy, try to follow it as closely as possible if (effectivePolicy != null) { Policy policy = effectivePolicy.getPolicy(); if (policy != null) { AssertionInfoMap infoMap = new AssertionInfoMap(policy); Set<Map.Entry<QName, Collection<AssertionInfo>>> entries = infoMap.entrySet(); for (Map.Entry<QName, Collection<AssertionInfo>> entry : entries) { Collection<AssertionInfo> assetInfoList = entry.getValue(); for (AssertionInfo info : assetInfoList) { LOGGER.debug("Assertion Name: {}", info.getAssertion().getName().getLocalPart()); QName qName = info.getAssertion().getName(); StringWriter out = new StringWriter(); XMLStreamWriter writer = null; try { writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out); } catch (XMLStreamException e) { LOGGER.debug("Error with XMLStreamWriter", e); } catch (FactoryConfigurationError e) { LOGGER.debug("Error with FactoryConfiguration", e); } try { if (writer != null) { info.getAssertion().serialize(writer); writer.flush(); } } catch (XMLStreamException e) { LOGGER.debug("Error with XMLStream", e); } finally { if (writer != null) { try { writer.close(); } catch (XMLStreamException ignore) { //ignore } } } LOGGER.trace("Assertion XML: {}", out.toString()); String xml = out.toString(); // TODO DDF-1205 complete support for dynamic policy handling if (qName.equals(SP12Constants.TRANSPORT_BINDING)) { secBindingAssertion = qName; } else if (qName.equals(SP12Constants.INCLUDE_TIMESTAMP)) { createIncludeTimestamp(soapFactory, securityHeader); } else if (qName.equals(SP12Constants.LAYOUT)) { String xpathLax = "/Layout/Policy/Lax"; String xpathStrict = "/Layout/Policy/Strict"; String xpathLaxTimestampFirst = "/Layout/Policy/LaxTimestampFirst"; String xpathLaxTimestampLast = "/Layout/Policy/LaxTimestampLast"; } else if (qName.equals(SP12Constants.TRANSPORT_TOKEN)) { } else if (qName.equals(SP12Constants.HTTPS_TOKEN)) { String xpath = "/HttpsToken/Policy/RequireClientCertificate"; } else if (qName.equals(SP12Constants.SIGNED_SUPPORTING_TOKENS)) { String xpath = "/SignedSupportingTokens/Policy//IssuedToken/RequestSecurityTokenTemplate/TokenType"; tokenType = retrieveXmlValue(xml, xpath); supportingTokenAssertion = qName; } else if (qName.equals(SP12Constants.SUPPORTING_TOKENS)) { String xpath = "/SupportingTokens/Policy//IssuedToken/RequestSecurityTokenTemplate/TokenType"; tokenType = retrieveXmlValue(xml, xpath); supportingTokenAssertion = qName; } else if (qName.equals( org.apache.cxf.ws.addressing.policy.MetadataConstants.ADDRESSING_ASSERTION_QNAME)) { createAddressing(message, soapMessage, soapFactory); } else if (qName.equals(SP12Constants.TRUST_13)) { } else if (qName.equals(SP12Constants.ISSUED_TOKEN)) { //Check Token Assertion String xpath = "/IssuedToken/@IncludeToken"; tokenAssertion = retrieveXmlValue(xml, xpath); } else if (qName.equals(SP12Constants.WSS11)) { } } } //Check security and token policies if (tokenAssertion != null && tokenType != null && tokenAssertion.trim().equals(SP12Constants.INCLUDE_ALWAYS_TO_RECIPIENT) && tokenType.trim().equals(TOKEN_SAML20)) { policyRequirementsSupported = true; } else { LOGGER.warn( "AnonymousInterceptor does not support the policies presented by the endpoint."); } } else { if (overrideEndpointPolicies) { LOGGER.debug( "WS Policy is null, override is true - an anonymous assertion will be generated"); } else { LOGGER.warn( "WS Policy is null, override flag is false - no anonymous assertion will be generated."); } } } else { if (overrideEndpointPolicies) { LOGGER.debug( "Effective WS Policy is null, override is true - an anonymous assertion will be generated"); } else { LOGGER.warn( "Effective WS Policy is null, override flag is false - no anonymous assertion will be generated."); } } if (policyRequirementsSupported || overrideEndpointPolicies) { LOGGER.debug("Creating anonymous security token."); if (soapFactory != null) { HttpServletRequest request = (HttpServletRequest) message .get(AbstractHTTPDestination.HTTP_REQUEST); createSecurityToken(version, soapFactory, securityHeader, request.getRemoteAddr()); try { // Add security header to SOAP message soapMessage.getSOAPHeader().addChildElement(securityHeader); } catch (SOAPException e) { LOGGER.error("Issue when adding security header to SOAP message:" + e.getMessage()); } } else { LOGGER.debug("Security Header was null so not creating a SAML Assertion"); } } } else { LOGGER.debug("SOAP message contains security header, no action taken by the AnonymousInterceptor."); } if (LOGGER.isTraceEnabled()) { try { LOGGER.trace("SOAP request after anonymous interceptor: {}", SecurityLogger.getFormattedXml(soapMessage.getSOAPHeader().getParentNode())); } catch (SOAPException e) { //ignore } } } else { LOGGER.error("Incoming SOAP message is null - anonymous interceptor makes no sense."); } }
From source file:org.codice.ddf.security.interceptor.GuestInterceptor.java
private void internalHandleMessage(SoapMessage message, SOAPMessage soapMessage) throws Fault { //Check if security header exists; if not, execute GuestInterceptor logic String actor = (String) getOption(WSHandlerConstants.ACTOR); if (actor == null) { actor = (String) message.getContextualProperty(SecurityConstants.ACTOR); }/*from w w w .ja v a 2 s .com*/ Element existingSecurityHeader = null; try { LOGGER.debug("Checking for security header."); existingSecurityHeader = WSSecurityUtil.getSecurityHeader(soapMessage.getSOAPPart(), actor); } catch (WSSecurityException e1) { LOGGER.debug("Issue with getting security header", e1); } if (existingSecurityHeader != null) { LOGGER.debug("SOAP message contains security header, no action taken by the GuestInterceptor."); return; } LOGGER.debug("Current request has no security header, continuing with GuestInterceptor"); AssertionInfoMap assertionInfoMap = message.get(AssertionInfoMap.class); boolean hasAddressingAssertion = assertionInfoMap.entrySet().stream().flatMap(p -> p.getValue().stream()) .filter(info -> MetadataConstants.ADDRESSING_ASSERTION_QNAME.equals(info.getAssertion().getName())) .findFirst().isPresent(); if (hasAddressingAssertion) { createAddressing(message, soapMessage); } LOGGER.debug("Creating guest security token."); HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST); SecurityToken securityToken = createSecurityToken(request.getRemoteAddr()); message.put(SecurityConstants.TOKEN, securityToken); if (!MessageUtils.isRequestor(message)) { try { message.put(Message.REQUESTOR_ROLE, true); policyBasedWss4jOutInterceptor.handleMessage(message); } finally { message.remove(Message.REQUESTOR_ROLE); } } else { policyBasedWss4jOutInterceptor.handleMessage(message); } }
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 a v a2 s . 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.energy_home.jemma.ah.internal.greenathome.GreenathomeAppliance.java
private double[] getValuesFromSOAPResponse(SOAPMessage soapResponse) throws Exception { NodeList list = soapResponse.getSOAPPart().getElementsByTagName("values"); if (list != null) { forecast_debug += "---found values"; list = list.item(0).getChildNodes(); double[] frc_values = new double[24]; for (int i = 0; i < 24; i++) { Node node = list.item(i); Node value = node.getLastChild(); frc_values[i] = Double.parseDouble(value.getTextContent()); //System.out.println("node name: "+value.getNodeName()+" value: "+value.getTextContent()); }//from w w w . j ava2s .c o m return frc_values; } else { forecast_debug += "---not found values"; return null; } }