Java Code Examples for javax.xml.soap.SOAPMessage#getSOAPBody()

The following examples show how to use javax.xml.soap.SOAPMessage#getSOAPBody() . 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: Inflate.java    From tomee with Apache License 2.0 6 votes vote down vote up
public boolean handleMessage(SOAPMessageContext mc) {
    try {
        final SOAPMessage message = mc.getMessage();
        final SOAPBody body = message.getSOAPBody();
        final String localName = body.getFirstChild().getLocalName();

        if ("sumResponse".equals(localName) || "multiplyResponse".equals(localName)) {
            final Node responseNode = body.getFirstChild();
            final Node returnNode = responseNode.getFirstChild();
            final Node intNode = returnNode.getFirstChild();

            final int value = new Integer(intNode.getNodeValue());
            intNode.setNodeValue(Integer.toString(value * 1000));
        }

        return true;
    } catch (SOAPException e) {
        return false;
    }
}
 
Example 2
Source File: Soap.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Returns a string encoded accordingly with the SAML HTTP POST Binding specification based on the
 * given <code>inputStream</code> which must contain a valid SOAP message.
 *
 * <p>The resulting string is based on the Body of the SOAP message, which should map to a valid SAML message.
 *
 * @param inputStream the input stream containing a valid SOAP message with a Body that contains a SAML message
 *
 * @return a string encoded accordingly with the SAML HTTP POST Binding specification
 */
public static String toSamlHttpPostMessage(InputStream inputStream) {
    try {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage(null, inputStream);
        SOAPBody soapBody = soapMessage.getSOAPBody();
        Node authnRequestNode = soapBody.getFirstChild();
        Document document = DocumentUtil.createDocument();

        document.appendChild(document.importNode(authnRequestNode, true));

        return PostBindingUtil.base64Encode(DocumentUtil.asString(document));
    } catch (Exception e) {
        throw new RuntimeException("Error creating fault message.", e);
    }
}
 
Example 3
Source File: EcpAuthenticationHandler.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public AuthOutcome handle(OnSessionCreated onCreateSession) {
    String header = facade.getRequest().getHeader(PAOS_HEADER);

    if (header != null) {
        return doHandle(new SamlInvocationContext(), onCreateSession);
    } else {
        try {
            MessageFactory messageFactory = MessageFactory.newInstance();
            SOAPMessage soapMessage = messageFactory.createMessage(null, facade.getRequest().getInputStream());
            SOAPBody soapBody = soapMessage.getSOAPBody();
            Node authnRequestNode = soapBody.getFirstChild();
            Document document = DocumentUtil.createDocument();

            document.appendChild(document.importNode(authnRequestNode, true));

            String samlResponse = PostBindingUtil.base64Encode(DocumentUtil.asString(document));

            return doHandle(new SamlInvocationContext(null, samlResponse, null), onCreateSession);
        } catch (Exception e) {
            throw new RuntimeException("Error creating fault message.", e);
        }
    }
}
 
Example 4
Source File: Increment.java    From tomee with Apache License 2.0 6 votes vote down vote up
public boolean handleMessage(SOAPMessageContext mc) {
    try {
        final SOAPMessage message = mc.getMessage();
        final SOAPBody body = message.getSOAPBody();
        final String localName = body.getFirstChild().getLocalName();

        if ("sumResponse".equals(localName) || "multiplyResponse".equals(localName)) {
            final Node responseNode = body.getFirstChild();
            final Node returnNode = responseNode.getFirstChild();
            final Node intNode = returnNode.getFirstChild();

            final int value = new Integer(intNode.getNodeValue());
            intNode.setNodeValue(Integer.toString(value + 1));
        }

        return true;
    } catch (SOAPException e) {
        return false;
    }
}
 
