Example #1
0
 /**
  * Forms a SOAP Fault and puts it in the SOAP Message's Body.
  *
  * @param faultcode fault code to be set in SOAPMEssage
  * @param faultString fault string
  * @param detail the details of the fault condition
  * @return <code>SOAPMessage</code> containing the SOAP fault
  */
 public SOAPMessage formSOAPError(String faultcode, String faultString, String detail) {
   SOAPMessage msg = null;
   SOAPEnvelope envelope = null;
   SOAPFault sf = null;
   SOAPBody body = null;
   SOAPElement se = null;
   try {
     msg = fac.createMessage();
     envelope = msg.getSOAPPart().getEnvelope();
     body = envelope.getBody();
     sf = body.addFault();
     Name qname = envelope.createName(faultcode, null, IFSConstants.SOAP_URI);
     sf.setFaultCode(qname);
     sf.setFaultString(FSUtils.bundle.getString(faultString));
     if ((detail != null) && !(detail.length() == 0)) {
       Detail det = sf.addDetail();
       se = (SOAPElement) det.addDetailEntry(envelope.createName("Problem"));
       se.addAttribute(envelope.createName("details"), FSUtils.bundle.getString(detail));
     }
   } catch (SOAPException e) {
     FSUtils.debug.error("FSSOAPService.formSOAPError:", e);
     return null;
   }
   return msg;
 }
  public void addToSOAPBody(org.apache.axis.Message msg, XRoadProtocolHeader xRoadProtocolHeader) {
    try {
      // get SOAP envelope from SOAP message
      org.apache.axis.message.SOAPEnvelope se = msg.getSOAPEnvelope();
      SOAPBody body = se.getBody();

      @SuppressWarnings("rawtypes")
      Iterator items = body.getChildElements();
      if (items.hasNext()) {
        body.removeContents();
      }

      SOAPBodyElement element =
          body.addBodyElement(
              se.createName(
                  getSendingOptionsResponseType.DEFAULT_RESPONSE_ELEMENT_NAME,
                  CommonStructures.NS_DHL_PREFIX,
                  CommonStructures.NS_DHL_URI));

      if (xRoadProtocolHeader.getProtocolVersion().equals(XRoadProtocolVersion.V2_0)) {
        SOAPElement elParing = element.addChildElement(se.createName("paring"));
        elParing.addTextNode(this.dataMd5Hash);
      }

      // X-road "keha" part in SOAP message
      SOAPElement elKeha = element.addChildElement(se.createName("keha"));
      elKeha.addAttribute(se.createName("href"), "cid:" + kehaHref);
    } catch (Exception ex) {
      CommonMethods.logError(ex, this.getClass().getName(), "addToSOAPBody");
    }
  }
