Java Code Examples for javax.xml.soap.SOAPEnvelope#getHeader()

The following examples show how to use javax.xml.soap.SOAPEnvelope#getHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InsurabilityHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void initMessageID(SOAPMessage msg) throws SOAPException {
	SOAPPart part = msg.getSOAPPart();
	if (part != null) {
		SOAPEnvelope soapEnvelope = part.getEnvelope();
		if (soapEnvelope != null) {
			SOAPHeader header = soapEnvelope.getHeader();
			
			if (header != null && header.getChildElements().hasNext()) {
				Node elementsResponseHeader = (Node) header.getChildElements().next();
				if (elementsResponseHeader != null && elementsResponseHeader.getLocalName() != null && elementsResponseHeader.getLocalName().equals("MessageID")) {
					NodeList elementsheader = elementsResponseHeader.getChildNodes();
					org.w3c.dom.Node element = elementsheader.item(0);
					messageId = element.getNodeValue();
					LOG.info("MyCareNet returned a response with messageId: " + messageId);
				}
			}
		}
	}
}
 
Example 2
Source File: InsurabilityHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void initMessageID(SOAPMessage msg) throws SOAPException {
   SOAPPart part = msg.getSOAPPart();
   if (part != null) {
      SOAPEnvelope soapEnvelope = part.getEnvelope();
      if (soapEnvelope != null) {
         SOAPHeader header = soapEnvelope.getHeader();
         if (header != null && header.getChildElements().hasNext()) {
            Node elementsResponseHeader = (Node)header.getChildElements().next();
            if (elementsResponseHeader != null && elementsResponseHeader.getLocalName() != null && elementsResponseHeader.getLocalName().equals("MessageID")) {
               NodeList elementsheader = elementsResponseHeader.getChildNodes();
               org.w3c.dom.Node element = elementsheader.item(0);
               messageId = element.getNodeValue();
               LOG.info("MyCareNet returned a response with messageId: " + messageId);
            }
         }
      }
   }

}
 
Example 3
Source File: InsurabilityHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void initMessageID(SOAPMessage msg) throws SOAPException {
	SOAPPart part = msg.getSOAPPart();
	if (part != null) {
		SOAPEnvelope soapEnvelope = part.getEnvelope();
		if (soapEnvelope != null) {
			SOAPHeader header = soapEnvelope.getHeader();
			
			if (header != null && header.getChildElements().hasNext()) {
				Node elementsResponseHeader = (Node) header.getChildElements().next();
				if (elementsResponseHeader != null && elementsResponseHeader.getLocalName() != null && elementsResponseHeader.getLocalName().equals("MessageID")) {
					NodeList elementsheader = elementsResponseHeader.getChildNodes();
					org.w3c.dom.Node element = elementsheader.item(0);
					messageId = element.getNodeValue();
					LOG.info("MyCareNet returned a response with messageId: " + messageId);
				}
			}
		}
	}
}
 
Example 4
Source File: InsurabilityHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void initMessageID(SOAPMessage msg) throws SOAPException {
	SOAPPart part = msg.getSOAPPart();
	if (part != null) {
		SOAPEnvelope soapEnvelope = part.getEnvelope();
		if (soapEnvelope != null) {
			SOAPHeader header = soapEnvelope.getHeader();
			
			if (header != null && header.getChildElements().hasNext()) {
				Node elementsResponseHeader = (Node) header.getChildElements().next();
				if (elementsResponseHeader != null && elementsResponseHeader.getLocalName() != null && elementsResponseHeader.getLocalName().equals("MessageID")) {
					NodeList elementsheader = elementsResponseHeader.getChildNodes();
					org.w3c.dom.Node element = elementsheader.item(0);
					messageId = element.getNodeValue();
					LOG.info("MyCareNet returned a response with messageId: " + messageId);
				}
			}
		}
	}
}
 
Example 5
Source File: XRoadProtocolNamespaceStrategyV4.java    From j-road with Apache License 2.0 6 votes vote down vote up
@Override
public void addXTeeHeaderElements(SOAPEnvelope env, XRoadServiceConfiguration conf) throws SOAPException {
  SOAPHeader header = env.getHeader();
  if(StringUtils.isNotBlank(conf.getIdCode())) {
    SOAPElement userId = header.addChildElement("userId", protocol.getNamespacePrefix());
    userId.addTextNode(conf.getIdCode());
  }
  SOAPElement id = header.addChildElement("id", protocol.getNamespacePrefix());
  id.addTextNode(generateUniqueMessageId(conf));
  if (StringUtils.isNotBlank(conf.getFile())) {
    SOAPElement issue = header.addChildElement("issue", protocol.getNamespacePrefix());
    issue.addTextNode(conf.getFile());
  }
  SOAPElement protocolVersion = header.addChildElement("protocolVersion", protocol.getNamespacePrefix());
  protocolVersion.addTextNode(protocol.getCode());

  addClientElements(env, conf, header);
  addServiceElements(env, conf, header);
}
 
