private void serializeRuntimeException() throws WebServiceException {
    try {
      MessageFactory factory = _soapContext.getMessageFactory();
      SOAPMessage message = factory.createMessage();

      QName faultcode =
          new QName(
              message.getSOAPBody().getNamespaceURI(), "Server", message.getSOAPBody().getPrefix());

      message.getSOAPBody().addFault(faultcode, _runtimeException.getMessage());

      _soapContext.setMessage(message);
      _source = _soapContext.getMessage().getSOAPPart().getContent();
    } catch (SOAPException se) {
      throw new WebServiceException(se);
    }
  }
Example #2
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();
    }
  }
 /** 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;
 }
  @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());
  }
Example #5
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;
 }
Example #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;
   }
 }
  @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());
  }
  /** @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();
    }
  }
Example #9
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));
   }
 }
Example #11
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;
  }
Example #12
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);
    }
  }
Example #13
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());
    }
  }
 private SOAPBody getSOAPBody(String request)
     throws UnsupportedEncodingException, SoapExceptionClient, IOException {
   SOAPMessage soapMessage = null;
   SOAPBody soapBody = null;
   try {
     MessageFactory factory = MessageFactory.newInstance();
     soapMessage =
         factory.createMessage(
             new MimeHeaders(), new ByteArrayInputStream(request.getBytes("UTF-8")));
     soapBody = soapMessage.getSOAPBody();
   } catch (SOAPException e) {
     throw new SoapExceptionClient(
         e.getLocalizedMessage() + " Cause: " + e.getCause().toString(), e);
   }
   return soapBody;
 }
 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 #17
0
  public SOAPClient(String url, String soapAction)
      throws UnsupportedOperationException, SOAPException {
    // Create the connection
    SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
    conn = scf.createConnection();

    // Create message
    MessageFactory mf = MessageFactory.newInstance();
    soapRequest = mf.createMessage();
    wsdlURL = url;

    // add SOAP Action
    if (soapAction != null) {
      MimeHeaders hd = soapRequest.getMimeHeaders();
      hd.addHeader("SOAPAction", soapAction);
    }
  }
Example #18
0
  /*
   * Binds the passed object xml string to SOAP message.
   * The SOAP Message will then be sent across to the remote
   * provider for processing.
   * @param xmlString the request/response xml string to be bound
   * @return SOAPMessage constructed from the xml string
   */
  public SOAPMessage bind(String xmlString) {
    SOAPMessage msg = null;
    MimeHeaders mimeHeaders = new MimeHeaders();
    mimeHeaders.addHeader("Content-Type", "text/xml");
    StringBuffer envBegin = new StringBuffer(100);
    envBegin
        .append("<")
        .append(IFSConstants.SOAP_ENV_PREFIX)
        .append(":Envelope")
        .append(IFSConstants.SPACE)
        .append("xmlns:")
        .append(IFSConstants.SOAP_ENV_PREFIX)
        .append("=\"")
        .append(IFSConstants.SOAP_URI)
        .append("\">")
        .append(IFSConstants.NL)
        .append("<")
        .append(IFSConstants.SOAP_ENV_PREFIX)
        .append(":Body>")
        .append(IFSConstants.NL);

    StringBuffer envEnd = new StringBuffer(100);
    envEnd
        .append(IFSConstants.START_END_ELEMENT)
        .append(IFSConstants.SOAP_ENV_PREFIX)
        .append(":Body>")
        .append(IFSConstants.NL)
        .append(IFSConstants.START_END_ELEMENT)
        .append(IFSConstants.SOAP_ENV_PREFIX)
        .append(":Envelope>")
        .append(IFSConstants.NL);
    try {
      StringBuffer sb = new StringBuffer(300);
      sb.append(envBegin).append(xmlString).append(envEnd);
      if (FSUtils.debug.messageEnabled()) {
        FSUtils.debug.message("response created is: " + sb.toString() + "\n--------------------");
      }
      ByteArrayOutputStream bop = new ByteArrayOutputStream();
      bop.write(sb.toString().getBytes(IFSConstants.DEFAULT_ENCODING));
      msg = fac.createMessage(mimeHeaders, new ByteArrayInputStream(bop.toByteArray()));
    } catch (Exception e) {
      FSUtils.debug.error("could not build response:", e);
      return null;
    }
    return msg;
  }
 @Test
 public void updateinstanceTest()
     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);
   try {
     dispatch.invoke(request);
   } catch (SOAPFaultException sfe) {
     assertTrue("incorrect SOAPFaultException", sfe.getMessage().contains("EclipseLink-5010"));
   }
 }
  private void serializeProtocolException() throws WebServiceException {
    if (_protocolException instanceof SOAPFaultException) {
      SOAPFaultException sfe = (SOAPFaultException) _protocolException;
      SOAPFault fault = sfe.getFault();

      try {
        MessageFactory factory = _soapContext.getMessageFactory();
        SOAPMessage message = factory.createMessage();
        message.getSOAPBody().addChildElement(fault);
        _soapContext.setMessage(message);
        _source = _soapContext.getMessage().getSOAPPart().getContent();
      } catch (SOAPException se) {
        throw new WebServiceException(se);
      }
    } else {
      throw new WebServiceException(L.l("Unsupported ProtocolException: {0}", _protocolException));
    }
  }