Example #3
0
  public SecurityToken logon(
      String anEndpointReference, String aUserName, String aPassword, String anApplicationID)
      throws LogonManagerException, SOAPException, IOException {
    SecurityToken result;
    SOAPMessage message;
    SOAPConnection conn = null;

    try {
      result = null;
      String request =
          REQUEST_FORMAT.format(
              ((Object) (new Object[] {fURL, aUserName, aPassword, anEndpointReference})));
      message =
          MessageFactory.newInstance()
              .createMessage(new MimeHeaders(), new ByteArrayInputStream(request.getBytes()));
      conn = SOAPConnectionFactory.newInstance().createConnection();
      SOAPMessage response = conn.call(message, fURL);
      SOAPBody body = response.getSOAPBody();
      if (body.hasFault()) throw new LogonManagerException(body.getFault());
      result = new SecurityToken();
      result.setSOAPBody(body);
      for (Iterator it = body.getChildElements(); it.hasNext(); fill(result, (Node) it.next())) ;
      return result;
    } finally {
      if (conn != null) conn.close();
    }
  }
  /**
   * @param query the input of the user
   * @return SOAP message which is good for cross-platform web service
   */
  public SOAPMessage sendSOAPMessage(String query, URL serverURL) throws SOAPException {

    /** create a SOAP msg from query */
    SOAPMessage wsRequest = MessageFactory.newInstance().createMessage();

    // SOAP params
    SOAPPart part = wsRequest.getSOAPPart();
    SOAPEnvelope envelope = part.getEnvelope();
    SOAPBody body = envelope.getBody();

    // Name: a local name, a namespace prefix, and a namesapce URI.
    Name name = envelope.createName("query", "yyns", "http://cis555.co.nf/");
    SOAPElement elem = body.addChildElement(name);
    elem.addTextNode(query);
    //		body.addChildElement(envelope.createName("query", "yyns",
    // "http://cis555.co.nf/")).addTextNode(query);  //###
    wsRequest.saveChanges();

    /** send SOAP to P2P ring */
    // get response
    SOAPConnection conn = SOAPConnectionFactory.newInstance().createConnection();
    SOAPMessage wsResponse = conn.call(wsRequest, serverURL);
    conn.close();
    return wsResponse;
  }
  /** @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();
    }
  }
  public void getCBSArsHeader(String method, SOAPMessage message) throws Exception {
    SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
    envelope.addNamespaceDeclaration("arcl", "http://www.huawei.com/ar/wsservice/arcommon");
    envelope.addNamespaceDeclaration("cbs", "http://www.huawei.com/bme/cbsinterface/cbscommon");
    envelope.addNamespaceDeclaration(
        "arc", "http://www.huawei.com/bme/cbsinterface/arcustomizedservices");
    SOAPBody body = envelope.getBody();
    SOAPElement bodyElement = body.addChildElement(method, "arc");
    SOAPElement requestHeaderElement = bodyElement.addChildElement("RequestHeader");
    requestHeaderElement.addChildElement("Version", "cbs").addTextNode("1.0");
    requestHeaderElement
        .addChildElement("MessageSeq", "cbs")
        .addTextNode(BssServiceUtils.generateTransactionId());

    SOAPElement accessSecurityElement =
        requestHeaderElement.addChildElement("AccessSecurity", "cbs");
    accessSecurityElement
        .addChildElement("LoginSystemCode", "cbs")
        .addTextNode(SYSConfig.getConfig().get("cbs.inf.accessUser"));
    accessSecurityElement
        .addChildElement("Password", "cbs")
        .addTextNode(SYSConfig.getConfig().get("cbs.inf.accessPwd"));
    requestHeaderElement
        .addChildElement("AccessMode", "cbs")
        .addTextNode(SYSConfig.getConfig().get("cbs.inf.channelCode"));
  }
Example #7
0
  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;
  }
 private void soapToRpcResult(SOAPMessage response, RpcInvokeAction action, SimpleRpcResult result)
     throws Exception {
   logMessage("Response message:", response);
   SOAPBody responseBody = response.getSOAPBody();
   checkForFailureReponse(responseBody);
   actionData =
       WsRpcActionUtil.getWsRpcActionData(((SimpleRpcInvokeAction) action).getProperties());
   getFields(action.getFields(), responseBody.getChildElements());
   result.setRpcFields(action.getFields());
 }
  @Test
  public void shouldConvertRecordNodeToRecordVO() throws Exception {
    SOAPBody body = new MockRecordMessage("1200").getBody();

    NodeList records = body.getElementsByTagName("record");

    RecordNode node = new RecordNode(records.item(0).getChildNodes());
    RecordVO vo = node.toRecord();
    assertEquals(0, new BigDecimal(10000).compareTo(vo.amount));
    assertEquals(getDateOnJanuary1Of1970(), vo.date.getTime());
    assertEquals("1200", vo.account);
  }
  /**
   * @param wsResponse the web service response from P2P ring
   * @return html format to show users
   */
  String parseSOAPIntoHTML(SOAPMessage wsResponse) throws SOAPException {
    StringBuffer result = new StringBuffer();
    SOAPPart part = wsResponse.getSOAPPart();
    SOAPEnvelope envelope = part.getEnvelope();
    SOAPBody body = envelope.getBody();
    Iterator<Node> iter =
        body.getChildElements(envelope.createName("response", "yyns", "http://cis555.co.nf/"));

    NodeList childNodes = ((org.w3c.dom.Node) iter.next()).getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
      result.append(childNodes.item(i).getTextContent()).append("<br>");
    }
    return result.toString();
  }
 private QName getOperationName(MessageContext msgContext) {
   SOAPMessageContext soapMessageContext = (SOAPMessageContext) msgContext;
   SOAPMessage soapMessage = soapMessageContext.getMessage();
   SOAPBody soapBody;
   try {
     soapBody = soapMessage.getSOAPBody();
     Node child = soapBody.getFirstChild();
     String childNamespace = child.getNamespaceURI();
     String childName = child.getLocalName();
     return new QName(childNamespace, childName);
   } catch (SOAPException e) {
     if (trace) log.trace("Exception using backup method to get op name=", e);
   }
   return null;
 }
 /**
  * Normal response case,just tests if the endpoint accepts non-anon FaultTo
  *
  * @throws Exception
  */
 public void testNonAnonymousFaultTo1() throws Exception {
   SOAPMessage response =
       invoke(
           createDispatchWithoutAddressing(),
           TestMessages.NON_ANONYMOUS_FAULT_TO_COMPLETE_MESSAGE,
           S11_NS,
           nonAnonAddress,
           action,
           endpointAddress,
           "testNonAnonymousReplyTo");
   SOAPBody sb = response.getSOAPBody();
   Iterator itr =
       sb.getChildElements(
           new QName("http://server.responses.wsa.fromjava/", "addNumbersResponse"));
   assertTrue(itr.hasNext());
 }
  private SOAPElement assertResponseXML(SOAPMessage msg, String expectedText) throws Exception {
    assertTrue(msg != null);
    SOAPBody body = msg.getSOAPBody();
    assertTrue(body != null);

    Node invokeElement = (Node) body.getFirstChild();
    assertTrue(invokeElement instanceof SOAPElement);
    assertEquals("outMessage", invokeElement.getLocalName());

    String text = invokeElement.getValue();

    System.out.println("Received: " + text);
    assertEquals("Found (" + text + ") but expected (" + expectedText + ")", expectedText, text);

    return (SOAPElement) invokeElement;
  }
 public WelianoObjectResponse(SOAPBody body) {
   super(body);
   NodeList items = body.getChildNodes();
   if (items.getLength() > 0) {
     for (int i = 0; i < items.item(0).getChildNodes().getLength(); i++) {
       if (items.item(0).getChildNodes().item(i).getLocalName().equals("return")) {
         for (int ii = 0;
             ii < items.item(0).getChildNodes().item(i).getChildNodes().getLength();
             ii++) {
           if (items
               .item(0)
               .getChildNodes()
               .item(i)
               .getChildNodes()
               .item(ii)
               .getLocalName()
               .equals("data")) {
             setData(items.item(0).getChildNodes().item(i).getChildNodes().item(ii));
             break;
           }
         }
       }
     }
   }
 }