Example 6
Source File: SoapPayloadIOTest.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link io.apiman.gateway.engine.io.SoapPayloadIO#marshall(org.w3c.dom.Document)}.
 */
@Test
public void testMarshall_Simple() throws Exception {
    MessageFactory msgFactory = MessageFactory.newInstance();
    SOAPMessage message = msgFactory.createMessage();
    SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();

    SOAPHeader header = envelope.getHeader();
    SOAPHeaderElement cheader = header.addHeaderElement(new QName("urn:ns1", "CustomHeader"));
    cheader.setTextContent("CVALUE");

    SoapPayloadIO io = new SoapPayloadIO();
    byte[] data = io.marshall(envelope);
    String actual = new String(data);

    String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header><CustomHeader xmlns=\"urn:ns1\">CVALUE</CustomHeader></SOAP-ENV:Header><SOAP-ENV:Body/></SOAP-ENV:Envelope>";
    Assert.assertEquals(expected, actual);
}
 
Example 7
Source File: SimpleSoapPayloadPolicy.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * @see io.apiman.gateway.engine.policy.IPolicy#apply(io.apiman.gateway.engine.beans.ApiRequest, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object, io.apiman.gateway.engine.policy.IPolicyChain)
 */
@SuppressWarnings("nls")
@Override
public void apply(final ApiRequest request, final IPolicyContext context, final Object config,
        final IPolicyChain<ApiRequest> chain) {
    try {
        SOAPEnvelope soapPayload = context.getAttribute(PolicyContextKeys.REQUEST_PAYLOAD, (SOAPEnvelope) null);
        if (soapPayload != null) {
            SOAPHeader header = soapPayload.getHeader();
            SOAPHeaderElement header1 = (SOAPHeaderElement) header.examineAllHeaderElements().next();
            String prop1 = header1.getTextContent();
            request.getHeaders().put("X-Property-1", prop1);
            header.addHeaderElement(new QName("urn:ns5", "Property5")).setTextContent("value-5");
        }
        chain.doApply(request);
    } catch (Exception e) {
        chain.throwError(e);
    }
}
 
Example 8
Source File: VersionHandlerCtmg.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * The method is invoked for normal processing of outbound messages.
 * 
 * @param context
 *            the message context.
 * @return An indication of whether handler processing should continue for
 *         the current message. Return <code>true</code> to continue
 *         processing.
 * 
 * @throws Exception
 *             Causes the JAX-WS runtime to cease fault message processing.
 **/