Example #21
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;
  }
Example #22
0
  /**
   * Converts Document to SOAPMessage
   *
   * @param doc the source Document
   * @return SOAPMessage
   * @throws SOAPBindingException if an error occurs while converting the document
   * @supported.api
   */
  public static SOAPMessage DocumentToSOAPMessage(Document doc) throws SOAPBindingException {
    SOAPMessage msg = null;
    try {
      MimeHeaders mimeHeaders = new MimeHeaders();
      mimeHeaders.addHeader("Content-Type", "text/xml");

      String xmlstr = XMLUtils.print(doc);
      if (debug.messageEnabled()) {
        debug.message("Utils.DocumentToSOAPMessage: xmlstr = " + xmlstr);
      }
      msg =
          messageFactory.createMessage(
              mimeHeaders,
              new ByteArrayInputStream(xmlstr.getBytes(SOAPBindingConstants.DEFAULT_ENCODING)));
    } catch (Exception e) {
      debug.error("Utils.DocumentToSOAPMessage", e);
      throw new SOAPBindingException(e.getMessage());
    }
    return msg;
  }
Example #23
0
  /** @testStrategy Tests conversions between SAAJ and OM for normal element */
  public void test2() throws Exception {

    // Bootstrap: Create an OM SOAPEnvelope from the sample text.
    StringReader sr = new StringReader(sampleEnvelope);
    XMLStreamReader inflow = inputFactory.createXMLStreamReader(sr);
    StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(inflow, null);
    org.apache.axiom.soap.SOAPEnvelope omEnvelope = builder.getSOAPEnvelope();

    // Bootstrap: Get an OMElement from the body
    OMElement om = omEnvelope.getBody().getFirstElement();

    // Bootstrap: Get an SAAJ Body to hold the target SOAPElement
    MessageFactory msgFactory = MessageFactory.newInstance();
    SOAPMessage message = msgFactory.createMessage();
    SOAPBody body = message.getSOAPBody();

    // Step 1: Get the SAAJConverter object from the Factory
    SAAJConverterFactory f =
        (SAAJConverterFactory) FactoryRegistry.getFactory(SAAJConverterFactory.class);
    SAAJConverter converter = f.getSAAJConverter();

    // Step 2: Convert OM to SAAJ
    SOAPElement se = converter.toSAAJ(om, body);

    // Step 2a: Verify
    assertTrue(se instanceof SOAPBodyElement);
    assertTrue(se.getLocalName().equals("a"));

    // Step 3: Convert SAAJ to OM
    om = converter.toOM(se);

    // Step 3a: Verify
    assertTrue(om.getLocalName().equals("a"));

    // Step 4: Rinse and Repeat
    se = converter.toSAAJ(om, body);
    assertTrue(se instanceof SOAPBodyElement);
    assertTrue(se.getLocalName().equals("a"));
    om = converter.toOM(se);
    assertTrue(om.getLocalName().equals("a"));
  }
