Пример #1
0
  // 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\""));
  }
Пример #2
0
  public HttpSOAPConnection() throws SOAPException {

    try {
      messageFactory = MessageFactory.newInstance(SOAPConstants.DYNAMIC_SOAP_PROTOCOL);
    } catch (NoSuchMethodError ex) {
      // fallback to default SOAP 1.1 in this case for backward compatibility
      messageFactory = MessageFactory.newInstance();
    } catch (Exception ex) {
      log.log(Level.SEVERE, "SAAJ0001.p2p.cannot.create.msg.factory", ex);
      throw new SOAPExceptionImpl("Unable to create message factory", ex);
    }
  }
Пример #3
0
  @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);
    }
  }
Пример #4
0
 @Before
 public void setUp() throws Exception {
   msg = MessageFactory.newInstance().createMessage();
   sp = msg.getSOAPPart();
   envelope = sp.getEnvelope();
   hdr = envelope.getHeader();
 }
Пример #5
0
 private SOAPVersion(
     String httpBindingId,
     String nsUri,
     String contentType,
     String implicitRole,
     String roleAttributeName,
     String saajFactoryString,
     QName faultCodeMustUnderstand,
     String faultCodeClientLocalName,
     String faultCodeServerLocalName,
     Set<String> requiredRoles) {
   this.httpBindingId = httpBindingId;
   this.nsUri = nsUri;
   this.contentType = contentType;
   this.implicitRole = implicitRole;
   this.implicitRoleSet = Collections.singleton(implicitRole);
   this.roleAttributeName = roleAttributeName;
   try {
     saajMessageFactory = MessageFactory.newInstance(saajFactoryString);
     saajSoapFactory = SOAPFactory.newInstance(saajFactoryString);
   } catch (SOAPException e) {
     throw new Error(e);
   } catch (NoSuchMethodError e) {
     // SAAJ 1.3 is not in the classpath
     LinkageError x =
         new LinkageError("You are loading old SAAJ from " + Which.which(MessageFactory.class));
     x.initCause(e);
     throw x;
   }
   this.faultCodeMustUnderstand = faultCodeMustUnderstand;
   this.requiredRoles = requiredRoles;
   this.faultCodeClient = new QName(nsUri, faultCodeClientLocalName);
   this.faultCodeServer = new QName(nsUri, faultCodeServerLocalName);
 }
Пример #6
0
 /**
  * processRequest processes PhaseIV Web Service calls. It creates a soap message from input string
  * xmlRequest and invokes Phase IV Web Service processRequest method.
  *
  * @param PhaseIV xmlRequest
  * @return PhaseIV xmlResponse
  * @throws Exception
  */
 public String processRequest(String xmlRequest, String clientURL) throws Exception {
   try {
     if (Utils.getInstance().isNullString(xmlRequest)
         || Utils.getInstance().isNullString(clientURL)) {
       logger.debug("Recieved xmlRequest or clientURL as null");
       return null;
     }
     logger.debug("processRequest--> xmlRequest :" + xmlRequest);
     ByteArrayInputStream inStream = new ByteArrayInputStream(xmlRequest.getBytes());
     StreamSource source = new StreamSource(inStream);
     MessageFactory msgFactory = MessageFactory.newInstance();
     SOAPMessage sMsg = msgFactory.createMessage();
     SOAPPart sPart = sMsg.getSOAPPart();
     sPart.setContent(source);
     MimeHeaders mimeHeader = sMsg.getMimeHeaders();
     mimeHeader.setHeader("SOAPAction", "http://ejbs.phaseiv.bsg.adp.com");
     logger.debug("processRequest-->in PhaseIVClient before call");
     SOAPMessage respMsg = executeCall(sMsg, clientURL);
     logger.debug("processRequest-->in PhaseIVClient after call");
     // SOAPFault faultCode =
     // respMsg.getSOAPPart().getEnvelope().getBody().getFault();
     ByteArrayOutputStream outStream = new ByteArrayOutputStream();
     respMsg.writeTo(outStream);
     logger.debug("processRequest xmlResponse:" + outStream.toString());
     return outStream.toString();
   } catch (Exception exp) {
     logger.error("processRequest --> Error while processing request : " + exp.getMessage());
     logger.error("processRequest --> error xmlRequest:" + xmlRequest);
     exp.printStackTrace();
     throw exp;
   }
 }
