Namespace(String namespace, String prefix) {
    this.setNamespace(namespace);
    this.setPrefix(prefix);

    SOAPFactory factory = OMAbstractFactory.getSOAP12Factory();
    OMNamespace = factory.createOMNamespace(namespace, prefix);
  }
  private void setFaultCode(
      MessageContext synCtx, SOAPFactory factory, SOAPFault fault, int soapVersion) {

    QName fault_code = null;

    if (faultCodeValue == null && faultCodeExpr == null) {
      handleException("A valid fault code QName value or expression is required", synCtx);
    } else if (faultCodeValue != null) {
      fault_code = faultCodeValue;
    } else {
      String codeStr = faultCodeExpr.stringValueOf(synCtx);
      fault_code = new QName(fault.getNamespace().getNamespaceURI(), codeStr);
    }

    SOAPFaultCode code = factory.createSOAPFaultCode();
    switch (soapVersion) {
      case SOAP11:
        code.setText(fault_code);
        break;
      case SOAP12:
        SOAPFaultValue value = factory.createSOAPFaultValue(code);
        value.setText(fault_code);
        break;
    }
    fault.setCode(code);
  }
  private void setFaultReason(
      MessageContext synCtx, SOAPFactory factory, SOAPFault fault, int soapVersion) {
    String reasonString = null;

    if (faultReasonValue == null && faultReasonExpr == null) {
      handleException("A valid fault reason value or expression is required", synCtx);
    } else if (faultReasonValue != null) {
      reasonString = faultReasonValue;
    } else {
      reasonString = faultReasonExpr.stringValueOf(synCtx);
    }

    SOAPFaultReason reason = factory.createSOAPFaultReason();
    switch (soapVersion) {
      case SOAP11:
        reason.setText(reasonString);
        break;
      case SOAP12:
        SOAPFaultText text = factory.createSOAPFaultText();
        text.setText(reasonString);
        text.setLang("en");
        reason.addSOAPText(text);
        break;
    }
    fault.setReason(reason);
  }
  /**
   * Invokes the bussiness logic invocation on the service implementation class
   *
   * @param msgContext the incoming message context
   * @param newmsgContext the response message context
   * @throws AxisFault on invalid method (wrong signature) or behaviour (return null)
   */
  public void invokeBusinessLogic(MessageContext msgContext, MessageContext newmsgContext)
      throws AxisFault {
    try {

      // get the implementation class for the Web Service
      Object obj = getTheImplementationObject(msgContext);

      // find the WebService method
      Class implClass = obj.getClass();

      AxisOperation opDesc = msgContext.getAxisOperation();
      Method method = findOperation(opDesc, implClass);

      if (method == null) {
        throw new AxisFault(
            Messages.getMessage("methodDoesNotExistInOut", opDesc.getName().toString()));
      }

      OMElement result =
          (OMElement)
              method.invoke(
                  obj, new Object[] {msgContext.getEnvelope().getBody().getFirstElement()});
      SOAPFactory fac = getSOAPFactory(msgContext);
      SOAPEnvelope envelope = fac.getDefaultEnvelope();

      if (result != null) {
        envelope.getBody().addChild(result);
      }

      newmsgContext.setEnvelope(envelope);
    } catch (Exception e) {
      throw AxisFault.makeFault(e);
    }
  }
Example #5
0
  public static String sendSOAP(
      EndpointReference soapEPR, String requestString, String action, String operation)
      throws Exception {

    ServiceClient sender = PmServiceClient.getServiceClient();
    OperationClient operationClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);

    // creating message context
    MessageContext outMsgCtx = new MessageContext();
    // assigning message context's option object into instance variable
    Options opts = outMsgCtx.getOptions();
    // setting properties into option
    log.debug(soapEPR);
    opts.setTo(soapEPR);
    opts.setAction(action);
    opts.setTimeOutInMilliSeconds(180000);

    log.debug(requestString);

    SOAPEnvelope envelope = null;

    try {
      SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
      envelope = fac.getDefaultEnvelope();
      OMNamespace omNs =
          fac.createOMNamespace(
              "http://rpdr.partners.org/", //$NON-NLS-1$
              "rpdr"); //$NON-NLS-1$

      // creating the SOAP payload
      OMElement method = fac.createOMElement(operation, omNs);
      OMElement value = fac.createOMElement("RequestXmlString", omNs); // $NON-NLS-1$
      value.setText(requestString);
      method.addChild(value);
      envelope.getBody().addChild(method);
    } catch (FactoryConfigurationError e) {
      log.error(e.getMessage());
      throw new Exception(e);
    }

    outMsgCtx.setEnvelope(envelope);

    operationClient.addMessageContext(outMsgCtx);
    operationClient.execute(true);

    MessageContext inMsgtCtx = operationClient.getMessageContext("In"); // $NON-NLS-1$
    SOAPEnvelope responseEnv = inMsgtCtx.getEnvelope();

    OMElement soapResponse = responseEnv.getBody().getFirstElement();
    //		System.out.println("Sresponse: "+ soapResponse.toString());
    OMElement soapResult = soapResponse.getFirstElement();
    //		System.out.println("Sresult: "+ soapResult.toString());

    String i2b2Response = soapResult.getText();
    log.debug(i2b2Response);

    return i2b2Response;
  }
