/** Adds an "Access" element to the SOAP header */
  public boolean handleRequest(MessageContext msgct) {
    if (msgct instanceof SOAPMessageContext) {
      SOAPMessageContext smsgct = (SOAPMessageContext) msgct;
      try {
        SOAPMessage msg = smsgct.getMessage();
        SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
        SOAPHeader header = msg.getSOAPHeader();

        if (header == null) header = envelope.addHeader(); // add an header if non exists

        SOAPHeaderElement accessElement =
            header.addHeaderElement(
                envelope.createName(
                    "Access", "ns0", "http://www.ipd.uni-karlsruhe.de/jplag/types"));
        SOAPElement usernameelem = accessElement.addChildElement("username");
        usernameelem.addTextNode(username);
        SOAPElement passwordelem = accessElement.addChildElement("password");
        passwordelem.addTextNode(password);
        SOAPElement compatelem = accessElement.addChildElement("compatLevel");
        compatelem.addTextNode(compatibilityLevel + "");
      } catch (SOAPException x) {
        System.out.println("Unable to create access SOAP header!");
        x.printStackTrace();
      }
    }
    return true;
  }
Example #2
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;
   }
 }
  @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 #4
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 testWriteOutput_saaj_rpc() throws Exception {
    SOAPMessage soapMessage = writeRpcOutput();

    // soap body
    SOAPBody bodyElem = soapMessage.getSOAPBody();
    // operation wrapper
    SOAPElement operationElem =
        SoapUtil.getElement(bodyElem, BpelConstants.NS_EXAMPLES, "opResponse");

    // simple part
    SOAPElement intPart = SoapUtil.getElement(operationElem, "intPart");
    // value
    assertEquals("2020", intPart.getValue());

    // complex part
    SOAPElement complexPart = SoapUtil.getElement(operationElem, "complexPart");
    // attributes
    assertEquals("hi", complexPart.getAttribute("attributeOne"));
    assertEquals("ho", complexPart.getAttribute("attributeTwo"));
    // child elements
    SOAPElement one = SoapUtil.getElement(complexPart, "urn:uriOne", "elementOne");
    assertEquals("ram", one.getValue());
    SOAPElement two = SoapUtil.getElement(complexPart, "urn:uriTwo", "elementTwo");
    assertEquals("ones", two.getValue());
  }
  @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());
  }
  public void testCreateDispatchSMWsdlMSEPRNoPortQName() throws Exception {

    if (ClientServerTestUtil.useLocal()) {
      System.out.println("HTTP Transport Only Exiting");
      return;
    }

    RespectBindingFeature rbf = new RespectBindingFeature(false);
    WebServiceFeature[] wse = new WebServiceFeature[] {rbf};
    Service service = createServiceWithWSDL();
    MemberSubmissionEndpointReference msEPR = createMSEPRStubServiceWithWSDL(service);
    msEPR.portTypeName.name = null;
    MSEPRString = msEPR.toString();

    Dispatch<SOAPMessage> dispatch =
        service.createDispatch(
            EndpointReference.readFrom(makeStreamSource(MSEPRString)),
            SOAPMessage.class,
            Service.Mode.MESSAGE,
            wse);
    SOAPMessage sm = dispatch.invoke(getSOAPMessage(makeStreamSource(SMMsg)));
    sm.writeTo(System.out);

    // System.out.println("Adding numbers 2 and 4");
    // int result = dispatch.invoke(getSOAPMessage())
    // assert(result == 6);
    // System.out.println("Addinion of 2 and 4 successful");
  }
    @Override
    protected Soap createMessage(byte[] rawXml, SOAPMessage soap, String charset) throws Exception {
      if (soap.getSOAPHeader() != null) {
        SoapHeader header = unmarshalHeader(SoapHeader.class, soap.getSOAPHeader());
        if (header.getCentralService() != null) {
          if (header.getService() != null) {
            throw new CodedException(
                X_MALFORMED_SOAP,
                "Message header must contain either service id" + " or central service id");
          }

          ServiceId serviceId = GlobalConf.getServiceId(header.getCentralService());
          header.setService(serviceId);

          SOAPEnvelope envelope = soap.getSOAPPart().getEnvelope();
          envelope.removeChild(soap.getSOAPHeader());

          Node soapBody = envelope.removeChild(soap.getSOAPBody());
          envelope.removeContents(); // removes newlines etc.

          Marshaller marshaller =
              JaxbUtils.createMarshaller(SoapHeader.class, new SoapNamespacePrefixMapper());
          marshaller.marshal(header, envelope);

          envelope.appendChild(soapBody);

          byte[] newRawXml = SoapUtils.getBytes(soap);
          return super.createMessage(newRawXml, soap, charset);
        }
      }
      return super.createMessage(rawXml, soap, charset);
    }