Example 5
Source File: DeviceDiscovery.java    From onvif with Apache License 2.0 6 votes vote down vote up
private static Collection<String> parseSoapResponseForUrls(byte[] data)
    throws SOAPException, IOException {
  // System.out.println(new String(data));
  final Collection<String> urls = new ArrayList<>();
  MessageFactory factory = MessageFactory.newInstance(WS_DISCOVERY_SOAP_VERSION);
  final MimeHeaders headers = new MimeHeaders();
  headers.addHeader("Content-type", WS_DISCOVERY_CONTENT_TYPE);
  SOAPMessage message = factory.createMessage(headers, new ByteArrayInputStream(data));
  SOAPBody body = message.getSOAPBody();
  for (Node node : getNodeMatching(body, ".*:XAddrs")) {
    if (node.getTextContent().length() > 0) {
      urls.addAll(Arrays.asList(node.getTextContent().split(" ")));
    }
  }
  return urls;
}
 
Example 6
Source File: HubDecryptionHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void handleDecryption(SOAPMessageContext cxt) {
   try {
      SOAPMessage soapMessage = cxt.getMessage();
      SOAPBody soapBody = soapMessage.getSOAPBody();
      if (soapBody == null) {
         SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
         soapBody = soapEnvelope.getBody();
      }

      FolderDecryptor.decryptFolder(soapBody, this.crypto);
      soapMessage.saveChanges();
   } catch (SOAPException var5) {
      LOG.error("SOAPException when handling the SOAP Body", var5);
      throw new RuntimeException(var5);
   } catch (UnsealConnectorException var6) {
      LOG.error("UnsealConnectorException when handling the SOAP Message: " + var6.getMessage());
      throw new FolderDecryptionRuntimeException(var6.getMessage(), var6);
   } catch (TechnicalConnectorException var7) {
      LOG.error("TechnicalConnectorException when handling the SOAP Message: " + var7.getMessage());
      throw new RuntimeException(var7);
   }
}
 
Example 7
Source File: SAAJTestServlet.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
private static void assertSOAPBodiesAreEqual(SOAPMessage expected, SOAPMessage actual)
    throws Exception {
  SOAPBody expectedBody = expected.getSOAPBody();
  SOAPBody actualBody = actual.getSOAPBody();
  SOAPBodyElement expectedElement = (SOAPBodyElement) expectedBody.getChildElements().next();
  SOAPBodyElement actualElement = (SOAPBodyElement) actualBody.getChildElements().next();
  String expectedQN = expectedElement.getElementQName().toString();
  String actualQN = actualElement.getElementQName().toString();
  assertEquals(expectedQN, actualQN);
}
 
Example 8
Source File: MySOAPHandler.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleMessage(SOAPMessageContext context) {
    SOAPMessage msg = context.getMessage();

    try {
        SOAPBody body = msg.getSOAPBody();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(new DOMSource(body), new StreamResult(System.out));
    } catch (SOAPException | TransformerException e) {
        e.printStackTrace();
    }

    return true;
}
 
