/**
  * Executes the OperationClient
  *
  * @param opClient - Fully configured OperationClient
  * @param block - Indicates if blocking or non-blocking execute
  * @param msgContext - Axis2 MessageContext
  * @throws AxisFault - All exceptions are returned as AxisFaults
  */
 private void execute(
     OperationClient opClient, boolean block, org.apache.axis2.context.MessageContext msgContext)
     throws AxisFault {
   try {
     // Pre-Execute logging and setup
     preExecute(opClient, block, msgContext);
     // check if Exception should be thrown on SOAPFault
     if (log.isDebugEnabled()) {
       log.debug("Read throwExceptionIfSOAPFault property");
     }
     boolean exceptionToBeThrownOnSOAPFault =
         ClientUtils.getExceptionToBeThrownOnSOAPFault(msgContext);
     if (log.isDebugEnabled()) {
       log.debug(
           "throwExceptionIfSOAPFault property set on OperationClient.options "
               + exceptionToBeThrownOnSOAPFault);
     }
     opClient.getOptions().setExceptionToBeThrownOnSOAPFault(exceptionToBeThrownOnSOAPFault);
     // Invoke the OperationClient
     opClient.execute(block);
   } catch (Throwable e) {
     // Catch all Throwable (including runtime exceptions and Errors) and
     // throw as AxisFault.
     // Since e could be a Throwable (or Error) instead of an Exception, we'll have to wrap it:
     throw AxisFault.makeFault(ExceptionFactory.makeWebServiceException(e));
   } finally {
     // Post-Execute logging and setup
     postExecute(opClient, block, msgContext);
   }
 }
Exemple #2
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;
  }
  /*
   *  (non-Javadoc)
   * @see org.apache.axis2.jaxws.core.controller.InvocationController#invokeAsync(org.apache.axis2.jaxws.core.InvocationContext)
   */
  public Response doInvokeAsync(MessageContext request) {
    // We need the qname of the operation being invoked to know which
    // AxisOperation the OperationClient should be based on.
    // Note that the OperationDesc is only set through use of the Proxy. Dispatch
    // clients do not use operations, so the operationDesc will be null.  In this
    // case an anonymous AxisService with anoymouns AxisOperations for the supported
    // MEPs will be created; and it is that anonymous operation name which needs to
    // be specified
    QName operationName = getOperationNameToUse(request, ServiceClient.ANON_OUT_IN_OP);

    // TODO: Will the ServiceClient stick around on the InvocationContext
    // or will we need some other mechanism of creating this?
    // Try to create an OperationClient from the passed in ServiceClient
    InvocationContext ic = request.getInvocationContext();
    ServiceClient svcClient = ic.getServiceClient();
    OperationClient opClient = createOperationClient(svcClient, operationName);

    initOperationClient(opClient, request);

    // Setup the client so that it knows whether the underlying call to
    // Axis2 knows whether or not to start a listening port for an
    // asynchronous response.
    Boolean useAsyncMep = (Boolean) request.getProperty(Constants.USE_ASYNC_MEP);
    if ((useAsyncMep != null && useAsyncMep.booleanValue())
        || opClient.getOptions().isUseSeparateListener()) {
      configureAsyncListener(opClient);
    } else {
      if (log.isDebugEnabled()) {
        log.debug(
            "Asynchronous message exchange not enabled.  The invocation will be synchronous.");
      }
    }

    AsyncResponse resp = ic.getAsyncResponseListener();
    PollingFuture pf = new PollingFuture(ic);
    opClient.setCallback(pf);

    org.apache.axis2.context.MessageContext axisRequestMsgCtx = request.getAxisMessageContext();
    try {
      execute(opClient, false, axisRequestMsgCtx);
    } catch (AxisFault af) {
      if (log.isDebugEnabled()) {
        log.debug(
            axisRequestMsgCtx.getLogIDString()
                + " AxisFault received from client: "
                + af.getMessage());
      }
      /*
       * Save the exception on the callback.  The client will learn about the error when they try to
       * retrieve the async results via the Response.get().  "Errors that occur during the invocation
       * are reported via an exception when the client attempts to retrieve the results of the operation."
       * -- JAXWS 4.3.3
       */
      pf.onError(af);
    }

    return resp;
  }