Example #6
0
  public static MessageContext sendUsingSwA(String fileName, String targetEPR) throws IOException {

    Options options = new Options();
    options.setTo(new EndpointReference(targetEPR));
    options.setAction("urn:uploadFileUsingSwA");
    options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);

    ServiceClient sender = new ServiceClient();
    sender.setOptions(options);
    OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);

    MessageContext mc = new MessageContext();

    System.out.println("Sending file : " + fileName + " as SwA");
    FileDataSource fileDataSource = new FileDataSource(new File(fileName));
    DataHandler dataHandler = new DataHandler(fileDataSource);
    String attachmentID = mc.addAttachment(dataHandler);

    SOAPFactory factory = OMAbstractFactory.getSOAP11Factory();
    SOAPEnvelope env = factory.getDefaultEnvelope();
    OMNamespace ns = factory.createOMNamespace("http://services.samples/xsd", "m0");
    OMElement payload = factory.createOMElement("uploadFileUsingSwA", ns);
    OMElement request = factory.createOMElement("request", ns);
    OMElement imageId = factory.createOMElement("imageId", ns);
    imageId.setText(attachmentID);
    request.addChild(imageId);
    payload.addChild(request);
    env.getBody().addChild(payload);
    mc.setEnvelope(env);

    mepClient.addMessageContext(mc);
    mepClient.execute(true);
    MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);

    SOAPBody body = response.getEnvelope().getBody();
    String imageContentId =
        body.getFirstChildWithName(
                new QName("http://services.samples/xsd", "uploadFileUsingSwAResponse"))
            .getFirstChildWithName(new QName("http://services.samples/xsd", "response"))
            .getFirstChildWithName(new QName("http://services.samples/xsd", "imageId"))
            .getText();

    Attachments attachment = response.getAttachmentMap();
    dataHandler = attachment.getDataHandler(imageContentId);
    File tempFile = File.createTempFile("swa-", ".gif");
    FileOutputStream fos = new FileOutputStream(tempFile);
    dataHandler.writeTo(fos);
    fos.flush();
    fos.close();

    System.out.println("Saved response to file : " + tempFile.getAbsolutePath());

    return response;
  }
  private SOAPEnvelope buildSoapEnvelope(String clientID, String value) {

    String targetEPR = "http://localhost:9000/soap/Service1";
    String opration = "sampleOperation";

    SOAPFactory soapFactory = OMAbstractFactory.getSOAP12Factory();

    OMNamespace wsaNamespace =
        soapFactory.createOMNamespace("http://www.w3.org/2005/08/addressing", "wsa");

    SOAPEnvelope envelope = soapFactory.createSOAPEnvelope();

    SOAPHeader header = soapFactory.createSOAPHeader();
    envelope.addChild(header);

    OMNamespace synNamespace =
        soapFactory.createOMNamespace("http://ws.apache.org/ns/synapse", "syn");
    OMElement clientIDElement = soapFactory.createOMElement("ClientID", synNamespace);
    clientIDElement.setText(clientID);
    header.addChild(clientIDElement);

    SOAPBody body = soapFactory.createSOAPBody();
    envelope.addChild(body);

    OMElement valueElement = soapFactory.createOMElement("Value", null);
    valueElement.setText(value);
    body.addChild(valueElement);

    return envelope;
  }
 private void setFaultRole(SOAPFactory factory, SOAPFault fault) {
   if (faultRole != null) {
     SOAPFaultRole soapFaultRole = factory.createSOAPFaultRole();
     soapFaultRole.setRoleValue(faultRole.toString());
     fault.setRole(soapFaultRole);
   }
 }
 private void setFaultNode(SOAPFactory factory, SOAPFault fault) {
   if (faultNode != null) {
     SOAPFaultNode soapfaultNode = factory.createSOAPFaultNode();
     soapfaultNode.setNodeValue(faultNode.toString());
     fault.setNode(soapfaultNode);
   }
 }
  public void createSoapBody(
      org.apache.axiom.soap.SOAPBody sb,
      SOAPBody soapBody,
      Message msgDef,
      Element message,
      String rpcWrapper)
      throws AxisFault {
    OMElement partHolder =
        isRPC
            ? soapFactory.createOMElement(
                new QName(soapBody.getNamespaceURI(), rpcWrapper, "odens"), sb)
            : sb;
    List<Part> parts = msgDef.getOrderedParts(soapBody.getParts());

    for (Part part : parts) {
      Element srcPartEl = DOMUtils.findChildByName(message, new QName(null, part.getName()));
      if (srcPartEl == null) {
        throw new AxisFault("Missing required part in ODE Message");
      }

      OMElement omPart = OMUtils.toOM(srcPartEl, soapFactory);
      if (isRPC) {
        partHolder.addChild(omPart);
      } else {
        for (Iterator<OMNode> i = omPart.getChildren(); i.hasNext(); ) {
          partHolder.addChild(i.next());
        }
      }
    }
  }
 public String toString() {
   StringBuilder builder = new StringBuilder("AxiomSoapMessageFactory[");
   if (soapFactory.getSOAPVersion() == SOAP11Version.getSingleton()) {
     builder.append("SOAP 1.1");
   } else if (soapFactory.getSOAPVersion() == SOAP12Version.getSingleton()) {
     builder.append("SOAP 1.2");
   }
   builder.append(',');
   if (payloadCaching) {
     builder.append("PayloadCaching enabled");
   } else {
     builder.append("PayloadCaching disabled");
   }
   builder.append(']');
   return builder.toString();
 }
Example #12
0
  private void createAndSendSOAPResponse(
      Map<String, Object> serviceResults, String serviceName, HttpServletResponse response)
      throws EventHandlerException {
    try {
      // setup the response
      Debug.logVerbose("[EventHandler] : Setting up response message", module);
      String xmlResults = SoapSerializer.serialize(serviceResults);
      // Debug.logInfo("xmlResults ==================" + xmlResults, module);
      XMLStreamReader reader =
          XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(xmlResults));
      StAXOMBuilder resultsBuilder = new StAXOMBuilder(reader);
      OMElement resultSer = resultsBuilder.getDocumentElement();

      // create the response soap
      SOAPFactory factory = OMAbstractFactory.getSOAP11Factory();
      SOAPEnvelope resEnv = factory.createSOAPEnvelope();
      SOAPBody resBody = factory.createSOAPBody();
      OMElement resService = factory.createOMElement(new QName(serviceName + "Response"));
      resService.addChild(resultSer.getFirstElement());
      resBody.addChild(resService);
      resEnv.addChild(resBody);

      // The declareDefaultNamespace method doesn't work see
      // (https://issues.apache.org/jira/browse/AXIS2-3156)
      // so the following doesn't work:
      // resService.declareDefaultNamespace(ModelService.TNS);
      // instead, create the xmlns attribute directly:
      OMAttribute defaultNS = factory.createOMAttribute("xmlns", null, ModelService.TNS);
      resService.addAttribute(defaultNS);

      // log the response message
      if (Debug.verboseOn()) {
        try {
          Debug.logInfo("Response Message:\n" + resEnv + "\n", module);
        } catch (Throwable t) {
        }
      }

      resEnv.serialize(response.getOutputStream());
      response.getOutputStream().flush();
    } catch (Exception e) {
      Debug.logError(e, module);
      throw new EventHandlerException(e.getMessage(), e);
    }
  }
  /**
   * Adding the attachment ids iteratively to the SOAP Header
   *
   * @param header Header Element where the child elements going to be included
   * @param attachmentIDList attachment ids
   */
  private void addAttachmentIDHeader(SOAPHeader header, List<Long> attachmentIDList) {
    final String namespace = Constants.ATTACHMENT_ID_NAMESPACE;
    final String namespacePrefix = Constants.ATTACHMENT_ID_NAMESPACE_PREFIX;
    final String parentElementName = Constants.ATTACHMENT_ID_PARENT_ELEMENT_NAME;
    final String childElementName = Constants.ATTACHMENT_ID_CHILD_ELEMENT_NAME;

    OMNamespace omNs = soapFactory.createOMNamespace(namespace, namespacePrefix);
    OMElement headerElement = soapFactory.createOMElement(parentElementName, omNs);

    for (Long id : attachmentIDList) {
      OMElement idElement = soapFactory.createOMElement(childElementName, omNs);
      idElement.setText(String.valueOf(id));

      headerElement.addChild(idElement);
    }

    header.addChild(headerElement);
  }