Example 9
Source File: CougarHelpers.java    From cougar with Apache License 2.0 5 votes vote down vote up
public Node extractResponseNode(SOAPMessage response) throws SOAPException{

		Node responseNode;

		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		try {
			response.writeTo(outStream);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
//		logger.LogBetfairDebugEntry("SOAP Response: " + outStream.toString());

		if (response.getSOAPBody().hasFault()) {
			responseNode = response.getSOAPBody().getFault();
		}
		else if(response.getSOAPBody().getFirstChild() == null){ // Response type is void
			responseNode = response.getSOAPBody();
		}
		else {
			// extract the body
			SOAPBody respBody = response.getSOAPBody();
			// First child should be the service name object
			Node serviceResponseNode = respBody.getFirstChild();

			// second child
			responseNode = serviceResponseNode.getFirstChild();
		}

		return responseNode;
	}
 
Example 10
Source File: SoapServlet.java    From mdw with Apache License 2.0 5 votes vote down vote up
/**
 * Allow version specific factory passed in to support SOAP 1.1 and 1.2
 * <b>Important</b> Faults are treated differently for 1.1 and 1.2 For 1.2
 * you can't use the elementName otherwise it throws an exception
 */
protected String createSoapFaultResponse(String soapVersion, String code, String message)
        throws SOAPException, TransformerException {

    SOAPMessage soapMessage = getSoapMessageFactory(soapVersion).createMessage();
    SOAPBody soapBody = soapMessage.getSOAPBody();
    /**
     * Faults are treated differently for 1.1 and 1.2 For 1.2 you can't use
     * the elementName otherwise it throws an exception
     *
     * @see http://docs.oracle.com/cd/E19159-01/819-3669/bnbip/index.html
     */
    SOAPFault fault = null;
    if (soapVersion.equals(SOAPConstants.SOAP_1_1_PROTOCOL)) {
        // existing 1.1 functionality
        fault = soapBody.addFault(soapMessage.getSOAPHeader().getElementName(), message);
        if (code != null)
            fault.setFaultCode(code);
    }
    else if (soapVersion.equals(SOAPConstants.SOAP_1_2_PROTOCOL)) {
        /**
         * For 1.2 there are only a set number of allowed codes, so we can't
         * just use any one like what we did in 1.1. The recommended one to
         * use is SOAPConstants.SOAP_RECEIVER_FAULT
         */
        fault = soapBody.addFault(SOAPConstants.SOAP_RECEIVER_FAULT,
                code == null ? message : code + " : " + message);

    }
    return DomHelper.toXml(soapMessage.getSOAPPart().getDocumentElement());

}
 
Example 11
Source File: SoapValueParser.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/***
 * Parse the FritzBox response to a SOAP service request into values for all defined
 * {@link ItemMap#getItemCommands() items} of the item map of this service request.
 *
 * @param sm soap message to parse
 * @param mapping itemmap with information about all TR064 parameters returned by the invoked SOAP service.
 * @param itemConfiguration the item configuration for which the SOAP service call was initiated.
 *            All item configuration in the returned map must have the same
 *            {@link ItemConfiguration#getDataInValue() dataInValue}
 *            and {@link ItemConfiguration#getAdditionalParameters() parameters} as this configuration.
 * @return Map of item values for the {@link ItemConfiguration item configurations} corresponding to all
 *         {@link ItemMap#getItemCommands() items} defined for this service request.
 */
public Map<ItemConfiguration, String> parseValuesFromSoapMessage(SOAPMessage sm, ItemMap mapping,
        ItemConfiguration itemConfiguration) {
    Set<String> itemCommands = mapping.getItemCommands();
    Map<ItemConfiguration, String> itemConfigurationToValues = new HashMap<>(itemCommands.size());
    try {
        SOAPBody soapBody = sm.getSOAPBody();
        parseValuesFromSoapBody(sm, soapBody, mapping, itemCommands, itemConfigurationToValues, itemConfiguration);
    } catch (SOAPException e) {
        logger.warn("Error parsing SOAP response from FritzBox: {}. ", e.getMessage());
        setAllItemValuesUnavailable(itemCommands, itemConfigurationToValues, itemConfiguration);
    }
    return itemConfigurationToValues;
}
 
Example 12
Source File: DocumentWebServiceAdapter.java    From mdw with Apache License 2.0 5 votes vote down vote up
protected Node unwrapSoapResponse(SOAPMessage soapResponse)
throws ActivityException, AdapterException {
    try {
        SOAPBody soapBody = soapResponse.getSOAPBody();
        Node childElem = null;
        Iterator<?> it = soapBody.getChildElements();
        while (it.hasNext()) {
            Node node = (Node) it.next();
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                childElem = node;
                break;
            }
        }
        if (childElem == null)
          throw new SOAPException("SOAP body child element not found");

        // extract soap response headers
        SOAPHeader header = soapResponse.getSOAPHeader();
        if (header != null) {
            extractSoapResponseHeaders(header);
        }

        return childElem;
    }
    catch (Exception ex) {
        throw new ActivityException(ex.getMessage(), ex);
    }
}
 