Пример #7
0
  @Override
  public SOAPMessage invoke(SOAPMessage request) {
    SOAPMessage response = null;
    try {

      // store request
      File f = File.createTempFile("gen-AdviceOfReceipt", ".xml", new File("unit-test-data"));
      try (FileOutputStream fos = new FileOutputStream(f)) {
        request.writeTo(fos);
      }

      // response key!
      MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
      response = mf.createMessage();

      DOMResult drRes = new DOMResult(response.getSOAPPart());

      // generate AS4 Set message id and timestamp with xalan transformation or progamatically!!
      XMLUtils.deserialize(
          MSHServerTest.class.getResourceAsStream(
              "/test-samples/TEST_01-AdviceOfDelivery-Response.xml"),
          drRes);
      response.saveChanges();

    } catch (IOException ex) {
      Logger.getLogger(MSHTestProvider.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SOAPException ex) {
      Logger.getLogger(MSHTestProvider.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JAXBException ex) {
      Logger.getLogger(MSHTestProvider.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TransformerException ex) {
      Logger.getLogger(MSHTestProvider.class.getName()).log(Level.SEVERE, null, ex);
    }
    return response;
  }
Пример #8
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;
  }
 @Test
 public void buildARecordTest()
     throws SOAPException, IOException, SAXException, ParserConfigurationException,
         TransformerException {
   MessageFactory factory = MessageFactory.newInstance();
   SOAPMessage request = factory.createMessage();
   SOAPPart part = request.getSOAPPart();
   DOMSource domSource =
       new DOMSource(getDocumentBuilder().parse(new InputSource(new StringReader(REQUEST_MSG))));
   part.setContent(domSource);
   Dispatch<SOAPMessage> dispatch =
       testService.createDispatch(portQName, SOAPMessage.class, Service.Mode.MESSAGE);
   SOAPMessage response = null;
   try {
     response = dispatch.invoke(request);
   } catch (Exception e) {
     e.printStackTrace();
   }
   if (response != null) {
     Source src = response.getSOAPPart().getContent();
     DOMResult result = new DOMResult();
     getTransformer().transform(src, result);
     Document resultDoc = (Document) result.getNode();
     Document controlDoc = xmlParser.parse(new StringReader(TEST_RESPONSE));
     assertTrue(
         "control document not same as instance document",
         comparer.isNodeEqual(controlDoc, resultDoc));
   }
 }
  /**
   * @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;
  }
  @Test
  public void testSWA() throws Exception {
    SOAPFactory soapFac = SOAPFactory.newInstance();
    MessageFactory msgFac = MessageFactory.newInstance();
    SOAPConnectionFactory conFac = SOAPConnectionFactory.newInstance();
    SOAPMessage msg = msgFac.createMessage();

    QName sayHi = new QName("http://apache.org/hello_world_rpclit", "sayHiWAttach");
    msg.getSOAPBody().addChildElement(soapFac.createElement(sayHi));
    AttachmentPart ap1 = msg.createAttachmentPart();
    ap1.setContent("Attachment content", "text/plain");
    msg.addAttachmentPart(ap1);
    AttachmentPart ap2 = msg.createAttachmentPart();
    ap2.setContent("Attachment content - Part 2", "text/plain");
    msg.addAttachmentPart(ap2);
    msg.saveChanges();

    SOAPConnection con = conFac.createConnection();
    URL endpoint =
        new URL("http://localhost:9008/SOAPServiceProviderRPCLit/SoapPortProviderRPCLit1");
    SOAPMessage response = con.call(msg, endpoint);
    QName sayHiResp = new QName("http://apache.org/hello_world_rpclit", "sayHiResponse");
    assertNotNull(response.getSOAPBody().getChildElements(sayHiResp));
    assertEquals(2, response.countAttachments());
  }
  @Test
  public void invoke() throws Exception {

    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage request = messageFactory.createMessage();
    request
        .getSOAPBody()
        .addBodyElement(QName.valueOf("{http://springframework.org/spring-ws}Request"));
    MessageContext messageContext =
        new DefaultMessageContext(
            new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory));
    DefaultMethodEndpointAdapter adapter = new DefaultMethodEndpointAdapter();
    adapter.afterPropertiesSet();

    MessageDispatcher messageDispatcher = new SoapMessageDispatcher();
    messageDispatcher.setApplicationContext(applicationContext);
    messageDispatcher.setEndpointMappings(Collections.<EndpointMapping>singletonList(mapping));
    messageDispatcher.setEndpointAdapters(Collections.<EndpointAdapter>singletonList(adapter));

    messageDispatcher.receive(messageContext);

    MyEndpoint endpoint = applicationContext.getBean("endpoint", MyEndpoint.class);
    assertTrue("doIt() not invoked on endpoint", endpoint.isDoItInvoked());

    LogAspect aspect = (LogAspect) applicationContext.getBean("logAspect");
    assertTrue("log() not invoked on aspect", aspect.isLogInvoked());
  }
Пример #13
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 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();
    }
  }
Пример #15
0
 /** Converting String XML to SOAP Message. */
 private SOAPMessage getSoapMessageFromString(String xml) throws SOAPException, IOException {
   MessageFactory factory = MessageFactory.newInstance();
   SOAPMessage message =
       factory.createMessage(
           new MimeHeaders(), new ByteArrayInputStream(xml.getBytes(Charset.forName("UTF-8"))));
   return message;
 }
Пример #16
0
  public void testSendRequest_rpc_nil() throws Exception {
    String requestText =
        "<env:Envelope xmlns:env='"
            + SOAPConstants.URI_NS_SOAP_ENVELOPE
            + "'>"
            + "<env:Body>"
            + "<tns:op xmlns:tns='"
            + BpelConstants.NS_EXAMPLES
            + "' xmlns:xsi='"
            + BpelConstants.NS_XML_SCHEMA_INSTANCE
            + "'>"
            + "  <simplePart xsi:nil='true'>wazabi</simplePart>"
            + "  <complexPart xsi:nil='1'>"
            + "    <b on='true'>true</b>"
            + "    <c name='venus'/>"
            + "    <d amount='20'/>"
            + "    <e>30</e>"
            + "  </complexPart>"
            + "</tns:op>"
            + "</env:Body>"
            + "</env:Envelope>";

    SOAPMessage soapMessage =
        MessageFactory.newInstance()
            .createMessage(null, new ByteArrayInputStream(requestText.getBytes()));

    Connection connection = integrationControl.getJmsConnection();
    connection.start();

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    try {
      SoapHandler soapHandler = createRpcHandler();
      soapHandler.sendRequest(soapMessage, session, jbpmContext);

      PartnerLinkEntry entry =
          integrationControl.getPartnerLinkEntry(Q_RPC_PORT_TYPE, Q_SERVICE, RPC_PORT);
      MessageConsumer consumer = session.createConsumer(entry.getDestination());
      ObjectMessage message = (ObjectMessage) consumer.receiveNoWait();
      Map requestParts = (Map) message.getObject();

      // simple part
      Element simplePart = (Element) requestParts.get("simplePart");
      assertTrue(
          DatatypeUtil.toBoolean(
              simplePart.getAttributeNS(
                  BpelConstants.NS_XML_SCHEMA_INSTANCE, BpelConstants.ATTR_NIL)));
      assertFalse(simplePart.hasChildNodes());

      // complex part
      Element complexPart = (Element) requestParts.get("complexPart");
      assertTrue(
          DatatypeUtil.toBoolean(
              complexPart.getAttributeNS(
                  BpelConstants.NS_XML_SCHEMA_INSTANCE, BpelConstants.ATTR_NIL)));
      assertFalse(complexPart.hasChildNodes());
    } finally {
      session.close();
    }
  }
Пример #17
0
  private SoapMessage makeInvocation(
      Map<String, String> outProperties, List<String> xpaths, Map<String, String> inProperties)
      throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);

    SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    part.setContent(new DOMSource(doc));
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);

    for (String key : outProperties.keySet()) {
      msg.put(key, outProperties.get(key));
    }

    handler.handleMessage(msg);

    doc = part;

    for (String xpath : xpaths) {
      assertValid(xpath, doc);
    }

    byte[] docbytes = getMessageBytes(doc);
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

    WSS4JInInterceptor inHandler = new WSS4JInInterceptor();

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    for (String key : inProperties.keySet()) {
      inHandler.setProperty(key, inProperties.get(key));
    }

    inHandler.handleMessage(inmsg);

    return inmsg;
  }