Example #15
0
  @Override
  protected boolean handleInbound(SOAPMessageContext msgContext) {
    try {
      SOAPMessage soapMessage = msgContext.getMessage();
      SOAPBody soapBody = soapMessage.getSOAPBody();

      SOAPBodyElement soapBodyElement = (SOAPBodyElement) soapBody.getChildElements().next();
      if (soapBodyElement.getChildElements().hasNext()) {
        SOAPElement payload = (SOAPElement) soapBodyElement.getChildElements().next();
        String value = payload.getValue();
        payload.setValue(value + "World");
      }
    } catch (SOAPException e) {
      throw new WebServiceException(e);
    }
    return true;
  }
Example #16
0
  public SOAPMessage invoke(SOAPMessage request) {
    SOAPBody requestBody;
    try {
      requestBody = request.getSOAPBody();
      if (requestBody.getElementName().getLocalName().equals("Body")) {
        MessageFactory mf = MessageFactory.newInstance();
        SOAPFactory sf = SOAPFactory.newInstance();

        SOAPMessage response = mf.createMessage();
        SOAPBody respBody = response.getSOAPBody();
        Name bodyName;
        if (requestBody
            .getFirstChild()
            .getNextSibling()
            .getLocalName()
            .equals("getTomorrowForecast")) {
          bodyName = sf.createName("getTomorrowForecastResponse");
        } else if (requestBody.getFirstChild().getNextSibling().getLocalName().equals("invoke")) {
          bodyName = sf.createName("invokeResponse");
        } else {
          throw new SOAPException(
              "No operation named 'getTomorrowForecast' or 'invoke' was found !");
        }
        respBody.addBodyElement(bodyName);
        SOAPElement respContent = respBody.addChildElement("return");
        respContent.setValue(soapResponse);
        response.saveChanges();
        return response;
      }
    } catch (SOAPException soapEx) {
      logger.error("An error occurs !", soapEx);
    }
    return null;
  }
 public void process(Exchange exchange) throws Exception {
   InputStream is = (InputStream) exchange.getIn().getBody();
   // Bad Hack - Need to remote it and fix it in Camel (if it's a camel problem)
   // I need to copy the results here because I loose them at the end of the method
   String results = StringUtils.toString(is);
   if (is != null) {
     SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
     SOAPBody body = soapMessage.getSOAPPart().getEnvelope().getBody();
     QName payloadName = new QName("http://soap.jax.drools.org/", "executeResponse", "ns1");
     QName responseName = new QName("http://soap.jax.drools.org/", "return", "ns1");
     SOAPBodyElement payload = body.addBodyElement(payloadName);
     SOAPElement response = payload.addChildElement(responseName);
     // Bad Hack - Need to remote it and fix it in Camel (if it's a camel problem)
     // response.addTextNode( StringUtils.toString( is ) );
     response.addTextNode(results);
     exchange.getOut().setBody(soapMessage);
   }
 }
  public boolean handleMessage(SOAPMessageContext mCtx) {
    Boolean outbound = (Boolean) mCtx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (outbound) {
      try {
        SOAPMessage soapMessage = mCtx.getMessage();
        SOAPBody soapBody = soapMessage.getSOAPBody();
        Node firstChild = soapBody.getFirstChild(); // operation name

        String timeStamp = getTimestamp();
        String signature = getSignature(firstChild.getLocalName(), timeStamp, secretBytes);
        append(firstChild, "Signature", signature);
        append(firstChild, "Timestamp", timeStamp);
      } catch (Exception e) {
        throw new RuntimeException("SOAPException thrown.", e);
      }
    }
    return true; // continue down the handler chain
  }