Example 13
Source File: SaajEmptyNamespaceTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testPreserveNamespacesPosition() throws Exception {
    // Create SOAP message from XML string and process it with SAAJ reader
    XMLStreamReader envelope = XMLInputFactory.newFactory().createXMLStreamReader(
            new StringReader(INPUT_SOAP_MESSAGE_2));
    StreamMessage streamMessage = new StreamMessage(SOAPVersion.SOAP_11,
            envelope, null);
    SAAJFactory saajFact = new SAAJFactory();
    SOAPMessage soapMessage = saajFact.readAsSOAPMessage(SOAPVersion.SOAP_11, streamMessage);

    //Get SOAP body and convert it to string representation
    SOAPBody body = soapMessage.getSOAPBody();
    String bodyAsString = nodeToText(body);
    Assert.assertEquals(bodyAsString, PRESERVE_NAMESPACES_EXPECTED_RESULT);
}
 
Example 14
Source File: WsaTubeHelper.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
String getFaultActionFromSEIModel(Packet requestPacket, Packet responsePacket) {
    String action = null;
    if (seiModel == null || wsdlPort == null) {
        return action;
    }

    try {
        SOAPMessage sm = responsePacket.getMessage().copy().readAsSOAPMessage();
        if (sm == null) {
            return action;
        }

        if (sm.getSOAPBody() == null) {
            return action;
        }

        if (sm.getSOAPBody().getFault() == null) {
            return action;
        }

        Detail detail = sm.getSOAPBody().getFault().getDetail();
        if (detail == null) {
            return action;
        }

        String ns = detail.getFirstChild().getNamespaceURI();
        String name = detail.getFirstChild().getLocalName();

        WSDLOperationMapping wsdlOp = requestPacket.getWSDLOperationMapping();
        JavaMethodImpl jm = (wsdlOp != null) ? (JavaMethodImpl)wsdlOp.getJavaMethod() : null;
        if (jm != null) {
          for (CheckedExceptionImpl ce : jm.getCheckedExceptions()) {
              if (ce.getDetailType().tagName.getLocalPart().equals(name) &&
                      ce.getDetailType().tagName.getNamespaceURI().equals(ns)) {
                  return ce.getFaultAction();
              }
          }
        }
        return action;
    } catch (SOAPException e) {
        throw new WebServiceException(e);
    }
}
 
Example 15
Source File: WsaTubeHelper.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
String getFaultAction(@Nullable WSDLBoundOperation wbo, Packet responsePacket) {
    String action = AddressingUtils.getAction(responsePacket.getMessage().getHeaders(), addVer, soapVer);
    if (action != null) {
        return action;
    }

    action = addVer.getDefaultFaultAction();
    if (wbo == null) {
        return action;
    }

    try {
        SOAPMessage sm = responsePacket.getMessage().copy().readAsSOAPMessage();
        if (sm == null) {
            return action;
        }

        if (sm.getSOAPBody() == null) {
            return action;
        }

        if (sm.getSOAPBody().getFault() == null) {
            return action;
        }

        Detail detail = sm.getSOAPBody().getFault().getDetail();
        if (detail == null) {
            return action;
        }

        String ns = detail.getFirstChild().getNamespaceURI();
        String name = detail.getFirstChild().getLocalName();

        WSDLOperation o = wbo.getOperation();

        WSDLFault fault = o.getFault(new QName(ns, name));
        if (fault == null) {
            return action;
        }

        action = fault.getAction();

        return action;
    } catch (SOAPException e) {
        throw new WebServiceException(e);
    }
}
 
