List of usage examples for javax.xml.soap SOAPEnvelope getHeader
public SOAPHeader getHeader() throws SOAPException;
From source file:MainClass.java
public static void main(String[] args) throws Exception { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPHeader soapHeader = soapEnvelope.getHeader(); SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12")); SOAPBody soapBody = soapEnvelope.getBody(); soapBody.addAttribute(/* w w w.j a va2 s. c o m*/ soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"), "Body"); Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com"); SOAPBodyElement gltp = soapBody.addBodyElement(bodyName); Source source = soapPart.getContent(); }
From source file:Main.java
public static void main(String[] args) throws Exception { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPHeader soapHeader = soapEnvelope.getHeader(); SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12")); SOAPBody soapBody = soapEnvelope.getBody(); soapBody.addAttribute(//from www . j a v a 2s . c o m soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"), "Body"); Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com"); SOAPBodyElement gltp = soapBody.addBodyElement(bodyName); Source source = soapPart.getContent(); Node root = null; if (source instanceof DOMSource) { root = ((DOMSource) source).getNode(); } else if (source instanceof SAXSource) { InputSource inSource = ((SAXSource) source).getInputSource(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); Document doc = db.parse(inSource); root = (Node) doc.getDocumentElement(); } }
From source file:MainClass.java
public static void main(String[] args) throws Exception { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPHeader soapHeader = soapEnvelope.getHeader(); SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12")); SOAPBody soapBody = soapEnvelope.getBody(); soapBody.addAttribute(/*from w ww. java2 s . com*/ soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"), "Body"); Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com"); SOAPBodyElement gltp = soapBody.addBodyElement(bodyName); Source source = soapPart.getContent(); Node root = null; if (source instanceof DOMSource) { root = ((DOMSource) source).getNode(); } else if (source instanceof SAXSource) { InputSource inSource = ((SAXSource) source).getInputSource(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); Document doc = db.parse(inSource); root = (Node) doc.getDocumentElement(); } Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(root), new StreamResult(System.out)); }
From source file:Signing.java
public static void main(String[] args) throws Exception { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPHeader soapHeader = soapEnvelope.getHeader(); SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12")); SOAPBody soapBody = soapEnvelope.getBody(); soapBody.addAttribute(/* w ww . j a va 2s. c o m*/ soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"), "Body"); Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com"); SOAPBodyElement gltp = soapBody.addBodyElement(bodyName); Source source = soapPart.getContent(); Node root = null; if (source instanceof DOMSource) { root = ((DOMSource) source).getNode(); } else if (source instanceof SAXSource) { InputSource inSource = ((SAXSource) source).getInputSource(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); Document doc = db.parse(inSource); root = (Node) doc.getDocumentElement(); } dumpDocument(root); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(1024, new SecureRandom()); KeyPair keypair = kpg.generateKeyPair(); XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance(); Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null)); SignedInfo signedInfo = sigFactory.newSignedInfo( sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = sigFactory.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo); System.out.println("Signing the message..."); PrivateKey privateKey = keypair.getPrivate(); Element envelope = getFirstChildElement(root); Element header = getFirstChildElement(envelope); DOMSignContext sigContext = new DOMSignContext(privateKey, header); sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); sigContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); sig.sign(sigContext); dumpDocument(root); System.out.println("Validate the signature..."); Element sigElement = getFirstChildElement(header); DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement); valContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); boolean valid = sig.validate(valContext); System.out.println("Signature valid? " + valid); }
From source file:eu.planets_project.tb.gui.backing.admin.wsclient.util.WSClient.java
/** * Invokes an operation using SAAJ//from w ww.ja v a 2 s . c o m * * @param operation The operation to invoke */ public static void main(String[] args) { try { /*OperationInfo operation = new OperationInfo(); operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/"); operation.setInputMessageName("HelloWorld_sayHello"); operation.setInputMessageText("<urn:sayHello xmlns:urn='urn:jbosstest'><arg0>Markus</arg0></urn:sayHello>"); operation.setNamespaceURI("urn:jbosstest"); operation.setOutputMessageName("HelloWorld_sayHelloResponse"); operation.setOutputMessageText("<sayHello><return>0</return></sayHello>"); operation.setSoapActionURI(""); operation.setStyle("document"); operation.setTargetMethodName("sayHello"); operation.setTargetObjectURI(null); operation.setTargetURL("http://localhost:8080/HelloWorld/HelloWorld");*/ OperationInfo operation = new OperationInfo(); operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/"); operation.setInputMessageName("ConversionRateSoapIn"); operation.setInputMessageText( "<ns5:ConversionRate xmlns:ns5='http://www.webserviceX.NET/'><ns5:FromCurrency>EUR</ns5:FromCurrency><ns5:ToCurrency>SKK</ns5:ToCurrency></ns5:ConversionRate>"); operation.setNamespaceURI("http://www.webserviceX.NET/"); operation.setOutputMessageName("ConversionRateSoapOut"); operation.setOutputMessageText( "<ConversionRate><ConversionRateResult>0</ConversionRateResult></ConversionRate>"); operation.setSoapActionURI("http://www.webserviceX.NET/ConversionRate"); operation.setStyle("document"); operation.setTargetMethodName("ConversionRate"); operation.setTargetObjectURI(null); operation.setTargetURL("http://www.webservicex.net/CurrencyConvertor.asmx"); // Determine if the operation style is RPC boolean isRPC = operation.getStyle().equalsIgnoreCase("rpc"); // All connections are created by using a connection factory SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance(); // Now we can create a SOAPConnection object using the connection factory SOAPConnection connection = conFactory.createConnection(); // All SOAP messages are created by using a message factory MessageFactory msgFactory = MessageFactory.newInstance(); // Now we can create the SOAP message object SOAPMessage msg = msgFactory.createMessage(); // Get the SOAP part from the SOAP message object SOAPPart soapPart = msg.getSOAPPart(); // The SOAP part object will automatically contain the SOAP envelope SOAPEnvelope envelope = soapPart.getEnvelope(); //envelope.addNamespaceDeclaration("", operation.getNamespaceURI()); if (isRPC) { // Add namespace declarations to the envelope, usually only required for RPC/encoded envelope.addNamespaceDeclaration(XSI_NAMESPACE_PREFIX, XSI_NAMESPACE_URI); envelope.addNamespaceDeclaration(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE_URI); } // Get the SOAP header from the envelope SOAPHeader header = envelope.getHeader(); // The client does not yet support SOAP headers header.detachNode(); // Get the SOAP body from the envelope and populate it SOAPBody body = envelope.getBody(); // Create the default namespace for the SOAP body //body.addNamespaceDeclaration("", operation.getNamespaceURI()); // Add the service information String targetObjectURI = operation.getTargetObjectURI(); if (targetObjectURI == null) { // The target object URI should not be null targetObjectURI = ""; } // Add the service information //Name svcInfo = envelope.createName(operation.getTargetMethodName(), "", targetObjectURI); Name svcInfo = envelope.createName(operation.getTargetMethodName(), "ns2", operation.getNamespaceURI()); SOAPElement svcElem = body.addChildElement(svcInfo); if (isRPC) { // Set the encoding style of the service element svcElem.setEncodingStyle(operation.getEncodingStyle()); } // Add the message contents to the SOAP body Document doc = XMLSupport.readXML(operation.getInputMessageText()); if (doc.hasRootElement()) { // Begin building content buildSoapElement(envelope, svcElem, doc.getRootElement(), isRPC); } //svcElem.addTextNode(operation.getInputMessageText()); //svcElem. // Check for a SOAPAction String soapActionURI = operation.getSoapActionURI(); if (soapActionURI != null && soapActionURI.length() > 0) { // Add the SOAPAction value as a MIME header MimeHeaders mimeHeaders = msg.getMimeHeaders(); mimeHeaders.setHeader("SOAPAction", "\"" + operation.getSoapActionURI() + "\""); } // Save changes to the message we just populated msg.saveChanges(); // Get ready for the invocation URLEndpoint endpoint = new URLEndpoint(operation.getTargetURL()); // Show the URL endpoint message in the log ByteArrayOutputStream msgStream = new ByteArrayOutputStream(); msg.writeTo(msgStream); log.debug("SOAP Message MeasurementTarget URL: " + endpoint.getURL()); log.debug("SOAP Request: " + msgStream.toString()); // Make the call SOAPMessage response = connection.call(msg, endpoint); // Close the connection, we are done with it connection.close(); // Get the content of the SOAP response Source responseContent = response.getSOAPPart().getContent(); // Convert the SOAP response into a JDOM TransformerFactory tFact = TransformerFactory.newInstance(); Transformer transformer = tFact.newTransformer(); JDOMResult jdomResult = new JDOMResult(); transformer.transform(responseContent, jdomResult); // Get the document created by the transform operation Document responseDoc = jdomResult.getDocument(); // Send the response to the Log String strResponse = XMLSupport.outputString(responseDoc); log.debug("SOAP Response from: " + operation.getTargetMethodName() + ": " + strResponse); // Set the response as the output message operation.setOutputMessageText(strResponse); // Return the response generated //return strResponse; } catch (Throwable ex) { log.error("Error invoking operation:"); log.error(ex.getMessage()); } //return ""; }
From source file:com.wandrell.example.swss.test.util.factory.SecureSoapMessages.java
private static final SOAPMessage getMessageToSign(final String pathBase) throws SOAPException, IOException { final SOAPMessage soapMessage; final SOAPPart soapPart; final SOAPEnvelope soapEnvelope; final SOAPHeader soapHeader; final SOAPHeaderElement secElement; final SOAPElement binaryTokenElement; soapMessage = SoapMessageUtils.getMessage(pathBase); soapPart = soapMessage.getSOAPPart(); soapEnvelope = soapPart.getEnvelope(); soapHeader = soapEnvelope.getHeader(); secElement = soapHeader.addHeaderElement(soapEnvelope.createName("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")); binaryTokenElement = secElement.addChildElement(soapEnvelope.createName("BinarySecurityToken", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")); binaryTokenElement.setAttribute("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"); binaryTokenElement.setAttribute("ValueType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"); return soapMessage; }
From source file:eu.planets_project.tb.gui.backing.admin.wsclient.util.WSClient.java
/** * Invokes an operation using SAAJ//from www . j a v a 2 s. co m * * @param operation The operation to invoke */ public static String invokeOperation(OperationInfo operation) throws Exception { try { // Determine if the operation style is RPC boolean isRPC = false; if (operation.getStyle() != null) isRPC = operation.getStyle().equalsIgnoreCase("rpc"); else ; // All connections are created by using a connection factory SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance(); // Now we can create a SOAPConnection object using the connection factory SOAPConnection connection = conFactory.createConnection(); // All SOAP messages are created by using a message factory MessageFactory msgFactory = MessageFactory.newInstance(); // Now we can create the SOAP message object SOAPMessage msg = msgFactory.createMessage(); // Get the SOAP part from the SOAP message object SOAPPart soapPart = msg.getSOAPPart(); // The SOAP part object will automatically contain the SOAP envelope SOAPEnvelope envelope = soapPart.getEnvelope(); //my extension - START //envelope.addNamespaceDeclaration("_ns1", operation.getNamespaceURI()); //my extension - END if (isRPC) { // Add namespace declarations to the envelope, usually only required for RPC/encoded envelope.addNamespaceDeclaration(XSI_NAMESPACE_PREFIX, XSI_NAMESPACE_URI); envelope.addNamespaceDeclaration(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE_URI); } // Get the SOAP header from the envelope SOAPHeader header = envelope.getHeader(); // The client does not yet support SOAP headers header.detachNode(); // Get the SOAP body from the envelope and populate it SOAPBody body = envelope.getBody(); // Create the default namespace for the SOAP body //body.addNamespaceDeclaration("", operation.getNamespaceURI()); // Add the service information String targetObjectURI = operation.getTargetObjectURI(); if (targetObjectURI == null) { // The target object URI should not be null targetObjectURI = ""; } // Add the service information //Name svcInfo = envelope.createName(operation.getTargetMethodName(), "", targetObjectURI); Name svcInfo = envelope.createName(operation.getTargetMethodName(), "ns1", operation.getNamespaceURI()); SOAPElement svcElem = body.addChildElement(svcInfo); if (isRPC) { // Set the encoding style of the service element svcElem.setEncodingStyle(operation.getEncodingStyle()); } // Add the message contents to the SOAP body Document doc = XMLSupport.readXML(operation.getInputMessageText()); if (doc.hasRootElement()) { // Begin building content buildSoapElement(envelope, svcElem, doc.getRootElement(), isRPC); } //svcElem.addTextNode(operation.getInputMessageText()); //svcElem. // Check for a SOAPAction String soapActionURI = operation.getSoapActionURI(); if (soapActionURI != null && soapActionURI.length() > 0) { // Add the SOAPAction value as a MIME header MimeHeaders mimeHeaders = msg.getMimeHeaders(); mimeHeaders.setHeader("SOAPAction", "\"" + operation.getSoapActionURI() + "\""); } // Save changes to the message we just populated msg.saveChanges(); // Get ready for the invocation URLEndpoint endpoint = new URLEndpoint(operation.getTargetURL()); // Show the URL endpoint message in the log ByteArrayOutputStream msgStream = new ByteArrayOutputStream(); msg.writeTo(msgStream); log.debug("SOAP Message MeasurementTarget URL: " + endpoint.getURL()); log.debug("SOAP Request: " + msgStream.toString()); // Make the call SOAPMessage response = connection.call(msg, endpoint); // Close the connection, we are done with it connection.close(); // Get the content of the SOAP response Source responseContent = response.getSOAPPart().getContent(); // Convert the SOAP response into a JDOM TransformerFactory tFact = TransformerFactory.newInstance(); Transformer transformer = tFact.newTransformer(); JDOMResult jdomResult = new JDOMResult(); transformer.transform(responseContent, jdomResult); // Get the document created by the transform operation Document responseDoc = jdomResult.getDocument(); // Send the response to the Log String strResponse = XMLSupport.outputString(responseDoc); log.debug("SOAP Response from: " + operation.getTargetMethodName() + ": " + strResponse); // Set the response as the output message operation.setOutputMessageText(strResponse); // Return the response generated return strResponse; } catch (Throwable ex) { throw new Exception("Error invoking operation", ex); } }
From source file:cn.com.ttblog.ssmbootstrap_table.webservice.LicenseHandler.java
@SuppressWarnings("unchecked") @Override/*from ww w . ja v a2s . c om*/ public boolean handleMessage(SOAPMessageContext context) { try { Boolean out = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); logger.debug("LicenseHandler:{}", out); if (!out) { SOAPMessage message = context.getMessage(); logger.debug("SOAPMessage:{}", ToStringBuilder.reflectionToString(message)); SOAPEnvelope enve = message.getSOAPPart().getEnvelope(); SOAPHeader header = enve.getHeader(); SOAPBody body = enve.getBody(); Node bn = body.getChildNodes().item(0); String partname = bn.getLocalName(); if ("getUser".equals(partname)) { if (header == null) { // ? SOAPFault fault = body.addFault(); fault.setFaultString("??!"); throw new SOAPFaultException(fault); } Iterator<SOAPHeaderElement> iterator = header.extractAllHeaderElements(); if (!iterator.hasNext()) { // ? SOAPFault fault = body.addFault(); fault.setFaultString("??!"); throw new SOAPFaultException(fault); } while (iterator.hasNext()) { SOAPHeaderElement ele = iterator.next(); System.out.println(ele.getTextContent()); } } } } catch (SOAPException e) { e.printStackTrace(); } return true; }
From source file:be.fedict.eid.idp.protocol.ws_federation.sts.WSSecuritySoapHandler.java
private void handleInboundMessage(SOAPMessageContext context) throws SOAPException { SOAPMessage soapMessage = context.getMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPHeader soapHeader = soapEnvelope.getHeader(); if (null == soapHeader) { return;/* w w w . j a v a 2s .com*/ } Iterator<SOAPHeaderElement> headerIterator = soapHeader.examineAllHeaderElements(); while (headerIterator.hasNext()) { SOAPHeaderElement soapHeaderElement = headerIterator.next(); if (false == WSTrustConstants.WS_SECURITY_NAMESPACE.equals(soapHeaderElement.getNamespaceURI())) { continue; } if (false == "Security".equals(soapHeaderElement.getLocalName())) { continue; } Iterator<SOAPElement> securityElementIterator = soapHeaderElement.getChildElements(); while (securityElementIterator.hasNext()) { SOAPElement securityElement = securityElementIterator.next(); if (false == WSTrustConstants.SAML2_NAMESPACE.equals(securityElement.getNamespaceURI())) { continue; } if (false == "Assertion".equals(securityElement.getLocalName())) { continue; } LOG.debug("putting SAML token on JAX-WS context"); context.put(SAML_TOKEN_CONTEXT_ATTRIBUTE, securityElement); context.setScope(SAML_TOKEN_CONTEXT_ATTRIBUTE, Scope.APPLICATION); } } }
From source file:com.amazon.advertising.api.common.HmacSecurityHandler.java
public void invoke(MessageContext mc) throws AxisFault { String actionUri = mc.getSOAPActionURI(); String tokens[] = actionUri.split("/"); String action = tokens[tokens.length - 1]; String timestamp = getTimestamp(); String signature;//from w w w . j a v a2s . c o m try { signature = this.calculateSignature(action, timestamp); } catch (Exception e) { throw AxisFault.makeFault(e); } try { SOAPMessageContext smc = (SOAPMessageContext) mc; SOAPMessage message = smc.getMessage(); SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); SOAPHeader header = envelope.getHeader(); header.addNamespaceDeclaration(AWS_SECURITY_NS_PREFIX, AWS_SECURITY_NS); Name akidName = envelope.createName("AWSAccessKeyId", AWS_SECURITY_NS_PREFIX, AWS_SECURITY_NS); Name tsName = envelope.createName("Timestamp", AWS_SECURITY_NS_PREFIX, AWS_SECURITY_NS); Name sigName = envelope.createName("Signature", AWS_SECURITY_NS_PREFIX, AWS_SECURITY_NS); SOAPHeaderElement akidElement = header.addHeaderElement(akidName); SOAPHeaderElement tsElement = header.addHeaderElement(tsName); SOAPHeaderElement sigElement = header.addHeaderElement(sigName); akidElement.addTextNode(awsAccessKeyId); tsElement.addTextNode(timestamp); sigElement.addTextNode(signature); } catch (SOAPException e) { throw AxisFault.makeFault(e); } }