Example #9
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();
    }
  }
  public void testCreateDispatchSMWsdlWEPR() throws Exception {
    String eprString =
        "<EndpointReference xmlns=\"http://www.w3.org/2005/08/addressing\"><Address>"
            + "http://localhost:8080/jaxrpc-client_jaxws21_service_dispatch_features/hello</Address>"
            + "<Metadata><wsaw:ServiceName xmlns:wsaw=\"http://www.w3.org/2006/05/addressing/wsdl\" xmlns:wsns=\"http://example.com/\" EndpointName=\"AddNumbersPort\">wsns:AddNumbersService</wsaw:ServiceName>"
            + "</Metadata></EndpointReference>";
    if (ClientServerTestUtil.useLocal()) {
      System.out.println("HTTP Transport Only Exiting");
      return;
    }

    RespectBindingFeature rbf = new RespectBindingFeature(false);
    WebServiceFeature[] wse = new WebServiceFeature[] {rbf};
    Service service = createServiceWithWSDL();
    EndpointReference w3cEPR = createEPRStubServiceWithWSDL(service);
    // W3CEPRString = w3cEPR.toString();
    W3CEPRString = eprString;
    Dispatch<SOAPMessage> dispatch =
        service.createDispatch(
            EndpointReference.readFrom(makeStreamSource(W3CEPRString)),
            SOAPMessage.class,
            Service.Mode.MESSAGE);
    SOAPMessage sm = dispatch.invoke(getSOAPMessage(makeStreamSource(SMMsg)));
    sm.writeTo(System.out);
    // System.out.println("Adding numbers 2 and 4");
    // int result = dispatch.invoke(getSOAPMessage())
    // assert(result == 6);
    // System.out.println("Addinion of 2 and 4 successful");
  }
Example #11
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;
  }
Example #12
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);
    }
  }