Example #24
0
  @Override
  protected SOAPMessage processExceptionResponse(
      final String message, final String code, final String locator) {
    try {
      final ObjectFactory owsFactory = new ObjectFactory();
      final ExceptionType exceptionType = new ExceptionType(message, code, locator);

      final MessageFactory factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
      final SOAPMessage response = factory.createMessage();
      final Detail detail = response.getSOAPBody().addFault(SENDER_CODE, message).addDetail();

      final Marshaller m = getMarshallerPool().acquireMarshaller();
      m.marshal(owsFactory.createException(exceptionType), detail);
      getMarshallerPool().recycle(m);

      // detail.appendChild(n);
      return response;
    } catch (JAXBException | SOAPException ex) {
      LOGGER.log(Level.WARNING, null, ex);
      throw new RuntimeException(ex.getMessage());
    }
  }
  @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));
  }
 public String invokeServiceMethod(String methodName, String[] args) {
   try {
     MessageFactory factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
     SOAPMessage request = factory.createMessage();
     SOAPPart soap = request.getSOAPPart();
     SOAPEnvelope envelope = soap.getEnvelope();
     SOAPBody body = envelope.getBody();
     SOAPElement content = body.addBodyElement(new QName(serviceNs, methodName, "itu"));
     int c = 0;
     for (String arg : args) {
       SOAPElement name;
       name = content.addChildElement("arg" + c++);
       name.setTextContent(arg);
     }
     Dispatch<SOAPMessage> dispatch =
         webservice.createDispatch(port, SOAPMessage.class, Service.Mode.MESSAGE);
     SOAPMessage response = dispatch.invoke(request);
     String text = response.getSOAPBody().getTextContent();
     return text;
   } catch (SOAPException e) {
     throw new RuntimeException(e);
   }
 }
  public static void main(String[] args) throws SOAPException {
    // Service helloService = new HelloService();
    QName serviceName = new QName(targetNamespace, serName);
    QName portName = new QName(targetNamespace, pName);
    // Hello hello = helloService.getPortName();
    javax.xml.ws.Service service = Service.create(serviceName);
    service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
    Dispatch<SOAPMessage> dispatch =
        service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE);
    BindingProvider bp = (BindingProvider) dispatch;
    Map<String, Object> rc = bp.getRequestContext();
    rc.put(BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
    rc.put(BindingProvider.SOAPACTION_URI_PROPERTY, OPER_NAME);
    MessageFactory factory = ((SOAPBinding) bp.getBinding()).getMessageFactory();

    SOAPMessage request = factory.createMessage();
    SOAPBody body = request.getSOAPBody();
    QName payloadName = new QName(targetNamespace, OPER_NAME, "ns1");
    SOAPBodyElement payload = body.addBodyElement(payloadName);
    SOAPElement message = payload.addChildElement(INPUT_NAME);
    message.addTextNode("x");
    //		String value = "<people>" +
    //				"<name>TimLu</name>"+
    //				"<age>26</age>"+
    //				"</people>";
    //		message.setValue(value);
    SOAPMessage reply = null;
    try {
      reply = dispatch.invoke(request);
    } catch (WebServiceException wse) {
      wse.printStackTrace();
    }
    SOAPBody soapBody = reply.getSOAPBody();
    SOAPBodyElement nextSoapBodyElement = (SOAPBodyElement) soapBody.getChildElements().next();
    SOAPElement soapElement = (SOAPElement) nextSoapBodyElement.getChildElements().next();
    System.out.println("Return repsone value=" + soapElement.getValue());
  }
  private SOAPMessage actionToSoap(RpcInvokeAction action) throws Exception {
    useFirstElementPrefix = true;

    SOAPMessage message = messageFactory.createMessage();
    actionData =
        WsRpcActionUtil.getWsRpcActionData(((SimpleRpcInvokeAction) action).getProperties());

    SOAPEnvelope env = message.getSOAPPart().getEnvelope();
    env.addNamespaceDeclaration(ACTION_PREFIX, actionData.getMethodInputNameSpace());

    setFields(action.getFields(), env.getBody());

    if (actionData.getSoapAction().length() > 0) {
      message.getMimeHeaders().addHeader("SOAPAction", actionData.getSoapAction());
    }

    // Base auth headers from http://www.whitemesa.com/soapauth.html#S322
    /*
     * all auth standarts: http://www.soapui.org/testing-dojo/best-practices/authentication.html
     */
    if (props.getPassword() != null
        && props.getUserName() != null
        && !props.getUserName().trim().equals("")) {
      SOAPHeaderElement auth =
          message
              .getSOAPHeader()
              .addHeaderElement(
                  new QName("http://soap-authentication.org/basic/2001/10/", "BasicAuth", "h"));
      auth.setMustUnderstand(true);
      auth.addChildElement("Name").setValue(props.getUserName());
      auth.addChildElement("Password").setValue(props.getPassword());
    }

    logMessage("Request message:", message);

    return message;
  }
  @Test
  public void testContextClose() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    int port = FreePortScanner.getFreePort();
    Server jettyServer = new Server(port);
    Context jettyContext = new Context(jettyServer, "/");
    jettyContext.addServlet(new ServletHolder(new EchoServlet()), "/");
    jettyServer.start();
    WebServiceConnection connection = null;
    try {

      StaticApplicationContext appContext = new StaticApplicationContext();
      appContext.registerSingleton("messageSender", CommonsHttpMessageSender.class);
      appContext.refresh();

      CommonsHttpMessageSender messageSender =
          appContext.getBean("messageSender", CommonsHttpMessageSender.class);
      connection = messageSender.createConnection(new URI("http://localhost:" + port));

      appContext.close();

      connection.send(new SaajSoapMessage(messageFactory.createMessage()));
      connection.receive(new SaajSoapMessageFactory(messageFactory));
    } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (IOException ex) {
          // ignore
        }
      }
      if (jettyServer.isRunning()) {
        jettyServer.stop();
      }
    }
  }
  protected SOAPMessage createQueryMessage() {
    String queryStr = getQueryString();

    if (log.isDebugEnabled()) {
      log.debug("MDX query: " + queryStr);
    }

    try {
      MessageFactory mf = MessageFactory.newInstance();
      SOAPMessage message = mf.createMessage();

      MimeHeaders mh = message.getMimeHeaders();
      mh.setHeader("SOAPAction", "\"urn:schemas-microsoft-com:xml-analysis:Execute\"");

      SOAPPart soapPart = message.getSOAPPart();
      SOAPEnvelope envelope = soapPart.getEnvelope();
      SOAPBody body = envelope.getBody();
      Name nEx = envelope.createName("Execute", "", XMLA_URI);

      SOAPElement eEx = body.addChildElement(nEx);

      // add the parameters

      // COMMAND parameter
      // <Command>
      // <Statement>queryStr</Statement>
      // </Command>
      Name nCom = envelope.createName("Command", "", XMLA_URI);
      SOAPElement eCommand = eEx.addChildElement(nCom);
      Name nSta = envelope.createName("Statement", "", XMLA_URI);
      SOAPElement eStatement = eCommand.addChildElement(nSta);
      eStatement.addTextNode(queryStr);

      // <Properties>
      // <PropertyList>
      // <DataSourceInfo>dataSource</DataSourceInfo>
      // <Catalog>catalog</Catalog>
      // <Format>Multidimensional</Format>
      // <AxisFormat>TupleFormat</AxisFormat>
      // </PropertyList>
      // </Properties>
      Map paraList = new HashMap();
      String datasource =
          (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_DATASOURCE);
      paraList.put("DataSourceInfo", datasource);
      String catalog =
          (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_CATALOG);
      paraList.put("Catalog", catalog);
      paraList.put("Format", "Multidimensional");
      paraList.put("AxisFormat", "TupleFormat");
      addParameterList(envelope, eEx, "Properties", "PropertyList", paraList);
      message.saveChanges();

      if (log.isDebugEnabled()) {
        log.debug("XML/A query message: " + message.toString());
      }

      return message;
    } catch (SOAPException e) {
      throw new JRRuntimeException(e);
    }
  }