Пример #18
0
  public void testSendRequest_rpc() throws Exception {
    String requestText =
        "<env:Envelope xmlns:env='"
            + SOAPConstants.URI_NS_SOAP_ENVELOPE
            + "'>"
            + "<env:Body>"
            + "<tns:op xmlns:tns='"
            + BpelConstants.NS_EXAMPLES
            + "'>"
            + "  <simplePart>wazabi</simplePart>"
            + "  <complexPart>"
            + "    <b on='true'>true</b>"
            + "    <c name='venus'/>"
            + "    <d amount='20'/>"
            + "    <e>30</e>"
            + "  </complexPart>"
            + "</tns:op>"
            + "</env:Body>"
            + "</env:Envelope>";
    SOAPMessage soapMessage =
        MessageFactory.newInstance()
            .createMessage(null, new ByteArrayInputStream(requestText.getBytes()));

    Connection connection = integrationControl.getJmsConnection();
    connection.start();

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    try {
      SoapHandler soapHandler = createRpcHandler();
      soapHandler.sendRequest(soapMessage, session, jbpmContext);

      PartnerLinkEntry entry =
          integrationControl.getPartnerLinkEntry(Q_RPC_PORT_TYPE, Q_SERVICE, RPC_PORT);
      MessageConsumer consumer = session.createConsumer(entry.getDestination());
      ObjectMessage message = (ObjectMessage) consumer.receiveNoWait();
      Map requestParts = (Map) message.getObject();

      // simple part
      Element simplePart = (Element) requestParts.get("simplePart");
      assertEquals("simplePart", simplePart.getLocalName());
      assertNull(simplePart.getNamespaceURI());
      assertEquals("wazabi", DatatypeUtil.toString(simplePart));

      // complex part
      Element complexPart = (Element) requestParts.get("complexPart");
      assertEquals("complexPart", complexPart.getLocalName());
      assertNull(complexPart.getNamespaceURI());
      assertTrue(complexPart.hasChildNodes());

      // message properties
      assertEquals(
          rpcPartnerLinkId, message.getLongProperty(IntegrationConstants.PARTNER_LINK_ID_PROP));
      assertEquals("op", message.getStringProperty(IntegrationConstants.OPERATION_NAME_PROP));
      assertEquals("venus", message.getStringProperty("nameProperty"));
      assertEquals("30", message.getStringProperty("idProperty"));
    } finally {
      session.close();
    }
  }
