/** {@inheritDoc} */ @Override public boolean handleMessage(SOAPMessageContext smc) { Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (outboundProperty.booleanValue() && username != null && !"".equals(username.trim())) { try { SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope(); SOAPHeader header = envelope.getHeader(); if (header == null) { header = envelope.addHeader(); } SOAPElement securityElement = header.addChildElement(ELEMENT_SECURITY, PREFIX, SECURITY_URL); SOAPElement usernameTokenElement = securityElement.addChildElement(ELEMENT_USERNAME_TOKEN, PREFIX); SOAPElement usernameElement = usernameTokenElement.addChildElement(ELEMENT_USERNAME, PREFIX); usernameElement.addTextNode(username); SOAPElement passwordElement = usernameTokenElement.addChildElement(ELEMENT_PASSWORD, PREFIX); passwordElement.setAttribute(ATTRIBUTE_TYPE, PASSWORD_TYPE_URL); passwordElement.addTextNode(password); } catch (SOAPException e) { LOGGER.error("", e); } } return outboundProperty; }
/** @param args */ public static void main(String[] args) { try { MessageFactory factory = MessageFactory.newInstance(); SOAPMessage soapMsg = factory.createMessage(); SOAPPart part = soapMsg.getSOAPPart(); SOAPEnvelope envelope = part.getEnvelope(); SOAPHeader header = envelope.getHeader(); SOAPBody body = envelope.getBody(); header.addTextNode("Training Details"); SOAPBodyElement element = body.addBodyElement(envelope.createName("JAVA", "training", "http://shivasoft.in/blog")); element.addChildElement("WS").addTextNode("Training on Web service"); SOAPBodyElement element1 = body.addBodyElement(envelope.createName("JAVA", "training", "http://shivasoft.in/blog")); element1.addChildElement("Spring").addTextNode("Training on Spring 3.0"); soapMsg.writeTo(System.out); FileOutputStream fOut = new FileOutputStream("SoapMessage.xml"); soapMsg.writeTo(fOut); System.out.println(); System.out.println("SOAP msg created"); } catch (Exception e) { e.printStackTrace(); } }
/** Adds an "Access" element to the SOAP header */ public boolean handleRequest(MessageContext msgct) { if (msgct instanceof SOAPMessageContext) { SOAPMessageContext smsgct = (SOAPMessageContext) msgct; try { SOAPMessage msg = smsgct.getMessage(); SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope(); SOAPHeader header = msg.getSOAPHeader(); if (header == null) header = envelope.addHeader(); // add an header if non exists SOAPHeaderElement accessElement = header.addHeaderElement( envelope.createName( "Access", "ns0", "http://www.ipd.uni-karlsruhe.de/jplag/types")); SOAPElement usernameelem = accessElement.addChildElement("username"); usernameelem.addTextNode(username); SOAPElement passwordelem = accessElement.addChildElement("password"); passwordelem.addTextNode(password); SOAPElement compatelem = accessElement.addChildElement("compatLevel"); compatelem.addTextNode(compatibilityLevel + ""); } catch (SOAPException x) { System.out.println("Unable to create access SOAP header!"); x.printStackTrace(); } } return true; }
@Validated @Test public void testExamineHeader() { SOAPHeaderElement she = null; try { she1 = hdr.addHeaderElement(envelope.createName("foo1", "f1", "foo1-URI")); she1.setActor("actor-URI"); Iterator iterator = hdr.examineAllHeaderElements(); int cnt = 0; while (iterator.hasNext()) { cnt++; she = (SOAPHeaderElement) iterator.next(); if (!she.equals(she1)) { fail("SOAP Header Elements do not match"); } } if (cnt != 1) { fail("SOAPHeaderElement count mismatch: expected 1, received " + cnt); } iterator = hdr.examineAllHeaderElements(); if (!iterator.hasNext()) { fail("no elements in iterator - unexpected"); } } catch (Exception e) { fail("Unexpected Exception: " + e); } }
public void writeTo(SOAPMessage saaj) throws SOAPException { SOAPHeader header = saaj.getSOAPHeader(); SOAPHeaderElement she = header.addHeaderElement(new QName(getNamespaceURI(), getLocalPart())); she.addChildElement(actionLocalName); she.addTextNode(action); if (soapAction != null) { she.addChildElement(soapActionLocalName); she.addTextNode(soapAction); } }
@Validated @Test public void testAddHeaderElements() throws Exception { javax.xml.soap.SOAPMessage soapMessage = javax.xml.soap.MessageFactory.newInstance().createMessage(); javax.xml.soap.SOAPEnvelope soapEnv = soapMessage.getSOAPPart().getEnvelope(); javax.xml.soap.SOAPHeader header = soapEnv.getHeader(); try { header.addChildElement("ebxmlms1"); } catch (Exception e) { assertTrue(e instanceof SOAPException); } assertTrue( header.addChildElement("ebxmlms1", "ns-prefix", "http://test.apache.org") instanceof SOAPHeaderElement); ((SOAPHeaderElement) header.getFirstChild()).addTextNode("test add"); assertTrue( header.addHeaderElement( soapEnv.createName("ebxmlms2", "ns-prefix", "http://test2.apache.org")) != null); assertTrue( header.addHeaderElement( new PrefixedQName("http://test3.apache.org", "ebxmlms3", "ns-prefix")) != null); SOAPHeaderElement firstChild = (SOAPHeaderElement) header.getFirstChild(); assertEquals("ebxmlms1", firstChild.getLocalName()); assertEquals("ns-prefix", firstChild.getPrefix()); assertEquals("http://test.apache.org", firstChild.getNamespaceURI()); SOAPHeaderElement secondChild = (SOAPHeaderElement) firstChild.getNextSibling(); assertEquals("ebxmlms2", secondChild.getLocalName()); assertEquals("ns-prefix", secondChild.getPrefix()); assertEquals("http://test2.apache.org", secondChild.getNamespaceURI()); SOAPHeaderElement lastChild = (SOAPHeaderElement) header.getLastChild(); assertEquals("ebxmlms3", lastChild.getLocalName()); assertEquals("ns-prefix", lastChild.getPrefix()); assertEquals("http://test3.apache.org", lastChild.getNamespaceURI()); SOAPHeaderElement fourthChild = (SOAPHeaderElement) lastChild.getPreviousSibling(); assertEquals("ebxmlms2", fourthChild.getLocalName()); assertEquals("ns-prefix", fourthChild.getPrefix()); assertEquals("http://test2.apache.org", fourthChild.getNamespaceURI()); Iterator it = header.getChildElements(); int numOfHeaderElements = 0; while (it.hasNext()) { Object o = it.next(); assertTrue(o instanceof SOAPHeaderElement); SOAPHeaderElement el = (SOAPHeaderElement) o; String lName = el.getLocalName(); assertTrue(lName.equals("ebxmlms" + ++numOfHeaderElements)); } assertEquals(3, numOfHeaderElements); }
@Override protected boolean handleOutbound(MessageContext msgContext) { logger.trace("Handling Outbound Message"); if (httpHeaderName == null && httpCookieName == null) { throw logger.injectedValueMissing("Either httpHeaderName or httpCookieName should be set"); } HttpServletRequest servletRequest = getHttpRequest(msgContext); if (servletRequest == null) { throw logger.nullValueError("Http request"); } String token = getTokenValue(servletRequest); if (token == null) { throw logger.nullValueError("Null Token"); } SOAPElement security = null; try { security = create(token); } catch (SOAPException e) { logger.jbossWSUnableToCreateBinaryToken(e); } if (security == null) { logger.jbossWSUnableToCreateSecurityToken(); return true; } SOAPMessage sm = ((SOAPMessageContext) msgContext).getMessage(); SOAPEnvelope envelope; try { envelope = sm.getSOAPPart().getEnvelope(); SOAPHeader header = (SOAPHeader) Util.findElement(envelope, new QName(envelope.getNamespaceURI(), "Header")); if (header == null) { header = (SOAPHeader) envelope .getOwnerDocument() .createElementNS(envelope.getNamespaceURI(), envelope.getPrefix() + ":Header"); envelope.insertBefore(header, envelope.getFirstChild()); } header.addChildElement(security); } catch (SOAPException e) { logger.jbossWSUnableToCreateBinaryToken(e); } if (logger.isTraceEnabled()) { logger.trace("SOAP Message=" + SOAPUtil.soapMessageAsString(sm)); } return true; }
private Map toHeadersMap(SOAPMessage doc) { SOAPHeader header = getSOAPHeader(doc); if (header == null) { return new HashMap(0); } Map<String, String> headersMap = new HashMap(); NodeList nodes = header.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node item = nodes.item(i); if (item.hasChildNodes()) { headersMap.put(item.getLocalName(), item.getFirstChild().getNodeValue()); } } return headersMap; }
@Validated @Test public void testExamineHeaderElements2() throws Exception { javax.xml.soap.SOAPMessage soapMessage = javax.xml.soap.MessageFactory.newInstance().createMessage(); javax.xml.soap.SOAPEnvelope soapEnv = soapMessage.getSOAPPart().getEnvelope(); javax.xml.soap.SOAPHeader header = soapEnv.getHeader(); SOAPHeaderElement soapHeaderElement = null; try { // Add some soap header elements SOAPElement se = header .addHeaderElement(envelope.createName("Header1", "prefix", "http://myuri")) .addTextNode("This is Header1"); soapHeaderElement = (SOAPHeaderElement) se; soapHeaderElement.setMustUnderstand(true); se = header .addHeaderElement(envelope.createName("Header2", "prefix", "http://myuri")) .addTextNode("This is Header2"); soapHeaderElement = (SOAPHeaderElement) se; soapHeaderElement.setMustUnderstand(false); se = header .addHeaderElement(envelope.createName("Header3", "prefix", "http://myuri")) .addTextNode("This is Header3"); soapHeaderElement = (SOAPHeaderElement) se; soapHeaderElement.setMustUnderstand(true); se = header .addHeaderElement(envelope.createName("Header4", "prefix", "http://myuri")) .addTextNode("This is Header4"); soapHeaderElement = (SOAPHeaderElement) se; soapHeaderElement.setMustUnderstand(false); Iterator iterator = header.examineAllHeaderElements(); // validating Iterator count .... should be 4"); int cnt = 0; while (iterator.hasNext()) { cnt++; soapHeaderElement = (SOAPHeaderElement) iterator.next(); } assertEquals(cnt, 4); iterator = header.examineHeaderElements(SOAPConstants.URI_SOAP_ACTOR_NEXT); cnt = 0; while (iterator.hasNext()) { cnt++; soapHeaderElement = (SOAPHeaderElement) iterator.next(); } assertEquals(cnt, 0); } catch (Exception e) { fail("Unexpected Exception: " + e); } }
/** * Clear the soap MustUnderstand. * * @param soapHeader The SOAP header. * @param soapHeaderElement The SOAP header element. */ private void clearMustUnderstand( final SOAPHeader soapHeader, final SOAPHeaderElement soapHeaderElement) throws SOAPException { final Name headerName = soapHeader.getElementName(); final SOAPFactory factory = SOAPFactory.newInstance(); final Name attributeName = factory.createName("mustUnderstand", headerName.getPrefix(), headerName.getURI()); soapHeaderElement.removeAttribute(attributeName); }
@Validated @Test public void testAddNotUnderstoodHeaderElement() throws Exception { javax.xml.soap.SOAPMessage soapMessage = javax.xml.soap.MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(); javax.xml.soap.SOAPEnvelope soapEnv = soapMessage.getSOAPPart().getEnvelope(); javax.xml.soap.SOAPHeader header = soapEnv.getHeader(); SOAPElement soapElement = header.addNotUnderstoodHeaderElement(new QName("http://foo.org", "foo", "f")); assertNotNull(soapElement); Name name = soapElement.getElementName(); String uri = name.getURI(); String localName = name.getLocalName(); assertEquals(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE, uri); // Validate the LocalName which must be NotUnderstood assertEquals("NotUnderstood", localName); }
private void removeWSAHeader() throws SOAPOverUDPException { JAXBElement j = null; Unmarshaller u = SOAPOverUDPWsAddressingNamespaces.WS_ADDRESSING_2005_08.getUnmarshaller(); SOAPHeader header; try { header = soapMessage.getSOAPHeader(); } catch (SOAPException ex) { throw new SOAPOverUDPException("Unable to get SOAP header", ex); } // Loop through header and remove WSA elements for (Iterator<SOAPHeaderElement> i = header.examineAllHeaderElements(); i.hasNext(); ) { SOAPHeaderElement headerElement = i.next(); try { // Unmarshal the header element j = (JAXBElement) u.unmarshal(headerElement); } catch (UnmarshalException ex) { continue; // unknown element probably, just continue } catch (JAXBException ex) { throw new SOAPOverUDPException( "An unexpected error occured while unmarshalling header element " + headerElement.getTagName(), ex); } String tag = j.getName().getLocalPart(); if (j.getValue().getClass().equals(AttributedURIType.class)) { if (tag.equalsIgnoreCase("To") || tag.equalsIgnoreCase("Action") || tag.equalsIgnoreCase("MessageID")) headerElement.detachNode(); } else if (j.getValue().getClass().equals(RelatesToType.class)) { if (tag.equalsIgnoreCase("RelatesTo")) { headerElement.detachNode(); } } else if (j.getValue().getClass().equals(EndpointReferenceType.class)) { if (tag.equalsIgnoreCase("ReplyTo")) headerElement.detachNode(); } } }
@Override public boolean handleMessage(SOAPMessageContext context) { System.out.println("Client : handleMessage()......"); Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); // if this is a request, true for outbound messages, false for inbound if (isRequest) { try { SOAPMessage soapMsg = context.getMessage(); SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope(); SOAPHeader soapHeader = soapEnv.getHeader(); // if no header, add one if (soapHeader == null) { soapHeader = soapEnv.addHeader(); } // add a soap header, name as "mac address" QName qname = new QName("http://service.coupon.ronx.com/", "couponList"); SOAPHeaderElement soapHeaderElement = soapHeader.addHeaderElement(qname); soapHeaderElement.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT); // soapHeaderElement.addTextNode(mac); soapMsg.saveChanges(); // tracking soapMsg.writeTo(System.out); } catch (SOAPException | IOException e) { System.err.println(e); } } // continue other handler chain return true; }
/** * @param authHeader * @param qnameAuthHeader * @param soapHeader * @return SOAPHeaderElement */ private SOAPHeaderElement ProcessAuthHeader( AuthHeader authHeader, QName qnameAuthHeader, SOAPHeader soapHeader) { SOAPHeaderElement headerElement; try { /* * Create the authentication header element */ headerElement = soapHeader.addHeaderElement(qnameAuthHeader); /* * Check if Identifier is specified */ if (authHeader.getIdentifier() != null) { /* * Create Identifier element */ QName qName = new QName( qnameAuthHeader.getNamespaceURI(), AuthHeader.STR_Identifier, qnameAuthHeader.getPrefix()); SOAPElement element = soapFactory.createElement(qName); element.addTextNode(authHeader.getIdentifier()); headerElement.addChildElement(element); } /* * Check if PassKey is specified */ if (authHeader.getPasskey() != null) { /* * Create PassKey element */ QName qName = new QName( qnameAuthHeader.getNamespaceURI(), AuthHeader.STR_Passkey, qnameAuthHeader.getPrefix()); SOAPElement element = soapFactory.createElement(qName); element.addTextNode(authHeader.getPasskey()); headerElement.addChildElement(element); } } catch (SOAPException ex) { headerElement = null; } return headerElement; }
/* * ??? * * @param response * @param responseBean * @throws DOMException * @throws SOAPException */ private void extractHeaderDataSOAP(SOAPMessage response, HttpResponseBean responseBean) throws SOAPException { // extract MimeHeaders MimeHeaders mime = response.getMimeHeaders(); Iterator<MimeHeader> iter = mime.getAllHeaders(); while (iter.hasNext()) { MimeHeader mimeH = iter.next(); responseBean.addEntryToResponseHeaders(mimeH.getName(), mimeH.getValue()); } // extract SOAPHeaders from the envelope and a them to the mimeHeaders if (response.getSOAPHeader() != null) { javax.xml.soap.SOAPHeader header = response.getSOAPHeader(); NodeList nodes = header.getChildNodes(); for (int x = 0; x < nodes.getLength(); x++) { // if the header entry contains child nodes - write them with the node names if (nodes.item(x).hasChildNodes()) { NodeList childnodes = nodes.item(x).getChildNodes(); StringBuilder buff = new StringBuilder(); for (int y = 0; y < childnodes.getLength(); y++) { if (!"".equals(buff.toString())) { buff.append(" "); } buff.append(childnodes.item(y).getLocalName()).append(":"); buff.append(childnodes.item(y).getTextContent()); } responseBean.addEntryToResponseHeaders(nodes.item(x).getLocalName(), buff.toString()); } else { responseBean.addEntryToResponseHeaders( nodes.item(x).getLocalName(), nodes.item(x).getTextContent()); } } } }
@Override protected MessageContext createProtocolMessageContext(SoapMessage message) { SOAPMessageContextImpl sm = new SOAPMessageContextImpl(message); Exchange exch = message.getExchange(); setupBindingOperationInfo(exch, sm); SOAPMessage msg = sm.getMessage(); try { List<SOAPElement> params = new ArrayList<SOAPElement>(); message.put(MessageContext.REFERENCE_PARAMETERS, params); SOAPHeader head = msg.getSOAPHeader(); if (head != null) { Iterator<Node> it = CastUtils.cast(head.getChildElements()); while (it != null && it.hasNext()) { Node nd = it.next(); if (nd instanceof SOAPElement) { SOAPElement el = (SOAPElement) nd; if (el.hasAttributeNS(Names.WSA_NAMESPACE_NAME, "IsReferenceParameter") && ("1".equals(el.getAttributeNS(Names.WSA_NAMESPACE_NAME, "IsReferenceParameter")) || Boolean.parseBoolean( el.getAttributeNS(Names.WSA_NAMESPACE_NAME, "IsReferenceParameter")))) { params.add(el); } } } } if (msg.getSOAPPart().getEnvelope().getBody() != null && msg.getSOAPPart().getEnvelope().getBody().hasFault()) { return null; } } catch (SOAPException e) { throw new Fault(e); } return sm; }
@Validated @Test public void testAddUpgradeHeaderElement() throws Exception { javax.xml.soap.SOAPMessage soapMessage = javax.xml.soap.MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(); javax.xml.soap.SOAPEnvelope soapEnv = soapMessage.getSOAPPart().getEnvelope(); javax.xml.soap.SOAPHeader header = soapEnv.getHeader(); // create a list of supported URIs. ArrayList supported = new ArrayList(); supported.add(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE); supported.add(SOAPConstants.URI_NS_SOAP_ENVELOPE); SOAPElement soapElement = header.addUpgradeHeaderElement(supported.iterator()); assertNotNull(soapElement); Name name = soapElement.getElementName(); String uri = name.getURI(); String localName = name.getLocalName(); // Validate the URI which must be SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE); assertTrue(uri.equals(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE)); assertTrue(localName.equals("Upgrade")); }
@Override public void mapTo(Context context, SOAPBindingData target) throws Exception { SOAPMessage soapMessage = target.getSOAPMessage(); MimeHeaders mimeHeaders = soapMessage.getMimeHeaders(); SOAPHeader soapHeader = soapMessage.getSOAPHeader(); for (Property property : context.getProperties(Scope.IN)) { Object value = property.getValue(); if (value != null) { String name = property.getName(); QName qname = XMLHelper.createQName(name); boolean qualifiedForSoapHeader = Strings.trimToNull(qname.getNamespaceURI()) != null; if (qualifiedForSoapHeader && matches(qname)) { if (value instanceof Node) { Node domNode = soapHeader.getOwnerDocument().importNode((Node) value, true); soapHeader.appendChild(domNode); } else if (value instanceof Configuration) { Element configElement = new ElementPuller().pull(new StringReader(value.toString())); Node configNode = soapHeader.getOwnerDocument().importNode(configElement, true); soapHeader.appendChild(configNode); } else { String v = value.toString(); if (SOAPHeadersType.XML.equals(getSOAPHeadersType())) { try { Element xmlElement = new ElementPuller().pull(new StringReader(v)); Node xmlNode = soapHeader.getOwnerDocument().importNode(xmlElement, true); soapHeader.appendChild(xmlNode); } catch (Throwable t) { soapHeader.addChildElement(qname).setValue(v); } } else { soapHeader.addChildElement(qname).setValue(v); } } } else { if (matches(name)) { mimeHeaders.addHeader(name, String.valueOf(value)); } } } } }
@Validated @Test public void testExamineHeaderElements() throws Exception { javax.xml.soap.SOAPMessage soapMessage = javax.xml.soap.MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(); javax.xml.soap.SOAPEnvelope soapEnv = soapMessage.getSOAPPart().getEnvelope(); javax.xml.soap.SOAPHeader header = soapEnv.getHeader(); SOAPHeaderElement soapHeaderElement = header.addHeaderElement(envelope.createName("foo1", "f1", "foo1-URI")); Iterator iterator = null; soapHeaderElement.setRole("role-URI"); iterator = header.examineHeaderElements("role1-URI"); int count = 0; while (iterator.hasNext()) { count++; iterator.next(); } assertEquals(0, count); }
/** Returns the security header element. */ private Element getSecurityHeader(SOAPMessage soapMessage) throws SOAPBindingException { try { SOAPHeader header = soapMessage.getSOAPPart().getEnvelope().getHeader(); NodeList headerChildNodes = header.getChildNodes(); if ((headerChildNodes == null) || (headerChildNodes.getLength() == 0)) { throw new SOAPBindingException(WSSUtils.bundle.getString("noSecurityHeader")); } for (int i = 0; i < headerChildNodes.getLength(); i++) { Node currentNode = headerChildNodes.item(i); if (currentNode.getNodeType() != Node.ELEMENT_NODE) { continue; } if ((WSSEConstants.TAG_SECURITYT.equals(currentNode.getLocalName())) && (WSSEConstants.NS_WSSE_WSF11.equals(currentNode.getNamespaceURI()))) { return (Element) currentNode; } } return null; } catch (SOAPException se) { WSSUtils.debug.error("MessageProcess.getSecurityHeader:: " + "SOAPException", se); throw new SOAPBindingException(WSSUtils.bundle.getString("noSecurityHeader")); } }
@Validated @Test public void testQNamesOnHeader() { SOAPHeaderElement headerElement = null; try { // SOAP1.1 and SOAP1.2 requires all HeaderElements to be namespace qualified // Try adding HeaderElement with unqualified QName not belonging to any namespace // (expect SOAPException) headerElement = hdr.addHeaderElement(envelope.createName("Transaction")); fail("Did not throw expected SOAPException"); } catch (SOAPException e) { // Did throw expected SOAPException } catch (Exception e) { fail("Unexpected Exception: " + e.getMessage()); } }
@Validated @Test public void testAppendChild() throws Exception { MessageFactory fact = MessageFactory.newInstance(); SOAPMessage message = fact.createMessage(); SOAPHeader soapHeader = message.getSOAPHeader(); assertEquals(0, soapHeader.getChildNodes().getLength()); assertFalse(soapHeader.getChildElements().hasNext()); Document doc = soapHeader.getOwnerDocument(); String namespace = "http://example.com"; String localName = "GetLastTradePrice"; Element getLastTradePrice = doc.createElementNS(namespace, localName); Element symbol = doc.createElement("symbol"); symbol.setAttribute("foo", "bar"); getLastTradePrice.appendChild(symbol); org.w3c.dom.Text def = doc.createTextNode("DEF"); symbol.appendChild(def); soapHeader.appendChild(getLastTradePrice); assertEquals(1, soapHeader.getChildNodes().getLength()); Iterator iter = soapHeader.getChildElements(); assertTrue(iter.hasNext()); Object obj = iter.next(); // must be SOAPHeaderElement assertTrue(obj instanceof SOAPHeaderElement); SOAPElement soapElement = (SOAPElement) obj; assertEquals(namespace, soapElement.getNamespaceURI()); assertEquals(localName, soapElement.getLocalName()); iter = soapElement.getChildElements(); assertTrue(iter.hasNext()); obj = iter.next(); assertTrue(obj instanceof SOAPElement); soapElement = (SOAPElement) obj; assertEquals(null, soapElement.getNamespaceURI()); assertEquals("symbol", soapElement.getLocalName()); assertFalse(iter.hasNext()); iter = soapElement.getChildElements(); assertTrue(iter.hasNext()); obj = iter.next(); assertTrue(obj instanceof Text); Text text = (Text) obj; assertEquals("DEF", text.getData()); assertFalse(iter.hasNext()); }
@Override public void addXTeeHeaderElements(SOAPEnvelope env, XTeeServiceConfiguration serviceConfiguration) throws SOAPException { SOAPHeader header = env.getHeader(); SOAPElement pasutus = header.addChildElement("asutus", "ns4"); SOAPElement pandmekogu = header.addChildElement("andmekogu", "ns4"); SOAPElement ikood = header.addChildElement("isikukood", "ns4"); SOAPElement id = header.addChildElement("id", "ns4"); SOAPElement pnimi = header.addChildElement("nimi", "ns4"); String toimik = serviceConfiguration.getFile(); if (toimik != null) { SOAPElement toimikEl = header.addChildElement("toimik", "ns4"); toimikEl.addTextNode(toimik); } pasutus.addAttribute(env.createName("xsi:type"), "xsd:string"); pandmekogu.addAttribute(env.createName("xsi:type"), "xsd:string"); ikood.addAttribute(env.createName("xsi:type"), "xsd:string"); id.addAttribute(env.createName("xsi:type"), "xsd:string"); pnimi.addAttribute(env.createName("xsi:type"), "xsd:string"); pasutus.addTextNode(serviceConfiguration.getInstitution()); pandmekogu.addTextNode(serviceConfiguration.getDatabase()); ikood.addTextNode(serviceConfiguration.getIdCode()); id.addTextNode(generateUniqueMessageId(serviceConfiguration)); StringBuilder sb = new StringBuilder(serviceConfiguration.getDatabase()); sb.append("."); sb.append(serviceConfiguration.getMethod()); sb.append("."); sb.append(serviceConfiguration.getVersion() == null ? "v1" : serviceConfiguration.getVersion()); pnimi.addTextNode(sb.toString()); // deprecated: // http://ftp.ria.ee/pub/x-tee/doc/nouded_infosysteemidele.pdf if (serviceConfiguration.useDeprecatedApi()) { SOAPElement pametnik = header.addChildElement("ametnik", "ns4"); pametnik.addAttribute(env.createName("xsi:type"), "xsd:string"); pametnik.addTextNode(serviceConfiguration.getIdCode()); } }
/** * Find Base64 encoded certificate used to sign given message. No default constructor: Once * content has been created, remains unchanged for life of the instance. * * @param msg (received) SOAP message to parse * @exception JAXRException if any problem at all occurs, wrapping problems decoding content (from * Base64) and any caught CertificateException or SOAPException */ public ReceivedCertificate(SOAPMessage msg) throws JAXRException { // @wss:Id attribute value for <BinarySecurityToken/> element of interest final String tokenId = CanonicalConstants.CANONICAL_URI_SENDER_CERT; try { final Name binSecTokenName = SOAPFactory.newInstance().createName("BinarySecurityToken", "wsse", securityNS); SOAPHeader hdr = msg.getSOAPHeader(); Iterator hdrElemIter = hdr.examineAllHeaderElements(); while (hdrElemIter.hasNext()) { Object hdrElemObj = hdrElemIter.next(); if (hdrElemObj instanceof SOAPHeaderElement) { // found a SOAP header element of some type SOAPHeaderElement hdrElem = (SOAPHeaderElement) hdrElemObj; if ((hdrElem.getLocalName().equals("Security")) && (hdrElem.getNamespaceURI().equals(securityNS))) { // found a <wss:Security/> element // Name binSecTokenName = SOAPFactory.newInstance(). // createName("BinarySecurityToken", "wsse", securityNS); Iterator secTokensIter = hdrElem.getChildElements(binSecTokenName); while (secTokensIter.hasNext()) { Object binSecTokenObj = secTokensIter.next(); if (binSecTokenObj instanceof Element) { // found a <BinarySecurityToken/> element Element binSecTokenElem = (Element) binSecTokenObj; String _tokenId = binSecTokenElem.getAttributeNS(securityUtilityNS, "Id"); if (_tokenId.equals(tokenId)) { // found propery identified element if (null == cert) { // found first cert content InputStream is = null; String encodedData = binSecTokenElem.getFirstChild().getNodeValue(); try { try { is = new ByteArrayInputStream(encodedData.getBytes("UTF-8")); is = MimeUtility.decode(is, "base64"); } catch (Exception e) { throw new JAXRException( CommonResourceBundle.getInstance() .getString("message.UnableToDecodeData"), e); } CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(is); } finally { if (is != null) { try { is.close(); } catch (Exception e) { } } } } else { // found second cert content foundMultiple = true; break; } } } } } } } } catch (SOAPException e) { throw new JAXRException( CommonResourceBundle.getInstance().getString("message.CouldNotGetCertificate"), e); } catch (CertificateException e) { throw new JAXRException( CommonResourceBundle.getInstance().getString("message.CouldNotGetCertificate"), e); } }
public void writeTo(SOAPMessage saaj) throws SOAPException { SOAPHeader header = saaj.getSOAPHeader(); if (header == null) header = saaj.getSOAPPart().getEnvelope().addHeader(); Node clone = header.getOwnerDocument().importNode(node, true); header.appendChild(clone); }
public boolean handleMessage(SOAPMessageContext context) { boolean isSuccess = true; SOAPMessage message = null; boolean isRequest = false; String msgType = Constant.MESSAGE_TYPE_REQUEST; String requestID = null; String requestTimeStamp = null; String responseTimeStamp = null; String nameSpace = null; String webServiceName = null; try { if (context != null) { // get soap message from context message = context.getMessage(); if (message != null) { isRequest = ((Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)).booleanValue(); if (isRequest) { // assign a unique request id requestID = UUID.randomUUID().toString(); context.put(Constant.WS_REQUEST_ID, requestID); // get the request time stamp requestTimeStamp = Utility.getTimeStamp(Constant.WS_TIMESTAMP_FORMAT); // find the name space and service name QName wsdlService = null; if (context.get(SOAPMessageContext.WSDL_SERVICE) != null) { wsdlService = (QName) context.get(SOAPMessageContext.WSDL_SERVICE); nameSpace = wsdlService.getNamespaceURI(); webServiceName = wsdlService.getLocalPart(); context.put(Constant.WS_NAME, webServiceName); } // dump the request dump(message, msgType, requestTimeStamp, webServiceName, requestID); // add the authentication header QName userNameElement = new QName(nameSpace, Constant.SOAP_USERNAME); QName passwordElement = new QName(nameSpace, Constant.SOAP_PASSWORD); SOAPHeader header = message.getSOAPHeader(); SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); header = soapEnvelope.addHeader(); SOAPElement userNameSOAPElement = header.addChildElement(userNameElement); userNameSOAPElement.addTextNode(Utility.getWSProperty(Constant.USERNAME_KEY)); SOAPElement passwordSOAPElement = header.addChildElement(passwordElement); passwordSOAPElement.addTextNode( Utility.convertHexToString(Utility.getWSProperty(Constant.PASSWORD_KEY))); } else { msgType = Constant.MESSAGE_TYPE_RESPONSE; requestID = (String) context.get(Constant.WS_REQUEST_ID); webServiceName = (String) context.get(Constant.WS_NAME); responseTimeStamp = Utility.getTimeStamp(Constant.WS_TIMESTAMP_FORMAT); if (message.getSOAPHeader() != null) { message.getSOAPHeader().detachNode(); } dump(message, msgType, responseTimeStamp, webServiceName, requestID); } } } } catch (Exception e) { } return isSuccess; }
public SOAPMessage buildPullMessage( URI uri, String enumerationContext, String resourceUri, int maxElements, int timeout) throws SOAPException { MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); SOAPMessage soapMessage = messageFactory.createMessage(); SOAPEnvelope env = soapMessage.getSOAPPart().getEnvelope(); env.removeNamespaceDeclaration(env.getPrefix()); env.setPrefix("s"); env.addNamespaceDeclaration("a", NS_WS_ADDRESSING); env.addNamespaceDeclaration("w", NS_WS_MANAGEMENT); env.addNamespaceDeclaration("n", NS_WS_ENUMERATION); env.addNamespaceDeclaration("ev", NS_WS_EVENTING); QName mustUnderstand = new QName(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE, "mustUnderstand", "s"); SOAPHeader soapHeader = soapMessage.getSOAPHeader(); soapHeader.setPrefix("s"); SOAPHeaderElement toHeader = soapHeader.addHeaderElement(new QName(NS_WS_ADDRESSING, "To", "a")); toHeader.setValue(uri.toString()); SOAPHeaderElement resourceURI = soapHeader.addHeaderElement(new QName(NS_WS_MANAGEMENT, "ResourceURI", "w")); resourceURI.addAttribute(mustUnderstand, "true"); resourceURI.setValue(resourceUri); SOAPHeaderElement replyTo = soapHeader.addHeaderElement(new QName(NS_WS_ADDRESSING, "ReplyTo", "a")); SOAPElement addressElement = replyTo.addChildElement(new QName(NS_WS_ADDRESSING, "Address", "a")); addressElement.addAttribute(mustUnderstand, "true"); addressElement.addTextNode("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous"); SOAPElement actionElement = soapHeader.addChildElement(new QName(NS_WS_ADDRESSING, "Action", "a")); actionElement.addAttribute(mustUnderstand, "true"); actionElement.addTextNode(ENUMERATION_PULL); // MaxEnvelopeSize SOAPElement maxEnvelopeSize = soapHeader.addChildElement(new QName(NS_WS_MANAGEMENT, "MaxEnvelopeSize", "w")); maxEnvelopeSize.addAttribute(mustUnderstand, "true"); maxEnvelopeSize.addTextNode("51200"); // Message ID SOAPElement messageId = soapHeader.addChildElement(new QName(NS_WS_ADDRESSING, "MessageID", "a")); messageId.addTextNode("uuid:" + UUID.randomUUID().toString()); // Locale // SOAPElement locale = soapHeader.addChildElement(new // QName(NS_WS_MANAGEMENT, "Locale", "w")); // locale.addAttribute(mustUnderstand, "false"); // locale.addAttribute(new QName("xml", "lang"), "en-US"); SOAPElement operationTimeout = soapHeader.addChildElement(new QName(NS_WS_MANAGEMENT, "OperationTimeout", "w")); operationTimeout.addTextNode(String.format("PT%d.000S", timeout)); SOAPBody soapBody = soapMessage.getSOAPBody(); soapBody.setPrefix("s"); SOAPElement pullElement = soapBody.addBodyElement(new QName(NS_WS_ENUMERATION, "Pull", "n")); SOAPElement enumerationContextElement = pullElement.addChildElement(new QName(NS_WS_ENUMERATION, "EnumerationContext", "n")); enumerationContextElement.setTextContent(enumerationContext); // SOAPElement maxTime = pullElement.addChildElement(new // QName(NS_WS_ENUMERATION, "MaxTime", "n")); // maxTime.setTextContent("PS60S"); SOAPElement maxElement = pullElement.addChildElement(new QName(NS_WS_ENUMERATION, "MaxElements", "n")); maxElement.setTextContent(String.valueOf(maxElements)); // SOAPElement maxCharacters = pullElement.addChildElement(new // QName(NS_WS_ENUMERATION, "MaxCharacters", "n")); // enumerationContextElement.setTextContent("250000"); return soapMessage; }
public SOAPMessage buildWQLQuery( URI uri, String namespace, String query, int maxElements, int timeout) throws SOAPException { MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); SOAPMessage soapMessage = messageFactory.createMessage(); SOAPEnvelope env = soapMessage.getSOAPPart().getEnvelope(); env.removeNamespaceDeclaration(env.getPrefix()); env.setPrefix("s"); env.addNamespaceDeclaration("a", NS_WS_ADDRESSING); env.addNamespaceDeclaration("w", NS_WS_MANAGEMENT); env.addNamespaceDeclaration("en", NS_WS_ENUMERATION); QName mustUnderstand = new QName(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE, "mustUnderstand", "s"); SOAPHeader soapHeader = soapMessage.getSOAPHeader(); soapHeader.setPrefix("s"); SOAPHeaderElement toHeader = soapHeader.addHeaderElement(new QName(NS_WS_ADDRESSING, "To", "a")); toHeader.setValue(uri.toString()); SOAPHeaderElement resourceURI = soapHeader.addHeaderElement(new QName(NS_WS_MANAGEMENT, "ResourceURI", "w")); resourceURI.addAttribute(mustUnderstand, "true"); resourceURI.setValue(WSMAN_WMI_PREFIX + "/" + namespace + "/*"); SOAPHeaderElement replyTo = soapHeader.addHeaderElement(new QName(NS_WS_ADDRESSING, "ReplyTo", "a")); SOAPElement addressElement = replyTo.addChildElement(new QName(NS_WS_ADDRESSING, "Address", "a")); addressElement.addAttribute(mustUnderstand, "true"); addressElement.addTextNode("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous"); SOAPElement actionElement = soapHeader.addChildElement(new QName(NS_WS_ADDRESSING, "Action", "a")); actionElement.addTextNode(ENUMERATION_ENUMERATE); // MaxEnvelopeSize SOAPElement maxEnvelopeSize = soapHeader.addChildElement(new QName(NS_WS_MANAGEMENT, "MaxEnvelopeSize", "w")); maxEnvelopeSize.addAttribute(mustUnderstand, "true"); maxEnvelopeSize.addTextNode("51200"); // Message ID SOAPElement messageId = soapHeader.addChildElement(new QName(NS_WS_ADDRESSING, "MessageID", "a")); messageId.addTextNode("uuid:" + UUID.randomUUID().toString()); // Locale // SOAPElement locale = soapHeader.addChildElement(new // QName(NS_WS_MANAGEMENT, "Locale", "w")); // locale.addAttribute(mustUnderstand, "false"); // locale.addAttribute(new QName("xml", "lang"), "en-US"); SOAPElement operationTimeout = soapHeader.addChildElement(new QName(NS_WS_MANAGEMENT, "OperationTimeout", "w")); operationTimeout.addTextNode(String.format("PT%d.000S", timeout)); SOAPBody soapBody = soapMessage.getSOAPBody(); soapBody.setPrefix("s"); SOAPElement enumerateElement = soapBody.addBodyElement(new QName(NS_WS_ENUMERATION, "Enumerate", "en")); // Return in the same response enumerateElement.addChildElement(new QName(NS_WS_MANAGEMENT, "OptimizeEnumeration", "w")); SOAPElement maxElement = enumerateElement.addChildElement(new QName(NS_WS_MANAGEMENT, "MaxElements", "w")); maxElement.addTextNode(String.valueOf(maxElements)); SOAPElement filterElement = enumerateElement.addChildElement(new QName(NS_WS_MANAGEMENT, "Filter", "w")); filterElement.setAttribute("Dialect", DIALECT_WQL); filterElement.addTextNode(query); return soapMessage; }
public SOAPMessage buildEventSubscription( URI uri, String subscriptionQuery, int maxElements, int timeout) throws SOAPException { // EVENT_LOG_NOTIFICATION_QUERY = """ // SELECT * FROM __InstanceCreationEvent // WHERE TargetInstance ISA 'Win32_NTLogEvent' // AND TargetInstance.EventType <= %d // """ MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); SOAPMessage soapMessage = messageFactory.createMessage(); SOAPEnvelope env = soapMessage.getSOAPPart().getEnvelope(); env.removeNamespaceDeclaration(env.getPrefix()); env.setPrefix("s"); env.addNamespaceDeclaration("a", NS_WS_ADDRESSING); env.addNamespaceDeclaration("w", NS_WS_MANAGEMENT); env.addNamespaceDeclaration("en", NS_WS_ENUMERATION); env.addNamespaceDeclaration("ev", NS_WS_EVENTING); QName mustUnderstand = new QName(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE, "mustUnderstand", "s"); SOAPHeader soapHeader = soapMessage.getSOAPHeader(); soapHeader.setPrefix("s"); SOAPHeaderElement toHeader = soapHeader.addHeaderElement(new QName(NS_WS_ADDRESSING, "To", "a")); toHeader.setValue(uri.toString()); SOAPHeaderElement resourceURI = soapHeader.addHeaderElement(new QName(NS_WS_MANAGEMENT, "ResourceURI", "w")); resourceURI.addAttribute(mustUnderstand, "true"); resourceURI.setValue(WSMAN_EVENTLOG_PREFIX); SOAPHeaderElement replyTo = soapHeader.addHeaderElement(new QName(NS_WS_ADDRESSING, "ReplyTo", "a")); SOAPElement addressElement = replyTo.addChildElement(new QName(NS_WS_ADDRESSING, "Address", "a")); addressElement.addAttribute(mustUnderstand, "true"); addressElement.addTextNode("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous"); SOAPElement actionElement = soapHeader.addChildElement(new QName(NS_WS_ADDRESSING, "Action", "a")); actionElement.addTextNode(EVENTING_SUBSCRIBE); // MaxEnvelopeSize SOAPElement maxEnvelopeSize = soapHeader.addChildElement(new QName(NS_WS_MANAGEMENT, "MaxEnvelopeSize", "w")); maxEnvelopeSize.addAttribute(mustUnderstand, "true"); maxEnvelopeSize.addTextNode("51200"); // Message ID SOAPElement messageId = soapHeader.addChildElement(new QName(NS_WS_ADDRESSING, "MessageID", "a")); messageId.addTextNode("uuid:" + UUID.randomUUID().toString()); // Locale // SOAPElement locale = soapHeader.addChildElement(new // QName(NS_WS_MANAGEMENT, "Locale", "w")); // locale.addAttribute(mustUnderstand, "false"); // locale.addAttribute(new QName("xml", "lang"), "en-US"); SOAPElement operationTimeout = soapHeader.addChildElement(new QName(NS_WS_MANAGEMENT, "OperationTimeout", "w")); operationTimeout.addTextNode(String.format("PT%d.000S", timeout)); SOAPBody soapBody = soapMessage.getSOAPBody(); soapBody.setPrefix("s"); SOAPElement enumerateElement = soapBody.addBodyElement(new QName(NS_WS_EVENTING, "Subscribe", "ev")); SOAPElement deliveryElement = enumerateElement.addChildElement(new QName(NS_WS_EVENTING, "Delivery", "ev")); deliveryElement.setAttribute("Mode", "http://schemas.dmtf.org/wbem/wsman/1/wsman/Pull"); SOAPElement expiresElement = enumerateElement.addChildElement(new QName(NS_WS_EVENTING, "Expires", "ev")); // EXPIRE in 60 seconds - don't do this normally! expiresElement.addTextNode(String.format("PT%dS", new Date().getTime() + 500)); // "PT60S"); // <ev:Expires>[xs:dateTime | xs:duration]</ev:Expires> SOAPElement filterElement = enumerateElement.addChildElement(new QName(NS_WS_MANAGEMENT, "Filter", "w")); filterElement.setAttribute("Dialect", DIALECT_EVENTQUERY); // Need to convert the XML snippet specified in the subscriptionQuery try { filterElement.addChildElement(new Util().xmlToSOAPElement(subscriptionQuery)); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Tell them to send bookmarks so we can catch up later if we get // disconnected enumerateElement.addChildElement(new QName(NS_WS_MANAGEMENT, "SendBookmarks", "w")); return soapMessage; }
public SOAPMessage buildUnsubscribeMessage( URI uri, String enumerationContext, String subscriptionId, int maxElements, int timeout) throws SOAPException { MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); SOAPMessage soapMessage = messageFactory.createMessage(); SOAPEnvelope env = soapMessage.getSOAPPart().getEnvelope(); env.removeNamespaceDeclaration(env.getPrefix()); env.setPrefix("s"); env.addNamespaceDeclaration("a", NS_WS_ADDRESSING); env.addNamespaceDeclaration("w", NS_WS_MANAGEMENT); env.addNamespaceDeclaration("en", NS_WS_ENUMERATION); env.addNamespaceDeclaration("ev", NS_WS_EVENTING); QName mustUnderstand = new QName(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE, "mustUnderstand", "s"); SOAPHeader soapHeader = soapMessage.getSOAPHeader(); soapHeader.setPrefix("s"); SOAPHeaderElement toHeader = soapHeader.addHeaderElement(new QName(NS_WS_ADDRESSING, "To", "a")); toHeader.setValue(uri.toString()); SOAPHeaderElement resourceURI = soapHeader.addHeaderElement(new QName(NS_WS_MANAGEMENT, "ResourceURI", "w")); resourceURI.addAttribute(mustUnderstand, "true"); resourceURI.setValue(WSMAN_EVENTLOG_PREFIX); SOAPHeaderElement replyTo = soapHeader.addHeaderElement(new QName(NS_WS_ADDRESSING, "ReplyTo", "a")); SOAPElement addressElement = replyTo.addChildElement(new QName(NS_WS_ADDRESSING, "Address", "a")); addressElement.addAttribute(mustUnderstand, "true"); addressElement.addTextNode("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous"); SOAPElement actionElement = soapHeader.addChildElement(new QName(NS_WS_ADDRESSING, "Action", "a")); actionElement.addTextNode(EVENTING_UNSUBSCRIBE); // MaxEnvelopeSize SOAPElement maxEnvelopeSize = soapHeader.addChildElement(new QName(NS_WS_MANAGEMENT, "MaxEnvelopeSize", "w")); maxEnvelopeSize.addAttribute(mustUnderstand, "true"); maxEnvelopeSize.addTextNode("51200"); // Message ID SOAPElement messageId = soapHeader.addChildElement(new QName(NS_WS_ADDRESSING, "MessageID", "a")); messageId.addTextNode("uuid:" + UUID.randomUUID().toString()); SOAPElement operationTimeout = soapHeader.addChildElement(new QName(NS_WS_MANAGEMENT, "OperationTimeout", "w")); operationTimeout.addTextNode(String.format("PT%d.000S", timeout)); SOAPElement hsubId = soapHeader.addChildElement(new QName(NS_WS_EVENTING, "Identifier", "ev")); hsubId.addTextNode(subscriptionId); SOAPBody soapBody = soapMessage.getSOAPBody(); soapBody.setPrefix("s"); soapBody.addChildElement(new QName(NS_WS_EVENTING, "Unsubscribe", "ev")); return soapMessage; }