Example 16
Source File: WsaTubeHelper.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
String getFaultActionFromSEIModel(Packet requestPacket, Packet responsePacket) {
    String action = null;
    if (seiModel == null || wsdlPort == null) {
        return action;
    }

    try {
        SOAPMessage sm = responsePacket.getMessage().copy().readAsSOAPMessage();
        if (sm == null) {
            return action;
        }

        if (sm.getSOAPBody() == null) {
            return action;
        }

        if (sm.getSOAPBody().getFault() == null) {
            return action;
        }

        Detail detail = sm.getSOAPBody().getFault().getDetail();
        if (detail == null) {
            return action;
        }

        String ns = detail.getFirstChild().getNamespaceURI();
        String name = detail.getFirstChild().getLocalName();

        WSDLOperationMapping wsdlOp = requestPacket.getWSDLOperationMapping();
        JavaMethodImpl jm = (wsdlOp != null) ? (JavaMethodImpl)wsdlOp.getJavaMethod() : null;
        if (jm != null) {
          for (CheckedExceptionImpl ce : jm.getCheckedExceptions()) {
              if (ce.getDetailType().tagName.getLocalPart().equals(name) &&
                      ce.getDetailType().tagName.getNamespaceURI().equals(ns)) {
                  return ce.getFaultAction();
              }
          }
        }
        return action;
    } catch (SOAPException e) {
        throw new WebServiceException(e);
    }
}
 
Example 17
Source File: AbstractXTeeAxisEndpoint.java    From j-road with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected void invokeInternalEx(XTeeMessage<Document> request,
                                XTeeMessage<Element> response,
                                SOAPMessage requestMessage,
                                SOAPMessage responseMessage) throws Exception {
  requestMessage.getSOAPHeader().detachNode();
  Node bodyNode;
  if (XRoadProtocolVersion.V2_0 == version) {
    bodyNode = SOAPUtil.getNodeByXPath(requestMessage.getSOAPBody(), "//keha");
  } else {
    bodyNode = requestMessage.getSOAPBody();
  }
  Node reqNode = bodyNode.getParentNode();
  NodeList nl = bodyNode.getChildNodes();
  for (int i = 0; i < nl.getLength(); i++) {
    Node curNode = nl.item(i);
    reqNode.appendChild(curNode.cloneNode(true));
  }
  reqNode.removeChild(bodyNode);

  // Since Axis needs the XML as a String a transformation is required.
  StringResult result = new StringResult();
  Transformer transformer = TransformerFactory.newInstance().newTransformer();
  transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  transformer.transform(new DOMSource(requestMessage.getSOAPPart().getEnvelope()), result);

  Message axisMessage = new Message(result.toString());
  // The context is very important, as the binding stub creates all the type bindings for proper unmarshalling.
  axisMessage.setMessageContext(getContextHelper().getMessageContext());

  // Adding the attachments is needed to handle "href" attributes where the data is in an attachment.
  for (Iterator<AttachmentPart> i = requestMessage.getAttachments(); i.hasNext();) {
    axisMessage.addAttachmentPart(i.next());
  }

  XTeeMessage<P> axisRequestMessage = new BeanXTeeMessage<P>(request.getHeader(),
                                                             (P) axisMessage.getSOAPEnvelope().getFirstBody().getObjectValue(getParingKehaClass()),
                                                             request.getAttachments());
  XTeeMessage<V> axisResponseMessage =
      new BeanXTeeMessage<V>(response.getHeader(), null, new ArrayList<XTeeAttachment>());

  invoke(axisRequestMessage, axisResponseMessage);

  V responseBean = axisResponseMessage.getContent();
  // If response is null we return <keha/>, otherwise some marshalling needs to be done.
  if (responseBean != null) {
    String responseXml = AxisUtil.serialize(responseBean);
    Document doc =
        DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(responseXml.getBytes("UTF-8")));
    Node parent = response.getContent().getParentNode();
    parent.removeChild(response.getContent());
    parent.appendChild(parent.getOwnerDocument().importNode(doc.getFirstChild(), true));
  }
}
 