Exemple #4
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;
  }
  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());
  }
  /** Auto generated method signature */
  public void setEmp(com.pa.SetEmp setEmp3) throws java.rmi.RemoteException {

    org.apache.axis2.context.MessageContext _messageContext = null;

    org.apache.axis2.client.OperationClient _operationClient =
        _serviceClient.createClient(_operations[0].getName());
    _operationClient.getOptions().setAction("urn:setEmp");
    _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true);

    addPropertyToOperationClient(
        _operationClient,
        org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR,
        "&");

    org.apache.axiom.soap.SOAPEnvelope env = null;
    _messageContext = new org.apache.axis2.context.MessageContext();

    // Style is Doc.

    env =
        toEnvelope(
            getFactory(_operationClient.getOptions().getSoapVersionURI()),
            setEmp3,
            optimizeContent(new javax.xml.namespace.QName("http://pa.com", "setEmp")),
            new javax.xml.namespace.QName("http://pa.com", "setEmp"));

    // adding SOAP soap_headers
    _serviceClient.addHeadersToEnvelope(env);
    // create message context with that soap envelope

    _messageContext.setEnvelope(env);

    // add the message contxt to the operation client
    _operationClient.addMessageContext(_messageContext);

    _operationClient.execute(true);

    if (_messageContext.getTransportOut() != null) {
      _messageContext.getTransportOut().getSender().cleanup(_messageContext);
    }

    return;
  }
  /**
   * Called by execute(OperationClient) to perform pre-execute tasks.
   *
   * @param opClient
   * @param block - Indicates if blocking or non-blocking execute
   * @param msgContext - Axis2 MessageContext
   */
  private void preExecute(
      OperationClient opClient, boolean block, org.apache.axis2.context.MessageContext msgContext)
      throws AxisFault {
    // This assumes that we are on the ultimate execution thread

    // This has to be here so the ThreadContextMigrator can pick it up.
    msgContext.getOptions().setUseSeparateListener(opClient.getOptions().isUseSeparateListener());

    ThreadContextMigratorUtil.performMigrationToContext(
        Constants.THREAD_CONTEXT_MIGRATOR_LIST_ID, msgContext);

    // Enable the ThreadContextMigrator to override UseSeparateListener
    opClient.getOptions().setUseSeparateListener(msgContext.getOptions().isUseSeparateListener());

    if (log.isDebugEnabled()) {
      log.debug("Start OperationClient.execute(" + block + ")");
      log.debug("UseSeparateListener: " + opClient.getOptions().isUseSeparateListener());
    }
  }
  private void initOperationClient(OperationClient opClient, MessageContext requestMsgCtx) {
    org.apache.axis2.context.MessageContext axisRequest = requestMsgCtx.getAxisMessageContext();
    setupProperties(requestMsgCtx); // , axisRequest.getOptions());

    if (opClient != null) {
      Options options = opClient.getOptions();

      // Get the target endpoint address and setup the TO endpoint
      // reference.  This tells us where the request is going.
      EndpointReference toEPR = axisRequest.getTo();

      if (toEPR == null) {
        String targetUrl =
            (String) requestMsgCtx.getProperty(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
        toEPR = new EndpointReference(targetUrl);
      }

      options.setTo(toEPR);

      // Get the SOAP Action (if needed)
      String soapAction = ClientUtils.findSOAPAction(requestMsgCtx);
      options.setAction(soapAction);
      // get the timeout from the request message context options as it may have been
      // set by the user; if it was not set by the user we will just be setting the
      // timeout on the operation client to the default so it will not have a negative
      // effect; this logic is reliant on the fact the JAX-WS MessageContext is delegating
      // to the Axis2 Options object and not storing its own property bag
      long timeout = axisRequest.getOptions().getTimeOutInMilliSeconds();
      options.setTimeOutInMilliSeconds(timeout);

      // Use the OperationClient to send the request and put the contents
      // of the response in the response MessageContext.
      try {
        // Set the Axis2 request MessageContext
        opClient.addMessageContext(axisRequest);
      } catch (Exception e) {
        // TODO: Do something
      }
    }
  }
  /**
   * Auto generated method signature for Asynchronous Invocations
   *
   * @see com.pa.SecondFileService#startgetEmp
   * @param getEmp4
   */
  public void startgetEmp(
      com.pa.GetEmp getEmp4, final com.pa.SecondFileServiceCallbackHandler callback)
      throws java.rmi.RemoteException {

    org.apache.axis2.client.OperationClient _operationClient =
        _serviceClient.createClient(_operations[1].getName());
    _operationClient.getOptions().setAction("urn:getEmp");
    _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true);

    addPropertyToOperationClient(
        _operationClient,
        org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR,
        "&");

    // create SOAP envelope with that payload
    org.apache.axiom.soap.SOAPEnvelope env = null;
    final org.apache.axis2.context.MessageContext _messageContext =
        new org.apache.axis2.context.MessageContext();

    // Style is Doc.

    env =
        toEnvelope(
            getFactory(_operationClient.getOptions().getSoapVersionURI()),
            getEmp4,
            optimizeContent(new javax.xml.namespace.QName("http://pa.com", "getEmp")),
            new javax.xml.namespace.QName("http://pa.com", "getEmp"));

    // adding SOAP soap_headers
    _serviceClient.addHeadersToEnvelope(env);
    // create message context with that soap envelope
    _messageContext.setEnvelope(env);

    // add the message context to the operation client
    _operationClient.addMessageContext(_messageContext);

    _operationClient.setCallback(
        new org.apache.axis2.client.async.AxisCallback() {
          public void onMessage(org.apache.axis2.context.MessageContext resultContext) {
            try {
              org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope();

              java.lang.Object object =
                  fromOM(
                      resultEnv.getBody().getFirstElement(),
                      com.pa.GetEmpResponse.class,
                      getEnvelopeNamespaces(resultEnv));
              callback.receiveResultgetEmp((com.pa.GetEmpResponse) object);

            } catch (org.apache.axis2.AxisFault e) {
              callback.receiveErrorgetEmp(e);
            }
          }

          public void onError(java.lang.Exception error) {
            if (error instanceof org.apache.axis2.AxisFault) {
              org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error;
              org.apache.axiom.om.OMElement faultElt = f.getDetail();
              if (faultElt != null) {
                if (faultExceptionNameMap.containsKey(
                    new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getEmp"))) {
                  // make the fault by reflection
                  try {
                    java.lang.String exceptionClassName =
                        (java.lang.String)
                            faultExceptionClassNameMap.get(
                                new org.apache.axis2.client.FaultMapKey(
                                    faultElt.getQName(), "getEmp"));
                    java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName);
                    java.lang.reflect.Constructor constructor =
                        exceptionClass.getConstructor(String.class);
                    java.lang.Exception ex =
                        (java.lang.Exception) constructor.newInstance(f.getMessage());
                    // message class
                    java.lang.String messageClassName =
                        (java.lang.String)
                            faultMessageMap.get(
                                new org.apache.axis2.client.FaultMapKey(
                                    faultElt.getQName(), "getEmp"));
                    java.lang.Class messageClass = java.lang.Class.forName(messageClassName);
                    java.lang.Object messageObject = fromOM(faultElt, messageClass, null);
                    java.lang.reflect.Method m =
                        exceptionClass.getMethod(
                            "setFaultMessage", new java.lang.Class[] {messageClass});
                    m.invoke(ex, new java.lang.Object[] {messageObject});

                    callback.receiveErrorgetEmp(new java.rmi.RemoteException(ex.getMessage(), ex));
                  } catch (java.lang.ClassCastException e) {
                    // we cannot intantiate the class - throw the original Axis fault
                    callback.receiveErrorgetEmp(f);
                  } catch (java.lang.ClassNotFoundException e) {
                    // we cannot intantiate the class - throw the original Axis fault
                    callback.receiveErrorgetEmp(f);
                  } catch (java.lang.NoSuchMethodException e) {
                    // we cannot intantiate the class - throw the original Axis fault
                    callback.receiveErrorgetEmp(f);
                  } catch (java.lang.reflect.InvocationTargetException e) {
                    // we cannot intantiate the class - throw the original Axis fault
                    callback.receiveErrorgetEmp(f);
                  } catch (java.lang.IllegalAccessException e) {
                    // we cannot intantiate the class - throw the original Axis fault
                    callback.receiveErrorgetEmp(f);
                  } catch (java.lang.InstantiationException e) {
                    // we cannot intantiate the class - throw the original Axis fault
                    callback.receiveErrorgetEmp(f);
                  } catch (org.apache.axis2.AxisFault e) {
                    // we cannot intantiate the class - throw the original Axis fault
                    callback.receiveErrorgetEmp(f);
                  }
                } else {
                  callback.receiveErrorgetEmp(f);
                }
              } else {
                callback.receiveErrorgetEmp(f);
              }
            } else {
              callback.receiveErrorgetEmp(error);
            }
          }

          public void onFault(org.apache.axis2.context.MessageContext faultContext) {
            org.apache.axis2.AxisFault fault =
                org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext);
            onError(fault);
          }

          public void onComplete() {
            try {
              _messageContext.getTransportOut().getSender().cleanup(_messageContext);
            } catch (org.apache.axis2.AxisFault axisFault) {
              callback.receiveErrorgetEmp(axisFault);
            }
          }
        });

    org.apache.axis2.util.CallbackReceiver _callbackReceiver = null;
    if (_operations[1].getMessageReceiver() == null
        && _operationClient.getOptions().isUseSeparateListener()) {
      _callbackReceiver = new org.apache.axis2.util.CallbackReceiver();
      _operations[1].setMessageReceiver(_callbackReceiver);
    }

    // execute the operation client
    _operationClient.execute(false);
  }
  /**
   * Auto generated method signature
   *
   * @see com.pa.SecondFileService#getEmp
   * @param getEmp4
   */
  public com.pa.GetEmpResponse getEmp(com.pa.GetEmp getEmp4) throws java.rmi.RemoteException {

    org.apache.axis2.context.MessageContext _messageContext = null;
    try {
      org.apache.axis2.client.OperationClient _operationClient =
          _serviceClient.createClient(_operations[1].getName());
      _operationClient.getOptions().setAction("urn:getEmp");
      _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true);

      addPropertyToOperationClient(
          _operationClient,
          org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR,
          "&");

      // create a message context
      _messageContext = new org.apache.axis2.context.MessageContext();

      // create SOAP envelope with that payload
      org.apache.axiom.soap.SOAPEnvelope env = null;

      env =
          toEnvelope(
              getFactory(_operationClient.getOptions().getSoapVersionURI()),
              getEmp4,
              optimizeContent(new javax.xml.namespace.QName("http://pa.com", "getEmp")),
              new javax.xml.namespace.QName("http://pa.com", "getEmp"));

      // adding SOAP soap_headers
      _serviceClient.addHeadersToEnvelope(env);
      // set the message context with that soap envelope
      _messageContext.setEnvelope(env);

      // add the message contxt to the operation client
      _operationClient.addMessageContext(_messageContext);

      // execute the operation client
      _operationClient.execute(true);

      org.apache.axis2.context.MessageContext _returnMessageContext =
          _operationClient.getMessageContext(
              org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE);
      org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope();

      java.lang.Object object =
          fromOM(
              _returnEnv.getBody().getFirstElement(),
              com.pa.GetEmpResponse.class,
              getEnvelopeNamespaces(_returnEnv));

      return (com.pa.GetEmpResponse) object;

    } catch (org.apache.axis2.AxisFault f) {

      org.apache.axiom.om.OMElement faultElt = f.getDetail();
      if (faultElt != null) {
        if (faultExceptionNameMap.containsKey(
            new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getEmp"))) {
          // make the fault by reflection
          try {
            java.lang.String exceptionClassName =
                (java.lang.String)
                    faultExceptionClassNameMap.get(
                        new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getEmp"));
            java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName);
            java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class);
            java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage());
            // message class
            java.lang.String messageClassName =
                (java.lang.String)
                    faultMessageMap.get(
                        new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getEmp"));
            java.lang.Class messageClass = java.lang.Class.forName(messageClassName);
            java.lang.Object messageObject = fromOM(faultElt, messageClass, null);
            java.lang.reflect.Method m =
                exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] {messageClass});
            m.invoke(ex, new java.lang.Object[] {messageObject});

            throw new java.rmi.RemoteException(ex.getMessage(), ex);
          } catch (java.lang.ClassCastException e) {
            // we cannot intantiate the class - throw the original Axis fault
            throw f;
          } catch (java.lang.ClassNotFoundException e) {
            // we cannot intantiate the class - throw the original Axis fault
            throw f;
          } catch (java.lang.NoSuchMethodException e) {
            // we cannot intantiate the class - throw the original Axis fault
            throw f;
          } catch (java.lang.reflect.InvocationTargetException e) {
            // we cannot intantiate the class - throw the original Axis fault
            throw f;
          } catch (java.lang.IllegalAccessException e) {
            // we cannot intantiate the class - throw the original Axis fault
            throw f;
          } catch (java.lang.InstantiationException e) {
            // we cannot intantiate the class - throw the original Axis fault
            throw f;
          }
        } else {
          throw f;
        }
      } else {
        throw f;
      }
    } finally {
      if (_messageContext.getTransportOut() != null) {
        _messageContext.getTransportOut().getSender().cleanup(_messageContext);
      }
    }
  }
  public CadConsultaCadastro2Stub.ConsultaCadastro2Result consultaCadastro2(
      final CadConsultaCadastro2Stub.NfeDadosMsg nfeDadosMsg,
      final CadConsultaCadastro2Stub.NfeCabecMsgE nfeCabecMsg)
      throws java.rmi.RemoteException {

    org.apache.axis2.context.MessageContext _messageContext = null;
    try {
      final org.apache.axis2.client.OperationClient _operationClient =
          this._serviceClient.createClient(this._operations[0].getName());
      _operationClient
          .getOptions()
          .setAction(
              "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2/consultaCadastro2");
      _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true);

      this.addPropertyToOperationClient(
          _operationClient,
          org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR,
          "&");

      // create a message context
      _messageContext = new org.apache.axis2.context.MessageContext();

      // create SOAP envelope with that payload
      org.apache.axiom.soap.SOAPEnvelope env = null;

      env =
          this.toEnvelope(
              Stub.getFactory(_operationClient.getOptions().getSoapVersionURI()),
              nfeDadosMsg,
              this.optimizeContent(
                  new javax.xml.namespace.QName(
                      "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2",
                      "consultaCadastro2")),
              new javax.xml.namespace.QName(
                  "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2",
                  "consultaCadastro2"));

      env.build();

      // add the children only if the parameter is not null
      if (nfeCabecMsg != null) {

        final org.apache.axiom.om.OMElement omElementnfeCabecMsg =
            this.toOM(
                nfeCabecMsg,
                this.optimizeContent(
                    new javax.xml.namespace.QName(
                        "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2",
                        "consultaCadastro2")));
        this.addHeader(omElementnfeCabecMsg, env);
      }

      // adding SOAP soap_headers
      this._serviceClient.addHeadersToEnvelope(env);
      // set the message context with that soap envelope
      _messageContext.setEnvelope(env);

      // add the message contxt to the operation client
      _operationClient.addMessageContext(_messageContext);

      // execute the operation client
      _operationClient.execute(true);

      final org.apache.axis2.context.MessageContext _returnMessageContext =
          _operationClient.getMessageContext(
              org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE);
      final org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope();

      final java.lang.Object object =
          this.fromOM(
              _returnEnv.getBody().getFirstElement(),
              CadConsultaCadastro2Stub.ConsultaCadastro2Result.class,
              this.getEnvelopeNamespaces(_returnEnv));

      return (CadConsultaCadastro2Stub.ConsultaCadastro2Result) object;

    } catch (final org.apache.axis2.AxisFault f) {

      final org.apache.axiom.om.OMElement faultElt = f.getDetail();
      if (faultElt != null) {
        if (this.faultExceptionNameMap.containsKey(
            new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "consultaCadastro2"))) {
          // make the fault by reflection
          try {
            final java.lang.String exceptionClassName =
                (java.lang.String)
                    this.faultExceptionClassNameMap.get(
                        new org.apache.axis2.client.FaultMapKey(
                            faultElt.getQName(), "consultaCadastro2"));
            final Class<?> exceptionClass = java.lang.Class.forName(exceptionClassName);
            final Constructor<?> constructor = exceptionClass.getConstructor(String.class);
            final java.lang.Exception ex =
                (java.lang.Exception) constructor.newInstance(f.getMessage());
            // message class
            final java.lang.String messageClassName =
                (java.lang.String)
                    this.faultMessageMap.get(
                        new org.apache.axis2.client.FaultMapKey(
                            faultElt.getQName(), "consultaCadastro2"));
            final Class<?> messageClass = java.lang.Class.forName(messageClassName);
            final java.lang.Object messageObject = this.fromOM(faultElt, messageClass, null);
            final java.lang.reflect.Method m =
                exceptionClass.getMethod("setFaultMessage", messageClass);
            m.invoke(ex, messageObject);

            throw new java.rmi.RemoteException(ex.getMessage(), ex);
          } catch (final ClassCastException
              | InstantiationException
              | IllegalAccessException
              | java.lang.reflect.InvocationTargetException
              | NoSuchMethodException
              | ClassNotFoundException e) {
            // we cannot intantiate the class - throw the original Axis fault
            throw f;
          }
        } else {
          throw f;
        }
      } else {
        throw f;
      }
    } finally {
      if (_messageContext.getTransportOut() != null) {
        _messageContext.getTransportOut().getSender().cleanup(_messageContext);
      }
    }
  }
  /**
   * 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);
      }
    }
  }
  /**
   * This method creates 3 soap envelopes for 3 different client based sessions. Then it randomly
   * choose one envelope for each iteration and send it to the ESB. ESB should be configured with
   * session affinity load balancer and the SampleClientInitiatedSession dispatcher. This will
   * output request number, session number and the server ID for each iteration. So it can be
   * observed that one session number always associated with one server ID.
   */
  private void sessionfullClient() {

    String synapsePort = "8280";
    int iterations = 100;
    boolean infinite = true;

    String pPort = getProperty("port", synapsePort);
    String pIterations = getProperty("i", null);
    String addUrl = getProperty("addurl", null);
    String trpUrl = getProperty("trpurl", null);
    String prxUrl = getProperty("prxurl", null);
    String sleep = getProperty("sleep", null);
    String session = getProperty("session", null);

    long sleepTime = -1;
    if (sleep != null) {
      try {
        sleepTime = Long.parseLong(sleep);
      } catch (NumberFormatException ignored) {
      }
    }

    if (pPort != null) {
      try {

        Integer.parseInt(pPort);
        synapsePort = pPort;
      } catch (NumberFormatException e) {
        // run with default value
      }
    }

    if (pIterations != null) {
      try {
        iterations = Integer.parseInt(pIterations);
        if (iterations != -1) {
          infinite = false;
        }
      } catch (NumberFormatException e) {
        // run with default values
      }
    }

    Options options = new Options();
    options.setTo(
        new EndpointReference("http://localhost:" + synapsePort + "/services/LBService1"));
    options.setAction("urn:sampleOperation");
    options.setTimeOutInMilliSeconds(10000000);

    try {

      SOAPEnvelope env1 = buildSoapEnvelope("c1", "v1");
      SOAPEnvelope env2 = buildSoapEnvelope("c2", "v1");
      SOAPEnvelope env3 = buildSoapEnvelope("c3", "v1");
      SOAPEnvelope[] envelopes = {env1, env2, env3};

      ConfigurationContext configContext =
          ConfigurationContextFactory.createConfigurationContextFromFileSystem("client_repo", null);
      ServiceClient client = new ServiceClient(configContext, null);

      // set addressing, transport and proxy url
      if (addUrl != null && !"null".equals(addUrl)) {
        client.engageModule("addressing");
        options.setTo(new EndpointReference(addUrl));
      }
      if (trpUrl != null && !"null".equals(trpUrl)) {
        options.setProperty(Constants.Configuration.TRANSPORT_URL, trpUrl);
      } else {
        client.engageModule("addressing");
      }
      if (prxUrl != null && !"null".equals(prxUrl)) {
        HttpTransportProperties.ProxyProperties proxyProperties =
            new HttpTransportProperties.ProxyProperties();
        try {
          URL url = new URL(prxUrl);
          proxyProperties.setProxyName(url.getHost());
          proxyProperties.setProxyPort(url.getPort());
          proxyProperties.setUserName("");
          proxyProperties.setPassWord("");
          proxyProperties.setDomain("");
          options.setProperty(HTTPConstants.PROXY, proxyProperties);
        } catch (MalformedURLException e) {
          throw new AxisFault("Error creating proxy URL", e);
        }
      }
      client.setOptions(options);

      int i = 0;
      int sessionNumber = 0;
      String[] cookies = new String[3];
      boolean httpSession = session != null && "http".equals(session);
      int cookieNumber = 0;
      while (i < iterations || infinite) {

        i++;
        if (sleepTime != -1) {
          try {
            Thread.sleep(sleepTime);
          } catch (InterruptedException ignored) {
          }
        }

        MessageContext messageContext = new MessageContext();
        sessionNumber = getSessionTurn(envelopes.length);

        messageContext.setEnvelope(envelopes[sessionNumber]);
        cookieNumber = getSessionTurn(cookies.length);
        String cookie = cookies[cookieNumber];
        if (httpSession) {
          setSessionID(messageContext, cookie);
        }
        try {
          OperationClient op = client.createClient(ServiceClient.ANON_OUT_IN_OP);
          op.addMessageContext(messageContext);
          op.execute(true);

          MessageContext responseContext =
              op.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
          String receivedCookie = extractSessionID(responseContext);
          String receivedSetCookie = getSetCookieHeader(responseContext);
          if (httpSession) {

            if (receivedSetCookie != null && !"".equals(receivedSetCookie)) {
              cookies[cookieNumber] = receivedCookie;
            }
          }

          SOAPEnvelope responseEnvelope = responseContext.getEnvelope();

          OMElement vElement = responseEnvelope.getBody().getFirstChildWithName(new QName("Value"));
          System.out.println(
              "Request: "
                  + i
                  + " with Session ID: "
                  + (httpSession ? cookie : sessionNumber)
                  + " ---- "
                  + "Response : with  "
                  + (httpSession && receivedCookie != null
                      ? (receivedSetCookie != null ? receivedSetCookie : receivedCookie)
                      : " ")
                  + " "
                  + vElement.getText());
        } catch (AxisFault axisFault) {
          System.out.println(
              "Request with session id "
                  + (httpSession ? cookie : sessionNumber)
                  + " "
                  + "- Get a Fault : "
                  + axisFault.getMessage());
        }
      }

    } catch (AxisFault axisFault) {
      System.out.println(axisFault.getMessage());
    }
  }
  /*
   * (non-Javadoc)
   * @see org.apache.axis2.jaxws.core.controller.InvocationController#invoke(org.apache.axis2.jaxws.core.InvocationContext)
   */
  public MessageContext doInvoke(MessageContext request) {

    // We need the qname of the operation being invoked to know which
    // AxisOperation the OperationClient should be based on.
    // Note that the OperationDesc is only set through use of the Proxy. Dispatch
    // clients do not use operations, so the operationDesc will be null.  In this
    // case an anonymous AxisService with anoymouns AxisOperations for the supported
    // MEPs will be created; and it is that anonymous operation name which needs to
    // be specified
    QName operationName = getOperationNameToUse(request, ServiceClient.ANON_OUT_IN_OP);

    // TODO: Will the ServiceClient stick around on the InvocationContext
    // or will we need some other mechanism of creating this?
    // Try to create an OperationClient from the passed in ServiceClient
    InvocationContext ic = request.getInvocationContext();
    ServiceClient svcClient = ic.getServiceClient();
    OperationClient opClient = createOperationClient(svcClient, operationName);

    initOperationClient(opClient, request);

    // Setup the client so that it knows whether the underlying call to
    // Axis2 knows whether or not to start a listening port for an
    // asynchronous response.
    Boolean useAsyncMep = (Boolean) request.getProperty(Constants.USE_ASYNC_MEP);
    if ((useAsyncMep != null && useAsyncMep.booleanValue())
        || opClient.getOptions().isUseSeparateListener()) {
      configureAsyncListener(opClient);
    } else {
      if (log.isDebugEnabled()) {
        log.debug(
            "Asynchronous message exchange not enabled.  The invocation will be synchronous.");
      }
    }

    org.apache.axis2.context.MessageContext axisRequestMsgCtx = request.getAxisMessageContext();
    org.apache.axis2.context.MessageContext axisResponseMsgCtx = null;

    MessageContext response = null;

    AxisFault faultexception =
        null; // don't let the keyword "fault" confuse you.  This is an exception class.
    try {
      execute(opClient, true, axisRequestMsgCtx);
    } catch (AxisFault af) {
      // If an AxisFault was thrown, we need to cleanup the original OperationContext.
      // Failure to do so results in a memory leak.
      opClient.getOperationContext().cleanup();
      // save the fault in case it didn't come from the endpoint, and thus
      // there would be no message on the MessageContext
      faultexception = af;
      if (log.isDebugEnabled()) {
        log.debug(
            axisRequestMsgCtx.getLogIDString()
                + " AxisFault received from client: "
                + af.getMessage());
      }
    }

    try {
      // Collect the response MessageContext and envelope
      axisResponseMsgCtx = opClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
      response = new MessageContext(axisResponseMsgCtx);
      response.setMEPContext(request.getMEPContext());

      // If the Message object is still null, then it's possible that a
      // local AxisFault was thrown and we need to save it for later throwing
      // We do not want to create a message and go through the whole handler or
      // XMLFault processing because it's unnecessary.
      //
      // Same is true if we get a valid non-fault server response but some jaxws
      // client processing (a handler, perhaps) throws an exception.
      //
      // If the response message itself is a fault message, let it pass through.
      if ((faultexception != null)
          && ((response.getMessage() == null) || (!response.getMessage().isFault()))) {
        MessageFactory factory = (MessageFactory) FactoryRegistry.getFactory(MessageFactory.class);
        Message message = factory.create(request.getMessage().getProtocol());
        response.setLocalException(faultexception);
        response.setMessage(message);
      }

      // This assumes that we are on the ultimate execution thread
      ThreadContextMigratorUtil.performMigrationToThread(
          Constants.THREAD_CONTEXT_MIGRATOR_LIST_ID, axisResponseMsgCtx);
    } catch (Exception e) {
      throw ExceptionFactory.makeWebServiceException(e);
    }

    return response;
  }
 private void configureAsyncListener(OperationClient client) {
   client.getOptions().setUseSeparateListener(true);
 }
  /*
   *  (non-Javadoc)
   * @see org.apache.axis2.jaxws.core.controller.InvocationController#invokeAsync(org.apache.axis2.jaxws.core.InvocationContext, javax.xml.ws.AsyncHandler)
   */
  public Future<?> doInvokeAsync(MessageContext request, AsyncHandler callback) {
    // We need the qname of the operation being invoked to know which
    // AxisOperation the OperationClient should be based on.
    // Note that the OperationDesc is only set through use of the Proxy. Dispatch
    // clients do not use operations, so the operationDesc will be null.  In this
    // case an anonymous AxisService with anoymouns AxisOperations for the supported
    // MEPs will be created; and it is that anonymous operation name which needs to
    // be specified
    QName operationName = getOperationNameToUse(request, ServiceClient.ANON_OUT_IN_OP);

    // TODO: Will the ServiceClient stick around on the InvocationContext
    // or will we need some other mechanism of creating this?
    // Try to create an OperationClient from the passed in ServiceClient
    InvocationContext ic = request.getInvocationContext();
    ServiceClient svcClient = ic.getServiceClient();
    OperationClient opClient = createOperationClient(svcClient, operationName);

    initOperationClient(opClient, request);

    // Setup the client so that it knows whether the underlying call to
    // Axis2 knows whether or not to start a listening port for an
    // asynchronous response.
    Boolean useAsyncMep = (Boolean) request.getProperty(Constants.USE_ASYNC_MEP);
    if ((useAsyncMep != null && useAsyncMep.booleanValue())
        || opClient.getOptions().isUseSeparateListener()) {
      configureAsyncListener(opClient);
    } else {
      if (log.isDebugEnabled()) {
        log.debug(
            "Asynchronous message exchange not enabled.  The invocation will be synchronous.");
      }
    }

    CallbackFuture cbf = null;
    if (callback != null) {
      cbf = new CallbackFuture(ic, callback);
    } else {
      throw ExceptionFactory.makeWebServiceException(Messages.getMessage("ICErr4"));
    }

    opClient.setCallback(cbf);

    org.apache.axis2.context.MessageContext axisRequestMsgCtx = request.getAxisMessageContext();
    try {
      execute(opClient, false, axisRequestMsgCtx);
    } catch (AxisFault af) {
      if (log.isDebugEnabled()) {
        log.debug(
            axisRequestMsgCtx.getLogIDString()
                + " AxisFault received from client: "
                + af.getMessage());
      }
      /*
       * Save the exception on the callback.  The client will learn about the error when they try to
       * retrieve the async results via the Response.get().  "Errors that occur during the invocation
       * are reported via an exception when the client attempts to retrieve the results of the operation."
       * -- JAXWS 4.3.3
       */

      /*
       * TODO:  This is the appropriate thing to do here since the thrown exception may occur before
       * we switch threads to the async thread.  But... what happens if we've already switched over
       * to the async thread?  So far, it appears that the exception gets set on the FutureTask
       * Concurrent object, and we never hit this scope.  This means that later, when the client
       * calls future.get(), no exception will be thrown despite what the spec says.  The client can,
       * however, retrieve errors via it's AsyncHandler.
       */
      cbf.onError(af);
    }

    return cbf.getFutureTask();
  }