Пример #19
0
  private SOAPMessage writeDocOutput() throws Exception {
    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    Map responseParts = createOutputDocParts();

    SoapHandler soapHandler = createDocHandler();
    soapHandler.writeOutput("op", soapMessage, responseParts);
    return soapMessage;
  }
Пример #20
0
 public WsRpcConnection() {
   try {
     connectionFactory = SOAPConnectionFactory.newInstance();
     messageFactory = MessageFactory.newInstance();
   } catch (Exception e) {
     logger.debug(e.getMessage(), e);
   }
 }
Пример #21
0
  @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);
  }
Пример #22
0
 public static SOAPMessage createFromXml(String filePath) {
   try {
     File file = new File(filePath);
     InputStream in = new FileInputStream(file);
     SOAPMessage m = MessageFactory.newInstance().createMessage(null, in);
     return m;
   } catch (Exception e) {
     return null;
   }
 }
Пример #23
0
 static {
   b.setBinary1(
       "fkldhafkdahfkdhfkhasdkfhldashfi9pweqryiweqyriqelhfklasdhfkldashflksdah".getBytes());
   b.setBinary2(
       "epriepireroerupequreopruopweuqrowequrpoweqrupweqrweqrweuqrweqrwerwerer".getBytes());
   try {
     messageFactory = MessageFactory.newInstance();
   } catch (SOAPException e) {
     e.printStackTrace();
   }
 }