Example #19
0
  private static SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://ws.cdyne.com/";

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", serverURI);

    /*
    Constructed SOAP Request Message:
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
        <SOAP-ENV:Header/>
        <SOAP-ENV:Body>
            <example:VerifyEmail>
                <example:email>[email protected]</example:email>
                <example:LicenseKey>123</example:LicenseKey>
            </example:VerifyEmail>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
     */

    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
    soapBodyElem1.addTextNode("*****@*****.**");
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
    soapBodyElem2.addTextNode("123");

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI + "VerifyEmail");

    soapMessage.saveChanges();

    /* Print the request message */
    System.out.print("Request SOAP Message:");
    soapMessage.writeTo(System.out);
    System.out.println();

    return soapMessage;
  }
  @Test
  public void testService() {
    try {
      QName qname = new QName("urn:simplespService", "simplespServicePort");
      Service service = Service.create(new QName("urn:simplesp", "simplespService"));
      service.addPort(
          qname,
          SOAPBinding.SOAP11HTTP_BINDING,
          "http://" + host + ":" + port + "/simplesp/simplesp");
      Dispatch<SOAPMessage> sourceDispatch =
          service.createDispatch(qname, SOAPMessage.class, Service.Mode.MESSAGE);
      SOAPMessage request = createSOAPMessage(SOAP_SIMPLESP_REQUEST);
      SOAPMessage response = sourceDispatch.invoke(request);
      assertNotNull("\nTest failed:  response is null.", response);

      SOAPBody responseBody = response.getSOAPPart().getEnvelope().getBody();
      Document resultDoc = responseBody.extractContentAsDocument();

      NodeList elts =
          resultDoc.getDocumentElement().getElementsByTagNameNS("urn:simplespService", "result");
      assertTrue(
          "The wrong number of elements were returned.",
          ((elts != null && elts.getLength() > 0) && elts.getLength() == 1));
      Node testNode = elts.item(0);
      assertTrue(
          "Didn't find [<srvc:result>] element",
          testNode.getLocalName().equalsIgnoreCase("result"));

      Document controlDoc = xmlParser.parse(new StringReader(SOAP_SIMPLESP_RESPONSE));
      elts =
          controlDoc.getDocumentElement().getElementsByTagNameNS("urn:simplespService", "result");
      Node ctrlNode = elts.item(0);

      assertTrue(
          "\nDocument comparison failed.  Expected:\n"
              + documentToString(ctrlNode)
              + "\nbut was:\n"
              + documentToString(testNode),
          comparer.isNodeEqual(ctrlNode, testNode));
    } catch (Exception x) {
      fail("Service test failed: " + x.getMessage());
    }
  }