Example #14
0
 public OMElement processDocument(InputStream inputStream, String s, MessageContext messageContext)
     throws AxisFault {
   messageContext.setProperty(JsonConstant.IS_JSON_STREAM, true);
   JsonReader jsonReader;
   String charSetEncoding = null;
   try {
     charSetEncoding =
         (String) messageContext.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING);
     jsonReader = new JsonReader(new InputStreamReader(inputStream, charSetEncoding));
     GsonXMLStreamReader gsonXMLStreamReader = new GsonXMLStreamReader(jsonReader);
     messageContext.setProperty(JsonConstant.GSON_XML_STREAM_READER, gsonXMLStreamReader);
     // dummy envelop
     SOAPFactory soapFactory = OMAbstractFactory.getSOAP11Factory();
     return soapFactory.getDefaultEnvelope();
   } catch (UnsupportedEncodingException e) {
     throw new AxisFault(
         charSetEncoding + " encoding is may not supported by json inputStream ", e);
   }
 }
 public void addOverridingHumanTaskAttributes(MessageContext msgCtx, boolean isSkipable) {
   SOAPHeader header = msgCtx.getEnvelope().getHeader();
   OMNamespace omNs =
       soapFactory.createOMNamespace(
           BPEL4PeopleConstants.HT_CONTEXT_NAMESPACE,
           BPEL4PeopleConstants.HT_CONTEXT_DEFAULT_PREFIX);
   OMElement contextRequest =
       header.getFirstChildWithName(
           new QName(
               BPEL4PeopleConstants.HT_CONTEXT_NAMESPACE,
               BPEL4PeopleConstants.HT_CONTEXT_REQUEST));
   // If context element is not exist create new one.
   if (contextRequest == null) {
     contextRequest = soapFactory.createOMElement(BPEL4PeopleConstants.HT_CONTEXT_REQUEST, omNs);
   }
   OMElement isSkipableElement =
       soapFactory.createOMElement(BPEL4PeopleConstants.HT_CONTEXT_IS_SKIPABLE, omNs);
   isSkipableElement.setText(Boolean.toString(isSkipable));
   contextRequest.addChild(isSkipableElement);
   header.addChild(contextRequest);
 }
  public void createSoapRequest(MessageContext msgCtx, Element message, Operation op)
      throws AxisFault {
    if (op == null) {
      throw new NullPointerException("Null operation");
    }
    // The message can be null if the input message has no part
    if (op.getInput().getMessage().getParts().size() > 0 && message == null) {
      throw new NullPointerException("Null message.");
    }
    if (msgCtx == null) {
      throw new NullPointerException("Null msgCtx");
    }

    BindingOperation bop = binding.getBindingOperation(op.getName(), null, null);

    if (bop == null) {
      throw new OdeFault("BindingOperation not found.");
    }

    BindingInput bi = bop.getBindingInput();
    if (bi == null) {
      throw new OdeFault("BindingInput not found.");
    }

    SOAPEnvelope soapEnv = msgCtx.getEnvelope();
    if (soapEnv == null) {
      soapEnv = soapFactory.getDefaultEnvelope();
      msgCtx.setEnvelope(soapEnv);
    }

    //        createSoapHeaders(soapEnv, getSOAPHeaders(bi), op.getInput().getMessage(), message);

    SOAPBody soapBody = getSOAPBody(bi);
    if (soapBody != null) {
      org.apache.axiom.soap.SOAPBody sb =
          soapEnv.getBody() == null ? soapFactory.createSOAPBody(soapEnv) : soapEnv.getBody();
      createSoapBody(sb, soapBody, op.getInput().getMessage(), message, op.getName());
    }
  }
 private void setFaultDetail(MessageContext synCtx, SOAPFactory factory, SOAPFault fault) {
   if (faultDetail != null) {
     SOAPFaultDetail soapFaultDetail = factory.createSOAPFaultDetail();
     soapFaultDetail.setText(faultDetail);
     fault.setDetail(soapFaultDetail);
   } else if (faultDetailExpr != null) {
     SOAPFaultDetail soapFaultDetail = factory.createSOAPFaultDetail();
     Object result = null;
     try {
       result = faultDetailExpr.evaluate(synCtx);
     } catch (JaxenException e) {
       handleException(
           "Evaluation of the XPath expression " + this.toString() + " resulted in an error", e);
     }
     if (result instanceof List) {
       List list = (List) result;
       for (Object obj : list) {
         if (obj instanceof OMNode) {
           soapFaultDetail.addChild((OMNode) obj);
         }
       }
     } else {
       soapFaultDetail.setText(faultDetailExpr.stringValueOf(synCtx));
     }
     fault.setDetail(soapFaultDetail);
   } else if (!faultDetailElements.isEmpty()) {
     SOAPFaultDetail soapFaultDetail = factory.createSOAPFaultDetail();
     for (OMElement faultDetailElement : faultDetailElements) {
       soapFaultDetail.addChild(faultDetailElement.cloneOMElement());
     }
     fault.setDetail(soapFaultDetail);
   } else if (fault.getDetail() != null) {
     // work around for a rampart issue in the following thread
     // http://www.nabble.com/Access-to-validation-error-message-tf4498668.html#a13284520
     fault.getDetail().detach();
   }
 }
  public static org.apache.axis2.context.MessageContext attachMessage(
      String jsonMessage, org.apache.axis2.context.MessageContext axis2Ctx) {
    if (jsonMessage == null) {
      log.error("Cannot attach null JSON string.");
      return null;
    }

    AxisConfiguration axisConfig = axis2Ctx.getConfigurationContext().getAxisConfiguration();
    if (axisConfig == null) {
      log.warn("Cannot create AxisConfiguration. AxisConfiguration is null.");
      return null;
    }

    try {
      SOAPFactory soapFactory = new SOAP12Factory();
      SOAPEnvelope envelope = soapFactory.createSOAPEnvelope();
      envelope.addChild(JsonUtil.newJsonPayload(axis2Ctx, jsonMessage, true, true));
      axis2Ctx.setEnvelope(envelope);
      return axis2Ctx;
    } catch (Exception e) {
      log.error("Cannot attach message to Message Context. Error: " + e.getMessage(), e);
      return null;
    }
  }
  public static void testConnect(
      String strOperation, String strParamName, AbstractConnector connector) throws AxisFault {

    org.apache.axis2.context.MessageContext axis2Ctx =
        new org.apache.axis2.context.MessageContext();
    SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
    org.apache.axiom.soap.SOAPEnvelope envelope = fac.getDefaultEnvelope();
    axis2Ctx.setEnvelope(envelope);
    Collection<String> collection = new java.util.ArrayList<String>();
    collection.add(strParamName);
    testCtx.setProperty(
        TEST_TEMPLATE + ":" + strParamName,
        new Value(
            "<sfdc:sObjects xmlns:sfdc='sfdc' type='Account'><sfdc:sObject><sfdc:Name>name01</sfdc:Name></sfdc:sObject></sfdc:sObjects>"));
    TemplateContext context = new TemplateContext(TEST_TEMPLATE, collection);
    Stack<TemplateContext> stack = new Stack<TemplateContext>();
    stack.add(context);
    context.setupParams(testCtx);

    testCtx.setProperty(SynapseConstants.SYNAPSE__FUNCTION__STACK, stack);
    try {
      connector.connect(testCtx);
    } catch (Exception e) {
      assertTrue(false);
    }

    Iterator<OMElement> iIteratorElements =
        testCtx.getEnvelope().getBody().getChildrenWithLocalName(strOperation);
    OMElement element = iIteratorElements.next();
    iIteratorElements = element.getChildren();
    if (iIteratorElements.hasNext()) {
      assertTrue(true);
    } else {
      assertTrue(false);
    }
  }
  private org.apache.axiom.soap.SOAPEnvelope toEnvelope(
      org.apache.axiom.soap.SOAPFactory factory,
      com.pa.GetEmp param,
      boolean optimizeContent,
      javax.xml.namespace.QName methodQName)
      throws org.apache.axis2.AxisFault {

    try {

      org.apache.axiom.soap.SOAPEnvelope emptyEnvelope = factory.getDefaultEnvelope();
      emptyEnvelope.getBody().addChild(param.getOMElement(com.pa.GetEmp.MY_QNAME, factory));
      return emptyEnvelope;
    } catch (org.apache.axis2.databinding.ADBException e) {
      throw org.apache.axis2.AxisFault.makeFault(e);
    }
  }
  private org.apache.axiom.soap.SOAPEnvelope toEnvelope(
      org.apache.axiom.soap.SOAPFactory factory,
      org.example.www.site.GetSiteResponse param,
      boolean optimizeContent)
      throws org.apache.axis2.AxisFault {
    try {
      org.apache.axiom.soap.SOAPEnvelope emptyEnvelope = factory.getDefaultEnvelope();

      emptyEnvelope
          .getBody()
          .addChild(param.getOMElement(org.example.www.site.GetSiteResponse.MY_QNAME, factory));

      return emptyEnvelope;
    } catch (org.apache.axis2.databinding.ADBException e) {
      throw org.apache.axis2.AxisFault.makeFault(e);
    }
  }
  private OMElement createMultipleQuoteRequestBody(String symbol, int iterations) {
    SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
    OMNamespace omNs = fac.createOMNamespace("http://services.samples", "ns");
    OMElement method1 = fac.createOMElement("getQuotes", omNs);
    OMElement method2 = fac.createOMElement("getQuote", omNs);

    for (int i = 0; i < iterations; i++) {
      OMElement value1 = fac.createOMElement("request", omNs);
      OMElement value2 = fac.createOMElement("symbol", omNs);
      value2.addChild(fac.createOMText(value1, symbol));
      value1.addChild(value2);
      method2.addChild(value1);
      method1.addChild(method2);
    }
    return method1;
  }
  public static void transferFile(File file, String destinationFile) throws Exception {

    Options options = new Options();
    options.setTo(targetEPR);
    options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);
    options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    // Increase the time out when sending large attachments
    options.setTimeOutInMilliSeconds(10000);
    options.setTo(targetEPR);
    options.setAction("urn:uploadFile");

    // assume the use runs this sample at
    // <axis2home>/samples/soapwithattachments/ dir
    ConfigurationContext configContext =
        ConfigurationContextFactory.createConfigurationContextFromFileSystem(
            "../../repository", null);

    ServiceClient sender = new ServiceClient(configContext, null);
    sender.setOptions(options);
    OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);

    MessageContext mc = new MessageContext();
    FileDataSource fileDataSource = new FileDataSource(file);

    // Create a dataHandler using the fileDataSource. Any implementation of
    // javax.activation.DataSource interface can fit here.
    DataHandler dataHandler = new DataHandler(fileDataSource);
    String attachmentID = mc.addAttachment(dataHandler);

    SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
    SOAPEnvelope env = fac.getDefaultEnvelope();
    OMNamespace omNs = fac.createOMNamespace("http://service.soapwithattachments.sample", "swa");
    OMElement uploadFile = fac.createOMElement("uploadFile", omNs);
    OMElement nameEle = fac.createOMElement("name", omNs);
    nameEle.setText(destinationFile);
    OMElement idEle = fac.createOMElement("attchmentID", omNs);
    idEle.setText(attachmentID);
    uploadFile.addChild(nameEle);
    uploadFile.addChild(idEle);
    env.getBody().addChild(uploadFile);
    mc.setEnvelope(env);

    mepClient.addMessageContext(mc);
    mepClient.execute(true);
    MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
    SOAPBody body = response.getEnvelope().getBody();
    OMElement element =
        body.getFirstElement()
            .getFirstChildWithName(
                new QName("http://service.soapwithattachments.sample", "return"));
    System.out.println(element.getText());
  }