Пример #24
0
  private Object parseMessage() {
    // Consume SOAP message, if any
    // TODO: Add a SOAP handler in Parser.java
    if (soapAction != null) {
      try {
        MimeHeaders mime_headers = new MimeHeaders();

        for (Object k : headers.getIds()) {
          if (k instanceof String) {
            String name = (String) k;
            String value = Context.toString(ScriptableObject.getProperty(headers, name));

            mime_headers.addHeader(name, value);
          }
        }

        return MessageFactory.newInstance(SOAPConstants.DYNAMIC_SOAP_PROTOCOL)
            .createMessage(mime_headers, request.getInputStream());
      } catch (IOException ex) {
        throw new ESXXException("Unable to read SOAP message stream: " + ex.getMessage());
      } catch (SOAPException ex) {
        throw new ESXXException(400 /* Bad Request */, "Invalid SOAP message: " + ex.getMessage());
      } finally {
        try {
          request.getInputStream().close();
        } catch (Exception ignored) {
        }
      }
    } else if (contentType != null && contentLength > 0) {
      try {
        ESXX esxx = ESXX.getInstance();
        return esxx.parseStream(
            contentType,
            request.getInputStream(),
            URI.create("urn:x-esxx:incoming-request-entity"),
            null,
            new java.io.PrintWriter(request.getErrorWriter()),
            Context.getCurrentContext(),
            this);
      } catch (Exception ex) {
        throw new ESXXException(
            400 /* Bad Request */, "Unable to parse request entity: " + ex.getMessage(), ex);
      } finally {
        try {
          request.getInputStream().close();
        } catch (Exception ignored) {
        }
      }
    } else {
      // Return a dummy object
      return Context.getCurrentContext().newObject(this);
    }
  }
Пример #25
0
  private void doTestSoapConnection(boolean disableChunking) throws Exception {
    SOAPFactory soapFac = SOAPFactory.newInstance();
    MessageFactory msgFac = MessageFactory.newInstance();
    SOAPConnectionFactory conFac = SOAPConnectionFactory.newInstance();
    SOAPMessage msg = msgFac.createMessage();

    if (disableChunking) {
      // this is the custom header checked by ServiceImpl
      msg.getMimeHeaders().addHeader("Transfer-Encoding-Disabled", "true");
      // this is a hint to SOAPConnection that the chunked encoding is not needed
      msg.getMimeHeaders().addHeader("Transfer-Encoding", "disabled");
    }

    QName sayHi = new QName("http://www.jboss.org/jbossws/saaj", "sayHello");
    msg.getSOAPBody().addChildElement(soapFac.createElement(sayHi));
    AttachmentPart ap1 = msg.createAttachmentPart();

    char[] content = new char[16 * 1024];
    Arrays.fill(content, 'A');

    ap1.setContent(new String(content), "text/plain");
    msg.addAttachmentPart(ap1);

    AttachmentPart ap2 = msg.createAttachmentPart();
    ap2.setContent("Attachment content - Part 2", "text/plain");
    msg.addAttachmentPart(ap2);
    msg.saveChanges();

    SOAPConnection con = conFac.createConnection();

    final String serviceURL = baseURL.toString();

    URL endpoint = new URL(serviceURL);
    SOAPMessage response = con.call(msg, endpoint);
    QName sayHiResp = new QName("http://www.jboss.org/jbossws/saaj", "sayHelloResponse");

    Iterator<?> sayHiRespIterator = response.getSOAPBody().getChildElements(sayHiResp);
    SOAPElement soapElement = (SOAPElement) sayHiRespIterator.next();
    assertNotNull(soapElement);

    assertEquals(2, response.countAttachments());

    String[] values = response.getMimeHeaders().getHeader("Transfer-Encoding-Disabled");
    if (disableChunking) {
      // this means that the ServiceImpl executed the code branch verifying
      // that chunking was disabled
      assertNotNull(values);
      assertTrue(values.length == 1);
    } else {
      assertNull(values);
    }
  }