@Override
public boolean handleMessage(SOAPMessageContext context) {
    Boolean request_p = (Boolean) context
            .get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (request_p.booleanValue()) {
        try {
            SOAPMessage msg = context.getMessage();
            SOAPEnvelope env = msg.getSOAPPart().getEnvelope();
            SOAPHeader hdr = env.getHeader();
            if (hdr == null) {
                hdr = env.addHeader();
            }
            QName qname_user = new QName("http://com/auth/", "auth");
            SOAPHeaderElement helem_user = hdr.addHeaderElement(qname_user);
            helem_user.setActor(VERSION);
            if (version != null && version.trim().length() != 0) {
                helem_user.addTextNode(version);
            }

            msg.saveChanges();
            message = soapMessage2String(msg);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return true;
}
 
Example 9
Source File: VersionHandler.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * The method is invoked for normal processing of outbound messages.
 * 
 * @param context
 *            the message context.
 * @return An indication of whether handler processing should continue for
 *         the current message. Return <code>true</code> to continue
 *         processing.
 * 
 * @throws Exception
 *             Causes the JAX-WS runtime to cease fault message processing.
 **/
@Override
public boolean handleMessage(SOAPMessageContext context) {
    Boolean request_p = (Boolean) context
            .get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (request_p.booleanValue()) {
        try {
            SOAPMessage msg = context.getMessage();
            SOAPEnvelope env = msg.getSOAPPart().getEnvelope();
            SOAPHeader hdr = env.getHeader();
            if (hdr == null) {
                hdr = env.addHeader();
            }
            QName qname_user = new QName("http://com/auth/", "auth");
            SOAPHeaderElement helem_user = hdr.addHeaderElement(qname_user);
            helem_user.setActor(VERSION);
            if (version == null || version.trim().length() == 0) {
                helem_user.addTextNode(apiVersionInfo.getProperty(VERSION));
            } else {
                helem_user.addTextNode(version);
            }

            msg.saveChanges();
            message = soapMessage2String(msg);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return true;
}
 
Example 10
Source File: SoapRequestParser.java    From development with Apache License 2.0 5 votes vote down vote up
public static String parseApiVersion(SOAPMessageContext context)
        throws SOAPException {

    SOAPMessage soapMessage = context.getMessage();

    SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
    SOAPHeader soapHeader = soapEnvelope.getHeader();
    if (soapHeader == null) {
        return "";
    }

    Iterator<?> it = null;
    Iterator<?> itCm = soapHeader.extractHeaderElements(VERSION_CM);
    if (itCm == null || !itCm.hasNext()) {
        Iterator<?> itCtmg = soapHeader.extractHeaderElements(VERSION_CTMG);
        if (itCtmg == null || !itCtmg.hasNext()) {
            return "";
        } else {
            it = itCtmg;
        }
    } else {
        it = itCm;
    }

    Node node = (Node) it.next();
    String value = node == null ? null : node.getValue();

    return value;
}
 
Example 11
Source File: SecureSoapMessages.java    From spring-ws-security-soap-example with MIT License 5 votes vote down vote up
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;
}
 
Example 12
Source File: JPlagServerAccessHandler.java    From jplag with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Manually builds up a JPlagException SOAP message and replaces the
 * original one with it
 */
public void replaceByJPlagException(SOAPMessageContext smsg, String desc, String rep) {
	try {
		SOAPMessage msg = smsg.getMessage();
		SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();

		/*
		 * Remove old header andy body
		 */

		SOAPHeader oldheader = envelope.getHeader();
		if (oldheader != null)
			oldheader.detachNode();
		SOAPBody oldbody = envelope.getBody();
		if (oldbody != null)
			oldbody.detachNode();

		SOAPBody sb = envelope.addBody();
		SOAPFault sf = sb.addFault(envelope.createName("Server", "env", SOAPConstants.URI_NS_SOAP_ENVELOPE),
				"jplagWebService.server.JPlagException");
		Detail detail = sf.addDetail();
		DetailEntry de = detail.addDetailEntry(envelope.createName("JPlagException", "ns0", JPLAG_WEBSERVICE_BASE_URL + "types"));

		SOAPElement e = de.addChildElement("exceptionType");
		e.addTextNode("accessException");

		e = de.addChildElement("description");
		e.addTextNode(desc);

		e = de.addChildElement("repair");
		e.addTextNode(rep);
	} catch (SOAPException x) {
		x.printStackTrace();
	}
}
 
Example 13
Source File: TestMustUnderstandHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
public boolean handleMessage(SOAPMessageContext ctx) {

        boolean continueProcessing = true;

        try {
            Object b = ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
            boolean outbound = (Boolean)b;
            SOAPMessage msg = ctx.getMessage();
            if (isServerSideHandler()) {
                if (outbound) {
                    QName qname = new QName("http://cxf.apache.org/mu", "MU");
                    SOAPPart soapPart = msg.getSOAPPart();
                    SOAPEnvelope envelope = soapPart.getEnvelope();
                    SOAPHeader header = envelope.getHeader();
                    if (header == null) {
                        header = envelope.addHeader();
                    }


                    SOAPHeaderElement headerElement
                        = header.addHeaderElement(envelope.createName("MU", "ns1", qname.getNamespaceURI()));

                    // QName soapMustUnderstand = new QName("http://schemas.xmlsoap.org/soap/envelope/",
                    // "mustUnderstand");
                    Name name = SOAPFactory.newInstance()
                        .createName("mustUnderstand", "soap", "http://schemas.xmlsoap.org/soap/envelope/");
                    headerElement.addAttribute(name, "1");
                } else {
                    getHandlerInfoList(ctx).add(getHandlerId());
                }
            }
        } catch (SOAPException e) {
            e.printStackTrace();
        }
        return continueProcessing;
    }
 
Example 14
Source File: Tr064Comm.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sets all required namespaces and prepares the SOAP message to send.
 * Creates skeleton + body data.
 *
 * @param bodyData
 *            is attached to skeleton to form entire SOAP message
 * @return ready to send SOAP message
 */
private SOAPMessage constructTr064Msg(SOAPBodyElement bodyData) {
    SOAPMessage soapMsg = null;

    try {
        MessageFactory msgFac;
        msgFac = MessageFactory.newInstance();
        soapMsg = msgFac.createMessage();
        soapMsg.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
        soapMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
        SOAPPart part = soapMsg.getSOAPPart();

        // valid for entire SOAP msg
        String namespace = "s";

        // create suitable fbox envelope
        SOAPEnvelope envelope = part.getEnvelope();
        envelope.setPrefix(namespace);
        envelope.removeNamespaceDeclaration("SOAP-ENV"); // delete standard namespace which was already set
        envelope.addNamespaceDeclaration(namespace, "http://schemas.xmlsoap.org/soap/envelope/");
        Name nEncoding = envelope.createName("encodingStyle", namespace,
                "http://schemas.xmlsoap.org/soap/encoding/");
        envelope.addAttribute(nEncoding, "http://schemas.xmlsoap.org/soap/encoding/");

        // create empty header
        SOAPHeader header = envelope.getHeader();
        header.setPrefix(namespace);

        // create body with command based on parameter
        SOAPBody body = envelope.getBody();
        body.setPrefix(namespace);
        body.addChildElement(bodyData); // bodyData already prepared. Needs only be added

    } catch (Exception e) {
        logger.error("Error creating SOAP message for fbox request with data {}", bodyData);
        e.printStackTrace();
    }

    return soapMsg;
}
 
Example 15
Source File: SoapPayloadIOTest.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Test method for {@link io.apiman.gateway.engine.io.SoapPayloadIO#unmarshall(java.io.InputStream)}.
 */
@Test
public void testUnmarshall_Simple() throws Exception {
    String xml = "<?xml version=\"1.0\"?>\r\n" +
            "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">\r\n" +
            "  <soap:Header>\r\n" +
            "     <ns1:CustomHeader xmlns:ns1=\"urn:ns1\">CVALUE</ns1:CustomHeader>\r\n" +
            "  </soap:Header>\r\n" +
            "  <soap:Body>\r\n" +
            "    <m:GetStockPrice xmlns:m=\"http://www.example.org/stock/Surya\">\r\n" +
            "      <m:StockName>IBM</m:StockName>\r\n" +
            "    </m:GetStockPrice>\r\n" +
            "  </soap:Body>\r\n" +
            "</soap:Envelope>";
    byte [] xmlBytes = xml.getBytes();
    SoapPayloadIO io = new SoapPayloadIO();
    try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
        SOAPEnvelope envelope = io.unmarshall(is);
        Assert.assertNotNull(envelope);
        Assert.assertEquals("Envelope", envelope.getLocalName());
        Assert.assertEquals("http://www.w3.org/2003/05/soap-envelope", envelope.getNamespaceURI());

        SOAPHeader header = envelope.getHeader();
        Assert.assertNotNull(header);

        Iterator<?> allHeaderElements = header.examineAllHeaderElements();
        Assert.assertTrue(allHeaderElements.hasNext());
        SOAPHeaderElement cheader = (SOAPHeaderElement) allHeaderElements.next();
        Assert.assertNotNull(cheader);
        Assert.assertEquals("CVALUE", cheader.getTextContent());
    }
}
 
Example 16
Source File: SimpleSecurityHandler.java    From onvif with Apache License 2.0 4 votes vote down vote up
@Override
public boolean handleMessage(final SOAPMessageContext msgCtx) {
  // System.out.println("SimpleSecurityHandler");

  // Indicator telling us which direction this message is going in
  final Boolean outInd = (Boolean) msgCtx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

  // Handler must only add security headers to outbound messages
  if (outInd.booleanValue()) {
    try {
      // Create the xml
      SOAPMessage soapMessage = msgCtx.getMessage();
      SOAPEnvelope envelope = soapMessage.getSOAPPart().getEnvelope();
      SOAPHeader header = envelope.getHeader();
      if (header == null) header = envelope.addHeader();

      SOAPPart sp = soapMessage.getSOAPPart();
      SOAPEnvelope se = sp.getEnvelope();
      se.addNamespaceDeclaration(WSSE_PREFIX, WSSE_NS);
      se.addNamespaceDeclaration(WSU_PREFIX, WSU_NS);

      SOAPElement securityElem = header.addChildElement(WSSE_LN, WSSE_PREFIX);
      // securityElem.setAttribute("SOAP-ENV:mustUnderstand", "1");

      SOAPElement usernameTokenElem =
          securityElem.addChildElement(USERNAME_TOKEN_LN, WSSE_PREFIX);

      SOAPElement usernameElem = usernameTokenElem.addChildElement(USERNAME_LN, WSSE_PREFIX);
      usernameElem.setTextContent(username);

      SOAPElement passwordElem = usernameTokenElem.addChildElement(PASSWORD_LN, WSSE_PREFIX);
      passwordElem.setAttribute(PASSWORD_TYPE_ATTR, PASSWORD_DIGEST);
      passwordElem.setTextContent(encryptPassword(password));

      SOAPElement nonceElem = usernameTokenElem.addChildElement(NONCE_LN, WSSE_PREFIX);
      nonceElem.setAttribute("EncodingType", BASE64_ENCODING);
      nonceElem.setTextContent(Base64.encodeBase64String(nonce.getBytes()));

      SOAPElement createdElem = usernameTokenElem.addChildElement(CREATED_LN, WSU_PREFIX);
      createdElem.setTextContent(getLastUTCTime());
    } catch (final Exception e) {
      e.printStackTrace();
      return false;
    }
  }
  return true;
}