Example #21
0
  public SOAPMessage invokeSoapMessage(SOAPMessage request) {
    SOAPMessage response = null;
    try {
      SOAPBody body = request.getSOAPBody();
      Node n = body.getFirstChild();

      while (n.getNodeType() != Node.ELEMENT_NODE) {
        n = n.getNextSibling();
      }
      if (n.getLocalName().equals(sayHi.getLocalPart())) {
        response = sayHiResponse;
      } else if (n.getLocalName().equals(greetMe.getLocalPart())) {
        response = greetMeResponse;
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return response;
  }
  private Source createSource(SOAPBody soapBody)
      throws TransformerConfigurationException, TransformerException {
    DOMSource source = new DOMSource(soapBody.getFirstChild());
    StringWriter stringResult = new StringWriter();
    TransformerFactory.newInstance()
        .newTransformer()
        .transform(source, new StreamResult(stringResult));
    Source xmlSource = new StreamSource(new StringReader(stringResult.toString()));

    return xmlSource;
  }
 /**
  * Fault response case
  *
  * @throws Exception
  */
 public void testNonAnonymousFaultTo2() throws Exception {
   invokeAsync(
       createDispatchWithoutAddressing(),
       TestMessages.NON_ANONYMOUS_FAULT_TO_COMPLETE_FAULTY_MESSAGE,
       S11_NS,
       nonAnonAddress,
       action,
       endpointAddress,
       "testNonAnonymousReplyTo");
   // Lets see we get a response in 60 s
   SOAPMessage m =
       respMsgExchanger.exchange(null, TestMessages.CLIENT_MAX_TIMEOUT, TimeUnit.SECONDS);
   // System.out.println("****************************");
   // m.writeTo(System.out);
   // System.out.println("\n****************************");
   SOAPBody sb = m.getSOAPBody();
   assertTrue(sb.hasFault());
   SOAPFault fault = sb.getFault();
   assertEquals(fault.getFaultString(), "Negative numbers can't be added!");
 }
Example #24
0
  public boolean handleMessage(SOAPMessageContext context) {
    SOAPMessage sm = context.getMessage();
    try {
      System.out.println("Inside ServerHandler...");
      SOAPBody sb = sm.getSOAPBody();

      Node n = sb.getFirstChild();
      if (n != null) {
        if ((Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)) {
          if (n.getLocalName().equals("echo3Response")) {
            if (!n.getNamespaceURI().equals("http://example.com/echo3"))
              throw new WebServiceException(
                  "Expected: \"http://example.com/echo3\", got: " + n.getNamespaceURI());
            else return true;
          }
          if (!n.getNamespaceURI().equals("http://example.com/")) {
            throw new WebServiceException(
                "Expected: \"http://example.com/\", got: " + n.getNamespaceURI());
          }
        } else {
          if (n.getLocalName().equals("echo3")) {
            if (!n.getNamespaceURI().equals("http://tempuri.org/wsdl"))
              throw new WebServiceException(
                  "Expected: \"http://tempuri.org/wsdl\", got: " + n.getNamespaceURI());
            else return true;
          }
          if (!n.getNamespaceURI().equals("http://tempuri.org/")) {
            throw new WebServiceException(
                "Expected: \"http://tempuri.org/\", got: " + n.getNamespaceURI());
          }
        }
      } else {
        return true;
      }
    } catch (SOAPException e) {
      throw new WebServiceException(e);
    }
    return true;
  }
  // currently designed for sample service implementation
  private void checkForFailureReponse(SOAPBody responseBody) throws Exception {
    SOAPElement faultElement = findSOAPElement(responseBody.getChildElements(), ELEMENT_FAULT);

    if (faultElement == null) {
      return;
    }

    SOAPElement faultCode, faultString;
    faultCode = findSOAPElement(faultElement.getChildElements(), ELEMENT_FAULT_CODE);
    faultString = findSOAPElement(faultElement.getChildElements(), ELEMENT_FAULT_STRING);

    throw new Exception(String.format("%s>> %s", faultCode.getValue(), faultString.getValue()));
  }
  public void testNonAnonymousReplyTo() throws Exception {
    invokeAsync(
        createDispatchWithoutAddressing(),
        TestMessages.NON_ANONYMOUS_REPLY_TO_COMPLETE_MESSAGE,
        S11_NS,
        nonAnonAddress,
        action,
        endpointAddress,
        "testNonAnonymousReplyTo");

    // Lets see we get a response in 60 s
    SOAPMessage m =
        respMsgExchanger.exchange(null, TestMessages.CLIENT_MAX_TIMEOUT, TimeUnit.SECONDS);
    // System.out.println("****************************");
    // m.writeTo(System.out);
    // System.out.println("\n****************************");
    SOAPBody sb = m.getSOAPBody();
    Iterator itr =
        sb.getChildElements(
            new QName("http://server.responses.wsa.fromjava/", "addNumbersResponse"));
    assertTrue(itr.hasNext());
  }
  // Watch out: this functionality affects Drools Server
  //
  // The problem seems to be related with the CXFProducer and the async processors,
  // and it only appears when we do a lookup for different sessions.
  // Using different sessions requires that camel switch classloader to execute commands
  // in the existing sessions. That could be realted too..
  // but in Drools Camel code I don't find any problem
  // The rest endpoint is working ok
  public void testCxfSoapSessionLookup() throws Exception {

    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    SOAPBody body = soapMessage.getSOAPPart().getEnvelope().getBody();
    QName payloadName = new QName("http://soap.jax.drools.org", "execute", "ns1");

    body.addBodyElement(payloadName);

    String cmd = "";
    cmd += "<batch-execution lookup=\"ksession1\">\n";
    cmd += "  <insert out-identifier=\"salaboy\" disconnected=\"true\">\n";
    cmd += "      <org.drools.springframework.Person2>\n";
    cmd += "         <name>salaboy</name>\n";
    cmd += "         <age>27</age>\n";
    cmd += "      </org.drools.springframework.Person2>\n";
    cmd += "   </insert>\n";
    cmd += "   <fire-all-rules/>\n";
    cmd += "</batch-execution>\n";

    body.addTextNode(cmd);

    Object object = this.context.createProducerTemplate().requestBody("direct://http", soapMessage);

    OutputStream out = new ByteArrayOutputStream();
    out = new ByteArrayOutputStream();
    soapMessage = (SOAPMessage) object;
    soapMessage.writeTo(out);
    String response = out.toString();
    assertTrue(response.contains("fact-handle identifier=\"salaboy\""));

    SOAPMessage soapMessage2 = MessageFactory.newInstance().createMessage();
    SOAPBody body2 = soapMessage.getSOAPPart().getEnvelope().getBody();
    QName payloadName2 = new QName("http://soap.jax.drools.org", "execute", "ns1");

    body2.addBodyElement(payloadName2);

    String cmd2 = "";
    cmd2 += "<batch-execution lookup=\"ksession2\">\n";
    cmd2 += "  <insert out-identifier=\"salaboy\" disconnected=\"true\">\n";
    cmd2 += "      <org.drools.springframework.Person3>\n";
    cmd2 += "         <name>salaboy</name>\n";
    cmd2 += "         <age>27</age>\n";
    cmd2 += "      </org.drools.springframework.Person3>\n";
    cmd2 += "   </insert>\n";
    cmd2 += "   <fire-all-rules/>\n";
    cmd2 += "</batch-execution>\n";

    body2.addTextNode(cmd2);

    Object object2 =
        this.context.createProducerTemplate().requestBody("direct://http", soapMessage2);

    OutputStream out2 = new ByteArrayOutputStream();
    out2 = new ByteArrayOutputStream();
    soapMessage2 = (SOAPMessage) object2;
    soapMessage2.writeTo(out2);
    String response2 = out2.toString();
    assertTrue(response2.contains("fact-handle identifier=\"salaboy\""));
  }
Example #28
0
  /**
   * Sets the request parameters for a request.
   *
   * @param context the message context
   * @param params list of parameters to set in order
   * @throws SoapFault
   */
  protected void setSOAPRequestObjects(SOAPMessageContext context, List<SOAPElement> params) {
    // Extract the SOAP Message
    SOAPMessage message = context.getMessage();

    // Get the envelope body
    SOAPBody body;
    try {
      body = message.getSOAPBody();
    } catch (SOAPException e) {
      throw CXFUtility.getFault(e);
    }

    try {
      body.removeContents();
      for (SOAPElement p : params) {
        body.addChildElement(p);
      }
    } catch (Exception e) {
      logger.error("Problem changing SOAP message contents", e);
      throw CXFUtility.getFault(e);
    }
  }
  @Test
  public void testHandleMessage() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();

    String samlAssertion =
        "<Assertion xmlns=\"urn:oasis:names:tc:SAML:1.0:assertion\""
            + " AssertionID=\"_42e7a00652420d86ee884f295a3fbf02\">"
            + "</Assertion>";

    WSSecuritySOAPHandler testedInstance = new WSSecuritySOAPHandler();
    testedInstance.setPrivateKey(privateKey);
    testedInstance.setAssertion(samlAssertion);

    SOAPMessageContext mockSoapMessageContext = EasyMock.createMock(SOAPMessageContext.class);
    EasyMock.expect(mockSoapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY))
        .andReturn(true);

    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
    SOAPBody soapBody = soapEnvelope.getBody();
    soapBody.addBodyElement(new QName("http://www.example.com", "Test"));

    EasyMock.expect(mockSoapMessageContext.getMessage()).andReturn(soapMessage);

    // prepare
    EasyMock.replay(mockSoapMessageContext);

    // operate
    testedInstance.handleMessage(mockSoapMessageContext);

    // verify
    EasyMock.verify(mockSoapMessageContext);
    LOG.debug(toString(soapPart));
  }
 protected QName getOpQName(Exchange ex, Object data) {
   SOAPMessageContextImpl sm = (SOAPMessageContextImpl) data;
   try {
     SOAPMessage msg = sm.getMessage();
     if (msg == null) {
       return null;
     }
     SOAPBody body = msg.getSOAPBody();
     if (body == null) {
       return null;
     }
     org.w3c.dom.Node nd = body.getFirstChild();
     while (nd != null && !(nd instanceof org.w3c.dom.Element)) {
       nd = nd.getNextSibling();
     }
     if (nd != null) {
       return new QName(nd.getNamespaceURI(), nd.getLocalName());
     }
   } catch (SOAPException e) {
     // ignore, nothing we can do
   }
   return null;
 }