Пример #26
0
  static {
    try {
      fac = MessageFactory.newInstance();
    } catch (Exception ex) {
      FSUtils.debug.error(FSUtils.bundle.getString("missingSOAPMessageFactory"), ex);
    }

    try {
      scf = SOAPConnectionFactory.newInstance();
    } catch (SOAPException e) {
      FSUtils.debug.error("FSSOAPService", e);
    }
  };
Пример #27
0
  // send to an explicit URI
  public void customSendAndReceive() throws SOAPException {
    MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
    SaajSoapMessageFactory newSoapMessageFactory = new SaajSoapMessageFactory(messageFactory);
    webServiceTemplate.setMessageFactory(newSoapMessageFactory);

    StreamSource source = new StreamSource(new StringReader(REQUEST_PERIODIC));
    StreamResult result = new StreamResult(System.out);
    webServiceTemplate.sendSourceAndReceiveToResult(
        URL_PERIODIC,
        source,
        new SoapActionCallback("http://www.webserviceX.NET/GetAtomicWeight"),
        result);
  }
Пример #28
0
  public SoapTargetBean() {

    try {
      MessageFactory factory = MessageFactory.newInstance();
      InputStream is = getClass().getResourceAsStream("sayHiDocLiteralResp.xml");
      sayHiResponse = factory.createMessage(null, is);
      is.close();
      is = getClass().getResourceAsStream("GreetMeDocLiteralResp.xml");
      greetMeResponse = factory.createMessage(null, is);
      is.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Пример #29
0
  @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());
  }
  public Document invokeMethod(DynamicBinder dBinder, Document inputDoc) throws ComponentException {
    try {
      logger.info(
          "URI : "
              + dBinder.wsdlURI
              + "\n porttype: "
              + dBinder.portType
              + " \n operation: "
              + dBinder.operation
              + "\n endpoint: "
              + dBinder.endPoint);

      QName serviceName = new QName(dBinder.targetNS, dBinder.serviceName);
      Service serv = Service.create(serviceName);

      QName portQName = new QName(dBinder.targetNS, dBinder.portType);
      serv.addPort(portQName, SOAPBinding.SOAP11HTTP_BINDING, dBinder.endPoint);

      MessageFactory factory = MessageFactory.newInstance();
      SOAPMessage message = factory.createMessage();

      // TODO: add namespaces declared on the SOAPBody level to the envelope
      message.getSOAPPart().getEnvelope().addNamespaceDeclaration("tns1", dBinder.targetNS);
      message.getSOAPBody().addDocument(inputDoc);
      message.getMimeHeaders().addHeader("SOAPAction", dBinder.operation);
      message.saveChanges();

      Dispatch<SOAPMessage> smDispatch =
          serv.createDispatch(portQName, SOAPMessage.class, Service.Mode.MESSAGE);

      List<Handler> handlers = smDispatch.getBinding().getHandlerChain();
      handlers.add(new SOAPLoggingHandler());
      smDispatch.getBinding().setHandlerChain(handlers);

      SOAPMessage soapResponse = null;
      try {
        soapResponse = smDispatch.invoke(message);
      } catch (Exception e) {
        logger.error("Fault has been returned in SOAP message!!!");
        return null;
      }

      return toDocument(soapResponse);
    } catch (Exception e) {
      logger.error(e.getMessage());
      throw new ComponentException(e.getMessage());
    }
  }