Example #24
0
  private org.apache.axiom.soap.SOAPEnvelope toEnvelope(
      final org.apache.axiom.soap.SOAPFactory factory,
      final CadConsultaCadastro2Stub.NfeDadosMsg param,
      final boolean optimizeContent,
      final javax.xml.namespace.QName methodQName)
      throws org.apache.axis2.AxisFault {

    try {

      final org.apache.axiom.soap.SOAPEnvelope emptyEnvelope = factory.getDefaultEnvelope();
      emptyEnvelope
          .getBody()
          .addChild(param.getOMElement(CadConsultaCadastro2Stub.NfeDadosMsg.MY_QNAME, factory));
      return emptyEnvelope;
    } catch (final org.apache.axis2.databinding.ADBException e) {
      throw org.apache.axis2.AxisFault.makeFault(e);
    }
  }
  private org.apache.axiom.soap.SOAPEnvelope toEnvelope(
      org.apache.axiom.soap.SOAPFactory factory,
      gsn.webservice.standard.RegisterQueryResponse param,
      boolean optimizeContent)
      throws org.apache.axis2.AxisFault {
    try {
      org.apache.axiom.soap.SOAPEnvelope emptyEnvelope = factory.getDefaultEnvelope();

      emptyEnvelope
          .getBody()
          .addChild(
              param.getOMElement(gsn.webservice.standard.RegisterQueryResponse.MY_QNAME, factory));

      return emptyEnvelope;
    } catch (org.apache.axis2.databinding.ADBException e) {
      throw org.apache.axis2.AxisFault.makeFault(e);
    }
  }
  private org.apache.axiom.soap.SOAPEnvelope toEnvelope(
      org.apache.axiom.soap.SOAPFactory factory,
      org.wso2.carbon.billing.mgt.services.AddPaymentResponse param,
      boolean optimizeContent,
      javax.xml.namespace.QName methodQName)
      throws org.apache.axis2.AxisFault {
    try {
      org.apache.axiom.soap.SOAPEnvelope emptyEnvelope = factory.getDefaultEnvelope();

      emptyEnvelope
          .getBody()
          .addChild(
              param.getOMElement(
                  org.wso2.carbon.billing.mgt.services.AddPaymentResponse.MY_QNAME, factory));

      return emptyEnvelope;
    } catch (org.apache.axis2.databinding.ADBException e) {
      throw org.apache.axis2.AxisFault.makeFault(e);
    }
  }
  private OMElement createRequestPayload() {
    SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
    OMNamespace omNs = fac.createOMNamespace("http://services.samples", "ns");
    OMElement top = fac.createOMElement("getQuotes", omNs);

    for (int i = 0; i < 3; i++) {
      OMElement method = fac.createOMElement("getQuote", omNs);
      OMElement value1 = fac.createOMElement("request", omNs);
      OMElement value2 = fac.createOMElement("symbol", omNs);
      value2.addChild(fac.createOMText(value1, "WSO2"));
      value1.addChild(value2);
      method.addChild(value1);
      top.addChild(method);
    }

    for (int i = 0; i < 3; i++) {
      OMElement method = fac.createOMElement("dummy", omNs);
      OMElement value1 = fac.createOMElement("request", omNs);
      OMElement value2 = fac.createOMElement("symbol", omNs);
      value2.addChild(fac.createOMText(value1, "WSO2"));
      value1.addChild(value2);
      method.addChild(value1);
      top.addChild(method);
    }

    return top;
  }
  /**
   * Based on the Axis2 client code. Sends the Axis2 Message context out and returns the Axis2
   * message context for the response.
   *
   * <p>Here Synapse works as a Client to the service. It would expect 200 ok, 202 ok and 500
   * internal server error as possible responses.
   *
   * @param endpoint the endpoint being sent to, maybe null
   * @param synapseOutMessageContext the outgoing synapse message
   * @throws AxisFault on errors
   */
  public static void send(
      EndpointDefinition endpoint, org.apache.synapse.MessageContext synapseOutMessageContext)
      throws AxisFault {

    boolean separateListener = false;
    boolean wsSecurityEnabled = false;
    String wsSecPolicyKey = null;
    String inboundWsSecPolicyKey = null;
    String outboundWsSecPolicyKey = null;
    boolean wsRMEnabled = false;
    String wsRMPolicyKey = null;
    boolean wsAddressingEnabled = false;
    String wsAddressingVersion = null;

    if (endpoint != null) {
      separateListener = endpoint.isUseSeparateListener();
      wsSecurityEnabled = endpoint.isSecurityOn();
      wsSecPolicyKey = endpoint.getWsSecPolicyKey();
      inboundWsSecPolicyKey = endpoint.getInboundWsSecPolicyKey();
      outboundWsSecPolicyKey = endpoint.getOutboundWsSecPolicyKey();
      wsRMEnabled = endpoint.isReliableMessagingOn();
      wsRMPolicyKey = endpoint.getWsRMPolicyKey();
      wsAddressingEnabled = endpoint.isAddressingOn() || wsRMEnabled;
      wsAddressingVersion = endpoint.getAddressingVersion();
    }

    if (log.isDebugEnabled()) {
      String to;
      if (endpoint != null && endpoint.getAddress() != null) {
        to = endpoint.getAddress(synapseOutMessageContext);
      } else {
        to = synapseOutMessageContext.getTo().toString();
      }

      log.debug(
          "Sending [add = "
              + wsAddressingEnabled
              + "] [sec = "
              + wsSecurityEnabled
              + "] [rm = "
              + wsRMEnabled
              + (endpoint != null
                  ? "] [mtom = "
                      + endpoint.isUseMTOM()
                      + "] [swa = "
                      + endpoint.isUseSwa()
                      + "] [format = "
                      + endpoint.getFormat()
                      + "] [force soap11="
                      + endpoint.isForceSOAP11()
                      + "] [force soap12="
                      + endpoint.isForceSOAP12()
                      + "] [pox="
                      + endpoint.isForcePOX()
                      + "] [get="
                      + endpoint.isForceGET()
                      + "] [encoding="
                      + endpoint.getCharSetEncoding()
                  : "")
              + "] [to="
              + to
              + "]");
    }

    // save the original message context without altering it, so we can tie the response
    MessageContext originalInMsgCtx =
        ((Axis2MessageContext) synapseOutMessageContext).getAxis2MessageContext();

    // TODO Temp hack: ESB removes the session id from request in a random manner.
    Map headers = (Map) originalInMsgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
    String session = (String) synapseOutMessageContext.getProperty("LB_COOKIE_HEADER");
    if (session != null) {
      headers.put("Cookie", session);
    }

    // create a new MessageContext to be sent out as this should not corrupt the original
    // we need to create the response to the original message later on
    String preserveAddressingProperty =
        (String) synapseOutMessageContext.getProperty(SynapseConstants.PRESERVE_WS_ADDRESSING);
    MessageContext axisOutMsgCtx = cloneForSend(originalInMsgCtx, preserveAddressingProperty);

    if (log.isDebugEnabled()) {
      log.debug(
          "Message [Original Request Message ID : "
              + synapseOutMessageContext.getMessageID()
              + "]"
              + " [New Cloned Request Message ID : "
              + axisOutMsgCtx.getMessageID()
              + "]");
    }
    // set all the details of the endpoint only to the cloned message context
    // so that we can use the original message context for resending through different endpoints
    if (endpoint != null) {

      if (SynapseConstants.FORMAT_POX.equals(endpoint.getFormat())) {
        axisOutMsgCtx.setDoingREST(true);
        axisOutMsgCtx.setProperty(
            org.apache.axis2.Constants.Configuration.MESSAGE_TYPE,
            org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);
        axisOutMsgCtx.setProperty(
            Constants.Configuration.CONTENT_TYPE,
            org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);

        Object o =
            axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        Map _headers = (Map) o;
        if (_headers != null) {
          _headers.remove(HTTP.CONTENT_TYPE);
          _headers.put(
              HTTP.CONTENT_TYPE,
              org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);
        }

      } else if (SynapseConstants.FORMAT_GET.equals(endpoint.getFormat())) {
        axisOutMsgCtx.setDoingREST(true);
        axisOutMsgCtx.setProperty(
            Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_GET);
        axisOutMsgCtx.setProperty(
            org.apache.axis2.Constants.Configuration.MESSAGE_TYPE,
            org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_X_WWW_FORM);

      } else if (SynapseConstants.FORMAT_SOAP11.equals(endpoint.getFormat())) {
        axisOutMsgCtx.setDoingREST(false);
        axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
        // We need to set this explicitly here in case the request was not a POST
        axisOutMsgCtx.setProperty(
            Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_POST);
        if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) {
          axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction());
        }
        if (!axisOutMsgCtx.isSOAP11()) {
          SOAPUtils.convertSOAP12toSOAP11(axisOutMsgCtx);
        }
        Object o =
            axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        Map _headers = (Map) o;
        if (_headers != null) {
          _headers.remove(HTTP.CONTENT_TYPE);
          _headers.put(
              HTTP.CONTENT_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_TEXT_XML);
        }

      } else if (SynapseConstants.FORMAT_SOAP12.equals(endpoint.getFormat())) {
        axisOutMsgCtx.setDoingREST(false);
        axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
        // We need to set this explicitly here in case the request was not a POST
        axisOutMsgCtx.setProperty(
            Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_POST);
        if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) {
          axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction());
        }
        if (axisOutMsgCtx.isSOAP11()) {
          SOAPUtils.convertSOAP11toSOAP12(axisOutMsgCtx);
        }
        Object o =
            axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        Map _headers = (Map) o;
        if (_headers != null) {
          _headers.remove(HTTP.CONTENT_TYPE);
          _headers.put(
              HTTP.CONTENT_TYPE,
              org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML);
        }

      } else if (SynapseConstants.FORMAT_REST.equals(endpoint.getFormat())) {
        /*format=rest is kept only backword compatibility. We no longer needed that.*/
        /* Remove Message Type  for GET and DELETE Request */
        if (originalInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD) != null) {
          if (originalInMsgCtx
                  .getProperty(Constants.Configuration.HTTP_METHOD)
                  .toString()
                  .equals(Constants.Configuration.HTTP_METHOD_GET)
              || originalInMsgCtx
                  .getProperty(Constants.Configuration.HTTP_METHOD)
                  .toString()
                  .equals(Constants.Configuration.HTTP_METHOD_DELETE)) {
            axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
          }
        }
        axisOutMsgCtx.setDoingREST(true);
      } else {
        processWSDL2RESTRequestMessageType(originalInMsgCtx, axisOutMsgCtx);
      }

      if (endpoint.isUseMTOM()) {
        axisOutMsgCtx.setDoingMTOM(true);
        // fix / workaround for AXIS2-1798
        axisOutMsgCtx.setProperty(
            org.apache.axis2.Constants.Configuration.ENABLE_MTOM,
            org.apache.axis2.Constants.VALUE_TRUE);
        axisOutMsgCtx.setDoingMTOM(true);

      } else if (endpoint.isUseSwa()) {
        axisOutMsgCtx.setDoingSwA(true);
        // fix / workaround for AXIS2-1798
        axisOutMsgCtx.setProperty(
            org.apache.axis2.Constants.Configuration.ENABLE_SWA,
            org.apache.axis2.Constants.VALUE_TRUE);
        axisOutMsgCtx.setDoingSwA(true);
      }

      if (endpoint.getCharSetEncoding() != null) {
        axisOutMsgCtx.setProperty(
            Constants.Configuration.CHARACTER_SET_ENCODING, endpoint.getCharSetEncoding());
        // Need to Clean this up. TargetRequest line 176 contains a code block which over writes the
        // Content-Type returned by the message formatter with the Content-Type in
        // TRANSPORT_HEADERS. Because of that, even when
        // the Character set encoding is set by the message formatter, it will be replaced by the
        // Content-Type header in TRANSPORT_HEADERS.
        // So Im setting a property to check in TargetRequest before over writing the header.
        axisOutMsgCtx.setProperty("EndpointCharEncodingSet", "true");
      }

      // HTTP Endpoint : use the specified HTTP method and remove REST_URL_POSTFIX, it's not
      // supported in HTTP Endpoint
      if (endpoint.isHTTPEndpoint()) {
        axisOutMsgCtx.setProperty(
            Constants.Configuration.HTTP_METHOD,
            synapseOutMessageContext.getProperty(Constants.Configuration.HTTP_METHOD));
        axisOutMsgCtx.removeProperty(NhttpConstants.REST_URL_POSTFIX);
      }

      // add rest request' suffix URI
      String restSuffix = (String) axisOutMsgCtx.getProperty(NhttpConstants.REST_URL_POSTFIX);
      boolean isRest = SynapseConstants.FORMAT_REST.equals(endpoint.getFormat());

      if (!isRest && !endpoint.isForceSOAP11() && !endpoint.isForceSOAP12()) {
        isRest = isRequestRest(originalInMsgCtx);
      }

      if (endpoint.getAddress() != null) {
        String address = endpoint.getAddress(synapseOutMessageContext);
        if (isRest && restSuffix != null && !"".equals(restSuffix)) {

          String url;
          if (!address.endsWith("/")
              && !restSuffix.startsWith("/")
              && !restSuffix.startsWith("?")) {
            url = address + "/" + restSuffix;
          } else if (address.endsWith("/") && restSuffix.startsWith("/")) {
            url = address + restSuffix.substring(1);
          } else if (address.endsWith("/") && restSuffix.startsWith("?")) {
            url = address.substring(0, address.length() - 1) + restSuffix;
          } else {
            url = address + restSuffix;
          }
          axisOutMsgCtx.setTo(new EndpointReference(url));

        } else {
          axisOutMsgCtx.setTo(new EndpointReference(address));
        }
        axisOutMsgCtx.setProperty(NhttpConstants.ENDPOINT_PREFIX, address);
        synapseOutMessageContext.setProperty(SynapseConstants.ENDPOINT_PREFIX, address);
      } else {
        // Supporting RESTful invocation
        if (isRest && restSuffix != null && !"".equals(restSuffix)) {
          EndpointReference epr = axisOutMsgCtx.getTo();
          if (epr != null) {
            String address = epr.getAddress();
            String url;
            if (!address.endsWith("/")
                && !restSuffix.startsWith("/")
                && !restSuffix.startsWith("?")) {
              url = address + "/" + restSuffix;
            } else {
              url = address + restSuffix;
            }
            axisOutMsgCtx.setTo(new EndpointReference(url));
          }
        }
      }

      if (endpoint.isUseSeparateListener()) {
        axisOutMsgCtx.getOptions().setUseSeparateListener(true);
      }
    } else {
      processWSDL2RESTRequestMessageType(originalInMsgCtx, axisOutMsgCtx);
    }

    // only put whttp:location for the REST (GET) requests, otherwise causes issues for POX messages
    if (axisOutMsgCtx.isDoingREST()
        && HTTPConstants.MEDIA_TYPE_X_WWW_FORM.equals(
            axisOutMsgCtx.getProperty(Constants.Configuration.MESSAGE_TYPE))) {
      if (axisOutMsgCtx.getProperty(WSDL2Constants.ATTR_WHTTP_LOCATION) == null
          && axisOutMsgCtx.getEnvelope().getBody().getFirstElement() != null) {
        axisOutMsgCtx.setProperty(
            WSDL2Constants.ATTR_WHTTP_LOCATION,
            axisOutMsgCtx.getEnvelope().getBody().getFirstElement().getQName().getLocalPart());
      }
    }

    if (wsAddressingEnabled) {

      if (wsAddressingVersion != null
          && SynapseConstants.ADDRESSING_VERSION_SUBMISSION.equals(wsAddressingVersion)) {

        axisOutMsgCtx.setProperty(
            AddressingConstants.WS_ADDRESSING_VERSION,
            AddressingConstants.Submission.WSA_NAMESPACE);

      } else if (wsAddressingVersion != null
          && SynapseConstants.ADDRESSING_VERSION_FINAL.equals(wsAddressingVersion)) {

        axisOutMsgCtx.setProperty(
            AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Final.WSA_NAMESPACE);
      }

      axisOutMsgCtx.setProperty(
          AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.FALSE);
    } else {
      axisOutMsgCtx.setProperty(
          AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE);
    }

    // remove the headers if we don't need to preserve them.
    // determine weather we need to preserve the processed headers
    String preserveHeaderProperty =
        (String) synapseOutMessageContext.getProperty(SynapseConstants.PRESERVE_PROCESSED_HEADERS);
    if (preserveHeaderProperty == null || !Boolean.parseBoolean(preserveHeaderProperty)) {
      // default behaviour is to remove the headers
      MessageHelper.removeProcessedHeaders(
          axisOutMsgCtx,
          (preserveAddressingProperty != null && Boolean.parseBoolean(preserveAddressingProperty)));
    }

    ConfigurationContext axisCfgCtx = axisOutMsgCtx.getConfigurationContext();
    AxisConfiguration axisCfg = axisCfgCtx.getAxisConfiguration();

    AxisService anoymousService =
        AnonymousServiceFactory.getAnonymousService(
            synapseOutMessageContext.getConfiguration(),
            axisCfg,
            wsAddressingEnabled,
            wsRMEnabled,
            wsSecurityEnabled);
    // mark the anon services created to be used in the client side of synapse as hidden
    // from the server side of synapse point of view
    anoymousService.getParent().addParameter(SynapseConstants.HIDDEN_SERVICE_PARAM, "true");
    ServiceGroupContext sgc =
        new ServiceGroupContext(axisCfgCtx, (AxisServiceGroup) anoymousService.getParent());
    ServiceContext serviceCtx = sgc.getServiceContext(anoymousService);

    boolean outOnlyMessage =
        "true".equals(synapseOutMessageContext.getProperty(SynapseConstants.OUT_ONLY));

    // get a reference to the DYNAMIC operation of the Anonymous Axis2 service
    AxisOperation axisAnonymousOperation =
        anoymousService.getOperation(
            outOnlyMessage
                ? new QName(AnonymousServiceFactory.OUT_ONLY_OPERATION)
                : new QName(AnonymousServiceFactory.OUT_IN_OPERATION));

    Options clientOptions = MessageHelper.cloneOptions(originalInMsgCtx.getOptions());
    clientOptions.setUseSeparateListener(separateListener);
    // if RM is requested,
    if (wsRMEnabled) {
      // if a WS-RM policy is specified, use it
      if (wsRMPolicyKey != null) {
        Object property = synapseOutMessageContext.getEntry(wsRMPolicyKey);
        if (property instanceof OMElement) {
          OMElement policyOMElement = (OMElement) property;
          RMAssertionBuilder builder = new RMAssertionBuilder();
          SandeshaPolicyBean sandeshaPolicyBean =
              (SandeshaPolicyBean) builder.build(policyOMElement, null);
          Parameter policyParam =
              new Parameter(Sandesha2Constants.SANDESHA_PROPERTY_BEAN, sandeshaPolicyBean);
          anoymousService.addParameter(policyParam);
        }
      }
    }

    // if security is enabled,
    if (wsSecurityEnabled) {
      // if a WS-Sec policy is specified, use it
      if (wsSecPolicyKey != null) {
        clientOptions.setProperty(
            SynapseConstants.RAMPART_POLICY,
            MessageHelper.getPolicy(synapseOutMessageContext, wsSecPolicyKey));
      } else {
        if (inboundWsSecPolicyKey != null) {
          clientOptions.setProperty(
              SynapseConstants.RAMPART_IN_POLICY,
              MessageHelper.getPolicy(synapseOutMessageContext, inboundWsSecPolicyKey));
        }
        if (outboundWsSecPolicyKey != null) {
          clientOptions.setProperty(
              SynapseConstants.RAMPART_OUT_POLICY,
              MessageHelper.getPolicy(synapseOutMessageContext, outboundWsSecPolicyKey));
        }
      }
      // temporary workaround for https://issues.apache.org/jira/browse/WSCOMMONS-197
      if (axisOutMsgCtx.getEnvelope().getHeader() == null) {
        SOAPFactory fac =
            axisOutMsgCtx.isSOAP11()
                ? OMAbstractFactory.getSOAP11Factory()
                : OMAbstractFactory.getSOAP12Factory();
        fac.createSOAPHeader(axisOutMsgCtx.getEnvelope());
      }
    }

    OperationClient mepClient = axisAnonymousOperation.createClient(serviceCtx, clientOptions);
    mepClient.addMessageContext(axisOutMsgCtx);
    axisOutMsgCtx.setAxisMessage(
        axisAnonymousOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE));

    // set the SEND_TIMEOUT for transport sender
    if (endpoint != null && endpoint.getTimeoutDuration() > 0) {
      axisOutMsgCtx.setProperty(SynapseConstants.SEND_TIMEOUT, endpoint.getTimeoutDuration());
    }

    // always set a callback as we decide if the send it blocking or non blocking within
    // the MEP client. This does not cause an overhead, as we simply create a 'holder'
    // object with a reference to the outgoing synapse message context
    // synapseOutMessageContext
    AsyncCallback callback = new AsyncCallback(axisOutMsgCtx, synapseOutMessageContext);
    if (!outOnlyMessage) {
      if (endpoint != null) {
        // set the timeout time and the timeout action to the callback, so that the
        // TimeoutHandler can detect timed out callbacks and take approprite action.
        callback.setTimeOutOn(System.currentTimeMillis() + endpoint.getTimeoutDuration());
        callback.setTimeOutAction(endpoint.getTimeoutAction());
      } else {
        callback.setTimeOutOn(System.currentTimeMillis());
      }
    }
    mepClient.setCallback(callback);
    //
    //        if (Utils.isClientThreadNonBlockingPropertySet(axisOutMsgCtx)) {
    //            SynapseCallbackReceiver synapseCallbackReceiver = (SynapseCallbackReceiver)
    // axisOutMsgCtx.getAxisOperation().getMessageReceiver();
    //            synapseCallbackReceiver.addCallback(axisOutMsgCtx.getMessageID(), new
    // FaultCallback(axisOutMsgCtx, synapseOutMessageContext));
    //        }

    // this is a temporary fix for converting messages from HTTP 1.1 chunking to HTTP 1.0.
    // Without this HTTP transport can block & become unresponsive because we are streaming
    // HTTP 1.1 messages and HTTP 1.0 require the whole message to caculate the content length
    if (originalInMsgCtx.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0)) {
      synapseOutMessageContext.getEnvelope().toString();
    }

    // with the nio transport, this causes the listener not to write a 202
    // Accepted response, as this implies that Synapse does not yet know if
    // a 202 or 200 response would be written back.
    originalInMsgCtx
        .getOperationContext()
        .setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, "SKIP");

    // if the transport out is explicitly set use it
    Object o = originalInMsgCtx.getProperty("TRANSPORT_OUT_DESCRIPTION");
    if (o != null && o instanceof TransportOutDescription) {
      axisOutMsgCtx.setTransportOut((TransportOutDescription) o);
      clientOptions.setTransportOut((TransportOutDescription) o);
      clientOptions.setProperty("TRANSPORT_OUT_DESCRIPTION", o);
    }

    mepClient.execute(true);
    if (wsRMEnabled) {
      Object rm11 = clientOptions.getProperty(SandeshaClientConstants.RM_SPEC_VERSION);
      if ((rm11 != null) && rm11.equals(Sandesha2Constants.SPEC_VERSIONS.v1_1)) {
        ServiceClient serviceClient =
            new ServiceClient(
                axisOutMsgCtx.getConfigurationContext(), axisOutMsgCtx.getAxisService());
        serviceClient.setTargetEPR(
            new EndpointReference(endpoint.getAddress(synapseOutMessageContext)));
        serviceClient.setOptions(clientOptions);
        serviceClient
            .getOptions()
            .setTo(new EndpointReference(endpoint.getAddress(synapseOutMessageContext)));
        SandeshaClient.terminateSequence(serviceClient);
      }
    }
  }
 /** get the default envelope */
 private org.apache.axiom.soap.SOAPEnvelope toEnvelope(org.apache.axiom.soap.SOAPFactory factory) {
   return factory.getDefaultEnvelope();
 }
  /**
   * Actual transformation of the current message into a fault message
   *
   * @param synCtx the current message context
   * @param soapVersion SOAP version of the resulting fault desired
   * @param synLog the Synapse log to use
   */
  private void makeSOAPFault(MessageContext synCtx, int soapVersion, SynapseLog synLog) {

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Creating a SOAP " + (soapVersion == SOAP11 ? "1.1" : "1.2") + " fault");
    }

    // get the correct SOAP factory to be used
    SOAPFactory factory =
        (soapVersion == SOAP11
            ? OMAbstractFactory.getSOAP11Factory()
            : OMAbstractFactory.getSOAP12Factory());

    // create the SOAP fault document and envelope
    OMDocument soapFaultDocument = factory.createOMDocument();
    SOAPEnvelope faultEnvelope = factory.getDefaultFaultEnvelope();
    soapFaultDocument.addChild(faultEnvelope);

    // create the fault element  if it is need
    SOAPFault fault = faultEnvelope.getBody().getFault();
    if (fault == null) {
      fault = factory.createSOAPFault();
    }

    // populate it
    setFaultCode(synCtx, factory, fault, soapVersion);
    setFaultReason(synCtx, factory, fault, soapVersion);
    setFaultNode(factory, fault);
    setFaultRole(factory, fault);
    setFaultDetail(synCtx, factory, fault);

    // set the all headers of original SOAP Envelope to the Fault Envelope
    if (synCtx.getEnvelope() != null) {
      SOAPHeader soapHeader = synCtx.getEnvelope().getHeader();
      if (soapHeader != null) {
        for (Iterator iter = soapHeader.examineAllHeaderBlocks(); iter.hasNext(); ) {
          Object o = iter.next();
          if (o instanceof SOAPHeaderBlock) {
            SOAPHeaderBlock header = (SOAPHeaderBlock) o;
            faultEnvelope.getHeader().addChild(header);
          } else if (o instanceof OMElement) {
            faultEnvelope.getHeader().addChild((OMElement) o);
          }
        }
      }
    }

    if (synLog.isTraceOrDebugEnabled()) {
      String msg =
          "Original SOAP Message : "
              + synCtx.getEnvelope().toString()
              + "Fault Message created : "
              + faultEnvelope.toString();
      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace(msg);
      }
      if (log.isTraceEnabled()) {
        log.trace(msg);
      }
    }

    // overwrite current message envelope with new fault envelope
    try {
      synCtx.setEnvelope(faultEnvelope);
    } catch (AxisFault af) {
      handleException(
          "Error replacing current SOAP envelope " + "with the fault envelope", af, synCtx);
    }

    if (synCtx.getFaultTo() != null) {
      synCtx.setTo(synCtx.getFaultTo());
    } else if (synCtx.getReplyTo() != null) {
      synCtx.setTo(synCtx.getReplyTo());
    } else {
      synCtx.setTo(null);
    }

    // set original messageID as relatesTo
    if (synCtx.getMessageID() != null) {
      RelatesTo relatesTo = new RelatesTo(synCtx.getMessageID());
      synCtx.setRelatesTo(new RelatesTo[] {relatesTo});
    }

    synLog.traceOrDebug("End : Fault mediator");
  }