Example 18
Source File: WsaTubeHelper.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
String getFaultAction(@Nullable WSDLBoundOperation wbo, Packet responsePacket) {
    String action = AddressingUtils.getAction(responsePacket.getMessage().getHeaders(), addVer, soapVer);
    if (action != null) {
        return action;
    }

    action = addVer.getDefaultFaultAction();
    if (wbo == null) {
        return action;
    }

    try {
        SOAPMessage sm = responsePacket.getMessage().copy().readAsSOAPMessage();
        if (sm == null) {
            return action;
        }

        if (sm.getSOAPBody() == null) {
            return action;
        }

        if (sm.getSOAPBody().getFault() == null) {
            return action;
        }

        Detail detail = sm.getSOAPBody().getFault().getDetail();
        if (detail == null) {
            return action;
        }

        String ns = detail.getFirstChild().getNamespaceURI();
        String name = detail.getFirstChild().getLocalName();

        WSDLOperation o = wbo.getOperation();

        WSDLFault fault = o.getFault(new QName(ns, name));
        if (fault == null) {
            return action;
        }

        action = fault.getAction();

        return action;
    } catch (SOAPException e) {
        throw new WebServiceException(e);
    }
}
 
Example 19
Source File: WsaTubeHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
String getFaultAction(@Nullable WSDLBoundOperation wbo, Packet responsePacket) {
    String action = AddressingUtils.getAction(responsePacket.getMessage().getHeaders(), addVer, soapVer);
    if (action != null) {
        return action;
    }

    action = addVer.getDefaultFaultAction();
    if (wbo == null) {
        return action;
    }

    try {
        SOAPMessage sm = responsePacket.getMessage().copy().readAsSOAPMessage();
        if (sm == null) {
            return action;
        }

        if (sm.getSOAPBody() == null) {
            return action;
        }

        if (sm.getSOAPBody().getFault() == null) {
            return action;
        }

        Detail detail = sm.getSOAPBody().getFault().getDetail();
        if (detail == null) {
            return action;
        }

        String ns = detail.getFirstChild().getNamespaceURI();
        String name = detail.getFirstChild().getLocalName();

        WSDLOperation o = wbo.getOperation();

        WSDLFault fault = o.getFault(new QName(ns, name));
        if (fault == null) {
            return action;
        }

        action = fault.getAction();

        return action;
    } catch (SOAPException e) {
        throw new WebServiceException(e);
    }
}
 
Example 20
Source File: WsaTubeHelper.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
String getFaultActionFromSEIModel(Packet requestPacket, Packet responsePacket) {
    String action = null;
    if (seiModel == null || wsdlPort == null) {
        return action;
    }

    try {
        SOAPMessage sm = responsePacket.getMessage().copy().readAsSOAPMessage();
        if (sm == null) {
            return action;
        }

        if (sm.getSOAPBody() == null) {
            return action;
        }

        if (sm.getSOAPBody().getFault() == null) {
            return action;
        }

        Detail detail = sm.getSOAPBody().getFault().getDetail();
        if (detail == null) {
            return action;
        }

        String ns = detail.getFirstChild().getNamespaceURI();
        String name = detail.getFirstChild().getLocalName();

        WSDLOperationMapping wsdlOp = requestPacket.getWSDLOperationMapping();
        JavaMethodImpl jm = (wsdlOp != null) ? (JavaMethodImpl)wsdlOp.getJavaMethod() : null;
        if (jm != null) {
          for (CheckedExceptionImpl ce : jm.getCheckedExceptions()) {
              if (ce.getDetailType().tagName.getLocalPart().equals(name) &&
                      ce.getDetailType().tagName.getNamespaceURI().equals(ns)) {
                  return ce.getFaultAction();
              }
          }
        }
        return action;
    } catch (SOAPException e) {
        throw new WebServiceException(e);
    }
}