Example #13
0
  private void addAttachment(SOAPMessageContext messageContext) {
    if (logger.isInfoEnabled()) {
      logger.info("Inside handler addAttachment Method");
    }
    byte[] byt = null;
    SOAPMessage message;
    AttachmentPart attach;
    byt = (byte[]) messageContext.get("attachment");
    WrappedMessageContext wmc = (WrappedMessageContext) messageContext;
    Message cxfmsg = wmc.getWrappedMessage();
    SOAPMessageContextImpl smci = new SOAPMessageContextImpl(cxfmsg);
    message = smci.getMessage();
    if (byt != null) {
      logger.info("Attachment content :::" + new String(byt));
      ByteArrayDataSource source = new ByteArrayDataSource(byt, "Multipart/Related");
      DataHandler dataHandler = new DataHandler(source);
      // attach = message.createAttachmentPart(byt, "Multipart/Related");
      attach = message.createAttachmentPart(dataHandler);
      // attach.setMimeHeader("attc", "abcd");
      // attach.setContentId("1234567");

      attach.setMimeHeader("KeyA", "ValueA");
      attach.setContentId("1234567");
      logger.info("Content Id :: " + attach.getContentId());
      message.addAttachmentPart(attach);
    }
    messageContext.setMessage(message);
  }
 @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));
   }
 }
  @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());
  }
  private void doFromSoapMessage(Message message, Object sm) {
    SOAPMessage m = (SOAPMessage) sm;
    MessageContentsList list = (MessageContentsList) message.getContent(List.class);
    if (list == null) {
      list = new MessageContentsList();
      message.setContent(List.class, list);
    }
    Object o = m;

    if (StreamSource.class.isAssignableFrom(type)) {
      try {
        try (CachedOutputStream out = new CachedOutputStream()) {
          XMLStreamWriter xsw = StaxUtils.createXMLStreamWriter(out);
          StaxUtils.copy(new DOMSource(m.getSOAPPart()), xsw);
          xsw.close();
          o = new StreamSource(out.getInputStream());
        }
      } catch (Exception e) {
        throw new Fault(e);
      }
    } else if (SAXSource.class.isAssignableFrom(type)) {
      o = new StaxSource(new W3CDOMStreamReader(m.getSOAPPart()));
    } else if (Source.class.isAssignableFrom(type)) {
      o = new DOMSource(m.getSOAPPart());
    }
    list.set(0, o);
  }
  /** @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 #18
0
  public STElement call() throws IOException {
    try {
      soapRequest.saveChanges();
      if (debug) {
        System.out.print("********* REQUEST:");
        Element e = new DOMReader().read(soapRequest.getSOAPPart()).getRootElement();
        writer.write(e);
        System.out.println();
        System.out.println("------------------");
      }

      soapResponse = conn.call(soapRequest, wsdlURL);

      if (debug) {
        System.out.print("********* RESPONSE:");
        Element e = new DOMReader().read(soapResponse.getSOAPPart()).getRootElement();
        writer.write(e);
        System.out.println();
        System.out.println("------------------");
      }

      SOAPPart sp = soapResponse.getSOAPPart();
      SOAPEnvelope env = sp.getEnvelope();
      return new STElement(env.getBody());
    } catch (SOAPException e) {
      e.printStackTrace();
      return null;
    }
  }
  /**
   * @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;
  }
Example #20
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;
  }
 private void transportHeaders(Packet packet, boolean inbound, SOAPMessage msg)
     throws SOAPException {
   Map<String, List<String>> headers = getTransportHeaders(packet, inbound);
   if (headers != null) {
     addSOAPMimeHeaders(msg.getMimeHeaders(), headers);
   }
   if (msg.saveRequired()) msg.saveChanges();
 }
  public DeliverOrderRowsResponse(SOAPMessage soapResponse) throws SOAPException {
    super(soapResponse.getSOAPPart().getEnvelope().getBody().getElementsByTagName("*"));

    if (this.isOrderAccepted()) {
      setDeliverOrderRowsResponseAttributes(
          soapResponse.getSOAPPart().getEnvelope().getBody().getElementsByTagName("*"));
    }
  }
Example #23
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);
  }
Example #24
0
  public void testWriteFault_saaj() throws Exception {
    SOAPMessage soapMessage = writeFault();

    SOAPBody body = soapMessage.getSOAPBody();
    // SOAPFault fault = body.getFault();
    SOAPElement fault = SoapUtil.getElement(body, SOAPConstants.URI_NS_SOAP_ENVELOPE, "Fault");

    testFaultCode(fault);
    testFaultString(fault);
    testDetail(fault);
  }
Example #25
0
  @Override
  public String toString(SOAPMessage soapMessage) throws SOAPException, IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    soapMessage.writeTo(output);

    if (formatter != null) {
      // return formatter.format(output.toString(charset));
      return formatter.format(soapMessage.getSOAPBody().getOwnerDocument());
    }

    return output.toString(charset);
  }
 private void getNonExplicitAttachment(StreamingHandlerState state) throws Exception {
   javax.xml.rpc.handler.soap.SOAPMessageContext smc = state.getMessageContext();
   javax.xml.soap.SOAPMessage message = state.getRequest().getMessage();
   java.util.ArrayList attachments = null;
   for (java.util.Iterator iter = message.getAttachments(); iter.hasNext(); ) {
     if (attachments == null) {
       attachments = new java.util.ArrayList();
     }
     attachments.add(iter.next());
   }
   smc.setProperty(
       com.sun.xml.rpc.server.ServerPropertyConstants.GET_ATTACHMENT_PROPERTY, attachments);
 }
  @Override
  protected boolean handleOutbound(MessageContext msgContext) {

    logger.trace("Handling Outbound Message");

    if (httpHeaderName == null && httpCookieName == null) {
      throw logger.injectedValueMissing("Either httpHeaderName or httpCookieName should be set");
    }

    HttpServletRequest servletRequest = getHttpRequest(msgContext);
    if (servletRequest == null) {
      throw logger.nullValueError("Http request");
    }

    String token = getTokenValue(servletRequest);
    if (token == null) {
      throw logger.nullValueError("Null Token");
    }
    SOAPElement security = null;
    try {
      security = create(token);
    } catch (SOAPException e) {
      logger.jbossWSUnableToCreateBinaryToken(e);
    }
    if (security == null) {
      logger.jbossWSUnableToCreateSecurityToken();
      return true;
    }
    SOAPMessage sm = ((SOAPMessageContext) msgContext).getMessage();
    SOAPEnvelope envelope;
    try {
      envelope = sm.getSOAPPart().getEnvelope();
      SOAPHeader header =
          (SOAPHeader) Util.findElement(envelope, new QName(envelope.getNamespaceURI(), "Header"));
      if (header == null) {
        header =
            (SOAPHeader)
                envelope
                    .getOwnerDocument()
                    .createElementNS(envelope.getNamespaceURI(), envelope.getPrefix() + ":Header");
        envelope.insertBefore(header, envelope.getFirstChild());
      }
      header.addChildElement(security);
    } catch (SOAPException e) {
      logger.jbossWSUnableToCreateBinaryToken(e);
    }
    if (logger.isTraceEnabled()) {
      logger.trace("SOAP Message=" + SOAPUtil.soapMessageAsString(sm));
    }
    return true;
  }
Example #28
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());
  }
Example #29
0
  public static void main(String args[]) throws Exception {
    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Send SOAP Message to SOAP Server
    String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
    SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);

    // print SOAP Response
    System.out.print("Response SOAP Message:");
    soapResponse.writeTo(System.out);

    soapConnection.close();
  }
  public void testCreateDispatchSMWsdl() throws Exception {

    if (ClientServerTestUtil.useLocal()) {
      System.out.println("HTTP Transport Only Exiting");
      return;
    }
    RespectBindingFeature rbf = new RespectBindingFeature(false);
    WebServiceFeature[] wse = new WebServiceFeature[] {rbf};
    Service service = createServiceWithWSDL();
    Dispatch<SOAPMessage> dispatch =
        service.createDispatch(PORT_QNAME, SOAPMessage.class, Service.Mode.MESSAGE, wse);
    SOAPMessage result = dispatch.invoke(getSOAPMessage(makeStreamSource(SMMsg)));

    result.writeTo(System.out);
  }