public void invokeBusinessLogic(org.apache.axis2.context.MessageContext msgContext)
      throws org.apache.axis2.AxisFault {

    try {

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

      MultitenancyThrottlingServiceSkeletonInterface skel =
          (MultitenancyThrottlingServiceSkeletonInterface) obj;
      // Out Envelop
      org.apache.axiom.soap.SOAPEnvelope envelope = null;
      // Find the axisOperation that has been set by the Dispatch phase.
      org.apache.axis2.description.AxisOperation op =
          msgContext.getOperationContext().getAxisOperation();
      if (op == null) {
        throw new org.apache.axis2.AxisFault(
            "Operation is not located, if this is doclit style the SOAP-ACTION should specified via the SOAP Action to use the RawXMLProvider");
      }

      java.lang.String methodName;
      if ((op.getName() != null)
          && ((methodName =
                  org.apache.axis2.util.JavaUtils.xmlNameToJavaIdentifier(
                      op.getName().getLocalPart()))
              != null)) {

        if ("executeThrottlingRules".equals(methodName)) {

          // doc style
          org.wso2.carbon.throttling.manager.services.ExecuteThrottlingRules wrappedParam =
              (org.wso2.carbon.throttling.manager.services.ExecuteThrottlingRules)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.wso2.carbon.throttling.manager.services.ExecuteThrottlingRules.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          skel.executeThrottlingRules(wrappedParam);

          envelope = getSOAPFactory(msgContext).getDefaultEnvelope();

        } else {
          throw new java.lang.RuntimeException("method not found");
        }
      }
    } catch (MultitenancyThrottlingServiceExceptionException e) {
      msgContext.setProperty(
          org.apache.axis2.Constants.FAULT_NAME, "MultitenancyThrottlingServiceException");
      org.apache.axis2.AxisFault f = createAxisFault(e);
      if (e.getFaultMessage() != null) {
        f.setDetail(toOM(e.getFaultMessage(), false));
      }
      throw f;
    } catch (java.lang.Exception e) {
      throw org.apache.axis2.AxisFault.makeFault(e);
    }
  }
Пример #2
0
 private int getTenantId(MessageContext messageContext) {
   PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
   int tenantId = carbonContext.getTenantId();
   if (tenantId > -1 || tenantId == MultitenantConstants.SUPER_TENANT_ID) {
     return tenantId;
   }
   String domain = carbonContext.getTenantDomain();
   if (domain == null) {
     SOAPBody soapBody = messageContext.getEnvelope().getBody();
     if (soapBody != null && soapBody.getFirstElement() != null) {
       OMElement usernameElem =
           soapBody
               .getFirstElement()
               .getFirstChildWithName(
                   new QName(
                       ServerConstants.AUTHENTICATION_SERVICE_NS,
                       ServerConstants.AUTHENTICATION_SERVICE_USERNAME));
       if (usernameElem != null) {
         String userName = usernameElem.getText();
         domain = MultitenantUtils.getTenantDomain(userName);
       }
     }
   }
   if (domain != null) {
     try {
       tenantId = Util.getRealmService().getTenantManager().getTenantId(domain);
     } catch (org.wso2.carbon.user.api.UserStoreException e) {
       log.error("An error occurred while obtaining the tenant id.", e);
     }
   }
   return tenantId;
 }
  /**
   * 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);
    }
  }
 /**
  * Adding ws-Coordination context to soap request.
  *
  * @param msgCtx MessageContext
  * @param messageID UUID as a WS-Coordination identifier
  * @param registrationService URL of the ws-coordination registration service.
  */
 public void addCoordinationContext(
     MessageContext msgCtx, String messageID, String registrationService) {
   SOAPHeader header = msgCtx.getEnvelope().getHeader();
   EndpointReference epr = new EndpointReference();
   epr.setAddress(registrationService);
   CoordinationContext context = new HumanTaskCoordinationContextImpl(messageID, epr);
   header.addChild(context.toOM());
 }
  public void receive(org.apache.axis2.context.MessageContext mc) throws AxisFault {

    MessageContext synCtx = MessageContextCreatorForAxis2.getSynapseMessageContext(mc);

    StatisticsReporter.reportForComponent(
        synCtx,
        AspectConfigurationDetectionStrategy.getAspectConfiguration(synCtx),
        ComponentType.PROXYSERVICE);

    boolean traceOn = synCtx.getMainSequence().getTraceState() == SynapseConstants.TRACING_ON;
    boolean traceOrDebugOn = traceOn || log.isDebugEnabled();

    if (traceOrDebugOn) {
      traceOrDebug(traceOn, "Synapse received a new message for message mediation...");
      traceOrDebug(
          traceOn, "Received To: " + (mc.getTo() != null ? mc.getTo().getAddress() : "null"));
      traceOrDebug(
          traceOn, "SOAPAction: " + (mc.getSoapAction() != null ? mc.getSoapAction() : "null"));
      traceOrDebug(
          traceOn, "WSA-Action: " + (mc.getWSAAction() != null ? mc.getWSAAction() : "null"));

      if (traceOn && trace.isTraceEnabled()) {
        String[] cids = mc.getAttachmentMap().getAllContentIDs();
        if (cids != null && cids.length > 0) {
          for (String cid : cids) {
            trace.trace("Attachment : " + cid);
          }
        }
        trace.trace("Envelope : " + mc.getEnvelope());
      }
    }

    // get service log for this message and attach to the message context
    Log serviceLog =
        LogFactory.getLog(
            SynapseConstants.SERVICE_LOGGER_PREFIX + SynapseConstants.SYNAPSE_SERVICE_NAME);
    ((Axis2MessageContext) synCtx).setServiceLog(serviceLog);

    try {
      // invoke synapse message mediation through the main sequence
      synCtx.getEnvironment().injectMessage(synCtx);

    } catch (SynapseException syne) {

      if (!synCtx.getFaultStack().isEmpty()) {
        warn(traceOn, "Executing fault handler due to exception encountered", synCtx);
        ((FaultHandler) synCtx.getFaultStack().pop()).handleFault(synCtx, syne);

      } else {
        warn(
            traceOn,
            "Exception encountered but no fault handler found - " + "message dropped",
            synCtx);
      }
    } finally {
      StatisticsReporter.endReportForAllOnRequestProcessed(synCtx);
    }
  }
Пример #6
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;
  }
  /**
   * Create a SOAP request and add a list of attachment ids to the SOAP Header
   *
   * @param msgCtx base message context which will be manipulated through out the operation
   * @param message element to be included in the SOAP Body
   * @param op operation incorporated with the request
   * @param attachmentIDList list of attachment ids to be included in the SOAP header
   * @throws AxisFault Exception if operation/input not found for the binding or if any exception
   *     thrown from the axis2 level operations
   */
  public void createSoapRequest(
      MessageContext msgCtx, Element message, Operation op, List<Long> attachmentIDList)
      throws AxisFault {
    createSoapRequest(msgCtx, message, op);

    SOAPHeader header = msgCtx.getEnvelope().getHeader();

    if (attachmentIDList != null && !attachmentIDList.isEmpty()) {
      addAttachmentIDHeader(header, attachmentIDList);
    }
  }
Пример #8
0
  /**
   * Creates the content of a Reception Awareness Receipt as defined in section 5.1.8 of the AS4
   * profile.
   *
   * <p>NOTE: The first element returned by {@link
   * org.holodeckb2b.ebms3.packaging.UserMessage#getElements(org.apache.axiom.om.OMElement)} is
   * included in the <code>eb:Receipt</code> element. The given {@link UserMessage} object therefor
   * MUST represent this element.
   *
   * @param mc The current {@link MessageContext}, used to get copy of <code>eb:UserMessage</code>
   *     element
   * @param um The data on the current User Message being processed, used for getting
   *     <i>refToMessageId</i> and <i>P-Mode</i> info.
   * @return The content for the new Receipt represented as an iteration of <code>OMElement</code>s
   */
  protected Iterator<OMElement> createRARContent(MessageContext mc, UserMessage um) {
    ArrayList<OMElement> rcptContent = new ArrayList<OMElement>();
    // Get the UserMessage element from the message header
    SOAPHeaderBlock messaging = Messaging.getElement(mc.getEnvelope());
    OMElement umElement =
        (OMElement) org.holodeckb2b.ebms3.packaging.UserMessage.getElements(messaging).next();
    // and add it to receipt content
    rcptContent.add(umElement);

    return rcptContent.iterator();
  }
Пример #9
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;
  }
Пример #10
0
  /** {@inheritDoc} */
  public InvocationResponse invoke(MessageContext messageContext) throws AxisFault {
    if (log.isDebugEnabled()) {
      log.debug(
          "Starting Activation Handler invocation. Incoming Message: "
              + messageContext.getEnvelope().toString());
    }

    AxisService service = messageContext.getAxisService();
    int tenantId = getTenantId(messageContext);
    if (service != null && "ActivationService".equals(service.getName())) {
      log.debug("Granted access to the Activation Service");
      if (tenantId > 0) {
        TenantAxisUtils.getTenantAxisConfiguration(
            getTenantDomain(), messageContext.getConfigurationContext());
        log.debug("Loaded Tenant Configuration");
      }
      return InvocationResponse.CONTINUE;
    }
    if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
      log.debug("Granted access for super tenant");
      return InvocationResponse.CONTINUE;
    }
    if (ActivationManager.activationRecorded(tenantId)) {
      if (ActivationManager.getActivation(tenantId)) {
        TenantAxisUtils.getTenantAxisConfiguration(
            getTenantDomain(), messageContext.getConfigurationContext());
        log.debug("Loaded Tenant Configuration");
        return InvocationResponse.CONTINUE;
      } else {
        if (log.isWarnEnabled()) {
          String serviceName = Util.getServiceName();
          log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId);
        }
        return InvocationResponse.ABORT;
      }
    }
    String serviceName = Util.getServiceName();
    try {
      if (CloudServicesUtil.isCloudServiceActive(serviceName, tenantId)) {
        log.debug("Successful attempt to access " + serviceName + " by tenant " + tenantId);
        ActivationManager.setActivation(tenantId, true);
        TenantAxisUtils.getTenantAxisConfiguration(
            getTenantDomain(), messageContext.getConfigurationContext());
        log.debug("Loaded Tenant Configuration");
        return InvocationResponse.CONTINUE;
      }
    } catch (Exception e) {
      throw new AxisFault("Failed to determine Activation status.", e);
    }
    log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId);
    ActivationManager.setActivation(tenantId, false);
    return InvocationResponse.ABORT;
  }
 private boolean mediate(MessageContext synCtx, String format) {
   if (!isDoingXml(synCtx) && !isDoingJson(synCtx)) {
     log.error(
         "#mediate. Could not identify the payload format of the existing payload prior to mediate.");
     return false;
   }
   org.apache.axis2.context.MessageContext axis2MessageContext =
       ((Axis2MessageContext) synCtx).getAxis2MessageContext();
   StringBuffer result = new StringBuffer();
   StringBuffer resultCTX = new StringBuffer();
   regexTransformCTX(resultCTX, synCtx, format);
   replace(resultCTX.toString(), result, synCtx);
   String out = result.toString().trim();
   if (log.isDebugEnabled()) {
     log.debug("#mediate. Transformed payload format>>> " + out);
   }
   if (mediaType.equals(XML_TYPE)) {
     try {
       JsonUtil.removeJsonPayload(axis2MessageContext);
       OMElement omXML = AXIOMUtil.stringToOM(out);
       if (!checkAndReplaceEnvelope(
           omXML,
           synCtx)) { // check if the target of the PF 'format' is the entire SOAP envelop, not
                      // just the body.
         axis2MessageContext.getEnvelope().getBody().addChild(omXML.getFirstElement());
       }
     } catch (XMLStreamException e) {
       handleException("Error creating SOAP Envelope from source " + out, synCtx);
     }
   } else if (mediaType.equals(JSON_TYPE)) {
     JsonUtil.newJsonPayload(axis2MessageContext, out, true, true);
   } else if (mediaType.equals(TEXT_TYPE)) {
     JsonUtil.removeJsonPayload(axis2MessageContext);
     axis2MessageContext.getEnvelope().getBody().addChild(getTextElement(out));
   }
   // need to honour a content-type of the payload media-type as output from the payload
   // {re-merging patch https://wso2.org/jira/browse/ESBJAVA-3014}
   setContentType(synCtx);
   return true;
 }
Пример #12
0
  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());
  }
  /**
   * Determine the HttpStatusCodedepending on the message type processed <br>
   * (normal response versus fault response) as well as Axis2 message context properties set via
   * Synapse configuration or MessageBuilders.
   *
   * @see org.apache.synapse.transport.nhttp.NhttpConstants#FAULTS_AS_HTTP_200
   * @see org.apache.synapse.transport.nhttp.NhttpConstants#HTTP_SC
   * @param msgContext the Axis2 message context
   * @param response the HTTP response object
   * @return the HTTP status code to set in the HTTP response object
   */
  private int determineHttpStatusCode(MessageContext msgContext, HttpResponse response) {

    int httpStatus = HttpStatus.SC_OK;

    // retrieve original status code (if present)
    if (response.getStatusLine() != null) {
      httpStatus = response.getStatusLine().getStatusCode();
    }

    // if this is a dummy message to handle http 202 case with non-blocking IO
    // set the status code to 202
    if (msgContext.isPropertyTrue(NhttpConstants.SC_ACCEPTED)) {
      httpStatus = HttpStatus.SC_ACCEPTED;
    } else {

      // is this a fault message
      boolean handleFault =
          msgContext.getEnvelope().getBody().hasFault() || msgContext.isProcessingFault();

      // shall faults be transmitted with HTTP 200
      boolean faultsAsHttp200 =
          NhttpConstants.TRUE.equalsIgnoreCase(
              (String) msgContext.getProperty(NhttpConstants.FAULTS_AS_HTTP_200));

      // Set HTTP status code to 500 if this is a fault case and we shall not use HTTP 200
      if (handleFault && !faultsAsHttp200) {
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
      } else if (handleFault & faultsAsHttp200) {
        return HttpStatus.SC_OK;
      }

      /*
       * Any status code previously set shall be overwritten with the value of the following
       * message context property if it is set.
       */
      Object statusCode = msgContext.getProperty(NhttpConstants.HTTP_SC);
      if (statusCode != null) {
        try {
          httpStatus = Integer.parseInt(msgContext.getProperty(NhttpConstants.HTTP_SC).toString());
        } catch (NumberFormatException e) {
          log.warn(
              "Unable to set the HTTP status code from the property "
                  + NhttpConstants.HTTP_SC
                  + " with value: "
                  + statusCode);
        }
      }
    }

    return httpStatus;
  }
  @Override
  public InvocationResponse invoke(MessageContext messageContext) throws AxisFault {

    // get the counter property from the configuration context
    ConfigurationContext configurationContext = messageContext.getConfigurationContext();
    Integer count = (Integer) configurationContext.getProperty(OUTGOING_MESSAGE_COUNT_KEY);
    // increment the counter
    count = Integer.valueOf(count.intValue() + 1 + "");
    // set the new count back to the configuration context
    configurationContext.setProperty(OUTGOING_MESSAGE_COUNT_KEY, count);
    // print it out

    logger.info("The outgoing message count is now " + count);

    logger.info(messageContext.getEnvelope().toString());
    return InvocationResponse.CONTINUE;
  }
  private static MessageContext cloneForSend(MessageContext ori, String preserveAddressing)
      throws AxisFault {

    MessageContext newMC = MessageHelper.clonePartially(ori);

    newMC.setEnvelope(ori.getEnvelope());
    if (preserveAddressing != null && Boolean.parseBoolean(preserveAddressing)) {
      newMC.setMessageID(ori.getMessageID());
    } else {
      MessageHelper.removeAddressingHeaders(newMC);
    }

    newMC.setProperty(
        org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS,
        ori.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS));

    return newMC;
  }
Пример #16
0
  /**
   * Creates the content of a Non-Repudiation Of Receipt (NRR) Receipt as defined in section 5.1.8
   * of the AS4 profile.
   *
   * @param mc The current {@link MessageContext}, used to get copies of the <code>ds:Reference
   *     </code> elements
   * @return The content for the new Receipt represented as an iteration of <code>OMElement</code>s
   */
  protected Iterator<OMElement> createNRRContent(MessageContext mc) {
    ArrayList<OMElement> rcptContent = new ArrayList<OMElement>();
    // Get element factory for creating the elements in the Receipt content
    OMFactory elemFactory = mc.getEnvelope().getOMFactory();
    // Create the ebbp:NonRepudiationInformation container element
    OMElement ebbpNRIElement = elemFactory.createOMElement(QNAME_NRI_ELEM);
    ebbpNRIElement.declareNamespace(EBBP_NS, EBBP_NS_PREFIX);

    // Add a ebbp:MessagePartNRInformation for each reference found in Signature element of the
    // received message
    for (OMElement ref : SecurityUtils.getSignatureReferences(mc)) {
      OMElement ebbpMsgPart = elemFactory.createOMElement(QNAME_MSG_PART_ELEM);
      ebbpMsgPart.addChild(ref.cloneOMElement());
      ebbpNRIElement.addChild(ebbpMsgPart);
    }
    rcptContent.add(ebbpNRIElement);

    return rcptContent.iterator();
  }
 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());
    }
  }
Пример #19
0
  /**
   * Adds the appropriate properties to the MessageContext that the user will see
   *
   * @param soapMessageContext
   * @param jaxwsMessageContext
   */
  public static void addProperties(
      SOAPMessageContext soapMessageContext, MessageContext jaxwsMessageContext) {

    // Copy Axis2 MessageContext properties.  It's possible that some set of Axis2 handlers
    // have run and placed some properties in the context that need to be visible.
    soapMessageContext.putAll(jaxwsMessageContext.getProperties());

    EndpointDescription description = jaxwsMessageContext.getEndpointDescription();
    if (description != null) {
      // Set the WSDL properties
      ServiceDescription sd = description.getServiceDescription();
      if (sd != null) {
        String wsdlLocation = ((ServiceDescriptionWSDL) sd).getWSDLLocation();
        if (wsdlLocation != null && !"".equals(wsdlLocation)) {
          URI wsdlLocationURI = JavaUtils.createURI(wsdlLocation);
          if (wsdlLocationURI == null) {
            log.warn(
                Messages.getMessage(
                    "addPropertiesErr",
                    wsdlLocation.toString(),
                    description.getServiceQName().toString()));
          }
          setProperty(
              soapMessageContext,
              javax.xml.ws.handler.MessageContext.WSDL_DESCRIPTION,
              wsdlLocationURI,
              true);
        }
        setProperty(
            soapMessageContext,
            javax.xml.ws.handler.MessageContext.WSDL_SERVICE,
            description.getServiceQName(),
            true);
      }
    }

    // Lazily provide a list of available reference parameters.
    org.apache.axis2.context.MessageContext msgContext =
        jaxwsMessageContext.getAxisMessageContext();
    SOAPHeader header = null;
    if (msgContext != null && msgContext.getEnvelope() != null) {
      header = msgContext.getEnvelope().getHeader();
    }
    List<Element> list = new ReferenceParameterList(header);

    setProperty(soapMessageContext, javax.xml.ws.handler.MessageContext.REFERENCE_PARAMETERS, list);
    if (log.isDebugEnabled()) {
      log.debug("Added reference parameter list.");
    }

    // If we are running within a servlet container, then JAX-WS requires that the
    // servlet related properties be set on the MessageContext
    ServletContext servletContext =
        (ServletContext) jaxwsMessageContext.getProperty(HTTPConstants.MC_HTTP_SERVLETCONTEXT);
    if (servletContext != null) {
      log.debug("Servlet Context Set");
      setProperty(
          soapMessageContext, javax.xml.ws.handler.MessageContext.SERVLET_CONTEXT, servletContext);
    } else {
      log.debug("Servlet Context not found");
    }

    HttpServletRequest req =
        (HttpServletRequest) jaxwsMessageContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
    if (req == null) {
      if (log.isDebugEnabled()) {
        log.debug("HTTPServletRequest not found");
      }
    } else {
      setProperty(soapMessageContext, javax.xml.ws.handler.MessageContext.SERVLET_REQUEST, req);
      if (log.isDebugEnabled()) {
        log.debug("SERVLET_REQUEST Set");
      }

      String pathInfo = null;
      try {
        pathInfo = req.getPathInfo();
      } catch (Throwable t) {
        log.debug("exception in getPathInfo", t);
      }
      setProperty(soapMessageContext, javax.xml.ws.handler.MessageContext.PATH_INFO, pathInfo);
      if (log.isDebugEnabled()) {
        if (pathInfo != null) {
          log.debug("HTTP_REQUEST_PATHINFO Set");
        } else {
          log.debug("HTTP_REQUEST_PATHINFO not found");
        }
      }
      String queryString = req.getQueryString();
      setProperty(
          soapMessageContext, javax.xml.ws.handler.MessageContext.QUERY_STRING, queryString);
      if (log.isDebugEnabled()) {
        if (queryString != null) {
          log.debug("HTTP_REQUEST_QUERYSTRING Set");
        } else {
          log.debug("HTTP_REQUEST_QUERYSTRING not found");
        }
      }
      String method = req.getMethod();
      setProperty(
          soapMessageContext, javax.xml.ws.handler.MessageContext.HTTP_REQUEST_METHOD, method);
      if (log.isDebugEnabled()) {
        if (method != null) {
          log.debug("HTTP_REQUEST_METHOD Set");
        } else {
          log.debug("HTTP_REQUEST_METHOD not found");
        }
      }
    }
    HttpServletResponse res =
        (HttpServletResponse)
            jaxwsMessageContext.getProperty(HTTPConstants.MC_HTTP_SERVLETRESPONSE);
    if (res == null) {
      if (log.isDebugEnabled()) {
        log.debug("Servlet Response not found");
      }
    } else {
      setProperty(soapMessageContext, javax.xml.ws.handler.MessageContext.SERVLET_RESPONSE, res);
      if (log.isDebugEnabled()) {
        log.debug("SERVLET_RESPONSE Set");
      }
    }
  }
  /**
   * 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);
      }
    }
  }
  /**
   * 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) throws AxisFault {

    Object obj = null;
    try {

      String in_action = msgContext.getWSAAction();

      if (logger.isDebugEnabled()) {
        logger.debug("In MEP: in_action = " + in_action);
      }

      validate_action(msgContext);

      // get the implementation class for the Web Service

      obj = getTheImplementationObject(msgContext);

      // make return message context available to service
      if (obj instanceof AppendixV) {
        AppendixV xo = (AppendixV) obj;
      }

    } catch (Exception e) {

      logger.error(
          "Error in XDSRawXMLIn:\n"
              + ExceptionUtil.exception_details(e)
              + "\ngetSoapAction = "
              + msgContext.getSoapAction());

      throw AxisFault.makeFault(e);
    }

    // find the WebService method

    Class implClass = obj.getClass();

    AxisOperation opDesc = msgContext.getAxisOperation();

    Method method = findOperation(opDesc, implClass);

    Method methodDisplay;
    try {
      methodDisplay =
          implClass.getMethod("setMessageContextIn", new Class[] {MessageContext.class});
    } catch (SecurityException e) {
      logger.error(
          "Error in XDSRawXMLIn:\n"
              + "class is "
              + implClass.getName()
              + " method is setMessageContextIn"
              + ExceptionUtil.exception_details(e)
              + "\ngetSoapAction = "
              + msgContext.getSoapAction());

      throw AxisFault.makeFault(e);
    } catch (NoSuchMethodException e) {
      logger.error(
          "Error in XDSRawXMLIn:\n"
              + "class is "
              + implClass.getName()
              + " method is setMessageContextIn"
              + ExceptionUtil.exception_details(e)
              + "\ngetSoapAction = "
              + msgContext.getSoapAction());

      throw AxisFault.makeFault(e);
    }

    try {
      methodDisplay.invoke(obj, new Object[] {msgContext});
    } catch (Exception e) {
      logger.error(
          "Error in XDSRawXMLIn:\n"
              + "class is "
              + implClass.getName()
              + " method is setMessageContextIn"
              + ExceptionUtil.exception_details(e)
              + "\ngetSoapAction = "
              + msgContext.getSoapAction());

      throw AxisFault.makeFault(e);
    }

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

    try {
      method.invoke(obj, new Object[] {msgContext.getEnvelope().getBody().getFirstElement()});

    } catch (Exception e) {
      logger.error(
          "Error in XDSRawXMLIn:\n"
              + "class is "
              + implClass.getName()
              + " method is setMessageContextIn"
              + ExceptionUtil.exception_details(e)
              + "\ngetSoapAction = "
              + msgContext.getSoapAction());

      throw AxisFault.makeFault(e);
    }
  }
  /**
   * Handle the response or error (during a failed send) message received for an outgoing request
   *
   * @param messageID Request message ID
   * @param response the Axis2 MessageContext that has been received and has to be handled
   * @param synapseOutMsgCtx the corresponding (outgoing) Synapse MessageContext for the above Axis2
   *     MC, that holds Synapse specific information such as the error handler stack and local
   *     properties etc.
   * @throws AxisFault if the message cannot be processed
   */
  private void handleMessage(
      String messageID,
      MessageContext response,
      org.apache.synapse.MessageContext synapseOutMsgCtx,
      AsyncCallback callback)
      throws AxisFault {
    // apply the tenant information to the out message context
    TenantInfoConfigurator configurator =
        synapseOutMsgCtx.getEnvironment().getTenantInfoConfigurator();
    if (configurator != null) {
      configurator.applyTenantInfo(synapseOutMsgCtx);
    }
    Object o = response.getProperty(SynapseConstants.SENDING_FAULT);
    if (o != null && Boolean.TRUE.equals(o)) {

      StatisticsReporter.reportFaultForAll(
          synapseOutMsgCtx, ErrorLogFactory.createErrorLog(response));
      // there is a sending fault. propagate the fault to fault handlers.

      Stack faultStack = synapseOutMsgCtx.getFaultStack();
      if (faultStack != null && !faultStack.isEmpty()) {

        // if we have access to the full synapseOutMsgCtx.getEnvelope(), then let
        // it flow with the error details. Else, replace its envelope with the
        // fault envelope
        try {
          synapseOutMsgCtx.getEnvelope().build();
        } catch (OMException x) {
          synapseOutMsgCtx.setEnvelope(response.getEnvelope());
        }

        Exception e = (Exception) response.getProperty(SynapseConstants.ERROR_EXCEPTION);

        synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
        synapseOutMsgCtx.setProperty(
            SynapseConstants.ERROR_CODE, response.getProperty(SynapseConstants.ERROR_CODE));
        synapseOutMsgCtx.setProperty(
            SynapseConstants.ERROR_MESSAGE, response.getProperty(SynapseConstants.ERROR_MESSAGE));
        synapseOutMsgCtx.setProperty(
            SynapseConstants.ERROR_DETAIL, response.getProperty(SynapseConstants.ERROR_DETAIL));
        synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, e);

        if (log.isDebugEnabled()) {
          log.debug(
              "[Failed Request Message ID : "
                  + messageID
                  + "]"
                  + " [New to be Retried Request Message ID : "
                  + synapseOutMsgCtx.getMessageID()
                  + "]");
        }

        int errorCode = (Integer) response.getProperty(SynapseConstants.ERROR_CODE);

        // If a timeout has occured and the timeout action of the callback is to discard the message
        if (errorCode == SynapseConstants.NHTTP_CONNECTION_TIMEOUT
            && callback.getTimeOutAction() == SynapseConstants.DISCARD) {
          // Do not execute any fault sequences. Discard message
          if (log.isWarnEnabled()) {
            log.warn(
                "Synapse timed out for the request with Message ID : "
                    + messageID
                    + ". Ignoring fault handlers since the timeout action is DISCARD");
          }
          faultStack.removeAllElements();
        } else {
          ((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx, null);
        }
      }

    } else {

      // there can always be only one instance of an Endpoint in the faultStack of a message
      // if the send was successful, so remove it before we proceed any further
      Stack faultStack = synapseOutMsgCtx.getFaultStack();

      Endpoint successfulEndpoint = null;
      if (faultStack != null && !faultStack.isEmpty() && faultStack.peek() instanceof Endpoint) {
        successfulEndpoint = (Endpoint) faultStack.pop();
      }

      if (log.isDebugEnabled()) {
        log.debug("Synapse received an asynchronous response message");
        log.debug(
            "Received To: " + (response.getTo() != null ? response.getTo().getAddress() : "null"));
        log.debug(
            "SOAPAction: "
                + (response.getSoapAction() != null ? response.getSoapAction() : "null"));
        log.debug(
            "WSA-Action: " + (response.getWSAAction() != null ? response.getWSAAction() : "null"));
        String[] cids = response.getAttachmentMap().getAllContentIDs();
        if (cids != null && cids.length > 0) {
          for (String cid : cids) {
            log.debug("Attachment : " + cid);
          }
        }
        log.debug("Body : \n" + response.getEnvelope());
      }
      MessageContext axisOutMsgCtx =
          ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();

      // Processes 'Accept-Encoding'
      ResponseAcceptEncodingProcessor.process(response, axisOutMsgCtx);

      response.setServiceContext(null);
      response.setOperationContext(axisOutMsgCtx.getOperationContext());
      response.setAxisMessage(
          axisOutMsgCtx.getAxisOperation().getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE));

      // set properties on response
      response.setServerSide(true);
      response.setProperty(SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
      response.setProperty(
          MessageContext.TRANSPORT_OUT, axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
      response.setProperty(
          org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
          axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
      response.setTransportIn(axisOutMsgCtx.getTransportIn());
      response.setTransportOut(axisOutMsgCtx.getTransportOut());

      // If request is REST assume that the response is REST too
      response.setDoingREST(axisOutMsgCtx.isDoingREST());
      if (axisOutMsgCtx.isDoingMTOM()) {
        response.setDoingMTOM(true);
        response.setProperty(
            org.apache.axis2.Constants.Configuration.ENABLE_MTOM,
            org.apache.axis2.Constants.VALUE_TRUE);
      }
      if (axisOutMsgCtx.isDoingSwA()) {
        response.setDoingSwA(true);
        response.setProperty(
            org.apache.axis2.Constants.Configuration.ENABLE_SWA,
            org.apache.axis2.Constants.VALUE_TRUE);
      }

      // when axis2 receives a soap message without addressing headers it users
      // DISABLE_ADDRESSING_FOR_OUT_MESSAGES property to keep it and hence avoid addressing
      // headers on the response. this causes a problem for synapse if the original message
      // it receivs (from client) has addressing and the synaspse service invocation has not
      // engage addressing. in this case when synapse receives the response from the server
      // addessing In handler dissable addressing since that response does not have addressing
      // headers. synapse sends the response to its orignal client using the same message
      // context. Then this response does not have addressing headers since it already
      // disable. to avoid this we need to set the DISABLE_ADDRESSING_FOR_OUT_MESSAGES
      // property state to original state.
      if (axisOutMsgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES)
          != null) {

        response.setProperty(
            AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES,
            axisOutMsgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES));
      } else {
        response.removeProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES);
      }

      Object messageType =
          axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
      if (!HTTPConstants.MEDIA_TYPE_X_WWW_FORM.equals(messageType)) {
        // copy the message type property that's used by the out message to the
        // response message
        response.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, messageType);
      }

      // compare original received message (axisOutMsgCtx) soap version with the response
      // if they are different change to original version
      if (axisOutMsgCtx.isSOAP11() != response.isSOAP11()) {
        if (axisOutMsgCtx.isSOAP11()) {
          SOAPUtils.convertSOAP12toSOAP11(response);
        } else {
          SOAPUtils.convertSOAP11toSOAP12(response);
        }
      }

      if (axisOutMsgCtx.getMessageID() != null) {
        response.setRelationships(new RelatesTo[] {new RelatesTo(axisOutMsgCtx.getMessageID())});
      }

      response.setReplyTo(axisOutMsgCtx.getReplyTo());
      response.setFaultTo(axisOutMsgCtx.getFaultTo());

      if (axisOutMsgCtx.isPropertyTrue(NhttpConstants.IGNORE_SC_ACCEPTED)) {
        response.setProperty(NhttpConstants.FORCE_SC_ACCEPTED, Constants.VALUE_TRUE);
      }

      // create the synapse message context for the response
      Axis2MessageContext synapseInMessageContext =
          new Axis2MessageContext(
              response, synapseOutMsgCtx.getConfiguration(), synapseOutMsgCtx.getEnvironment());
      synapseInMessageContext.setResponse(true);

      Object obj = synapseOutMsgCtx.getProperty(SynapseConstants.FORCE_ERROR_PROPERTY);
      String errorOnSOAPFault = (String) obj;

      if (Constants.VALUE_TRUE.equals(errorOnSOAPFault) && successfulEndpoint != null) {

        if (log.isDebugEnabled()) {
          log.debug("FORCE_ERROR_ON_SOAP_FAULT is true, checking for SOAPFault");
        }

        try {
          RelayUtils.buildMessage(
              ((Axis2MessageContext) synapseInMessageContext).getAxis2MessageContext(), true);
        } catch (Exception e) {
          // handleException("Error while building message", e, synapseInMessageContext);
        }

        if ((synapseInMessageContext.getEnvelope() != null)
            && synapseInMessageContext.getEnvelope().hasFault()) {

          if (log.isDebugEnabled()) {
            log.debug(
                "SOAPFault found in response message, forcing endpoint "
                    + successfulEndpoint.getName()
                    + " to fail");
          }

          // setup new pipe configuration..if failure happens (this will be setup as the source
          // writer and during the TargetContext
          // clean up operation the writer will be reset and pull to the buffer
          MessageContext axis2OUTMC =
              ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
          NHttpServerConnection conn =
              (NHttpServerConnection) axis2OUTMC.getProperty("pass-through.Source-Connection");
          if (conn != null) {
            SourceConfiguration sourceConfiguration =
                (SourceConfiguration) axis2OUTMC.getProperty("PASS_THROUGH_SOURCE_CONFIGURATION");
            Pipe pipe =
                new Pipe(
                    conn,
                    sourceConfiguration.getBufferFactory().getBuffer(),
                    "source",
                    sourceConfiguration);
            axis2OUTMC.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
          }

          StatisticsReporter.reportFaultForAll(
              synapseOutMsgCtx, ErrorLogFactory.createErrorLog(response));
          synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
          synapseOutMsgCtx.setProperty(
              SynapseConstants.ERROR_CODE, SynapseConstants.ENDPOINT_CUSTOM_ERROR);
          ((FaultHandler) successfulEndpoint).handleFault(synapseOutMsgCtx, null);
          return;
        } else {
          successfulEndpoint.onSuccess();
        }

      } else if (successfulEndpoint != null) {
        successfulEndpoint.onSuccess();
      }

      synapseInMessageContext.setTo(
          new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL));
      synapseInMessageContext.setTracingState(synapseOutMsgCtx.getTracingState());

      // set the properties of the original MC to the new MC

      for (Object key : synapseOutMsgCtx.getPropertyKeySet()) {
        synapseInMessageContext.setProperty(
            (String) key, synapseOutMsgCtx.getProperty((String) key));
      }

      // Copy SequenceCallStack from original MC to the new MC
      if (synapseOutMsgCtx.isContinuationEnabled()) {

        // Set the message direction
        if (!synapseOutMsgCtx.isResponse()) {
          synapseInMessageContext.setResponse(false);
        }

        Stack<ContinuationState> seqContinuationStates =
            synapseOutMsgCtx.getContinuationStateStack();
        for (int i = 0; i < seqContinuationStates.size(); i++) {
          synapseInMessageContext.pushContinuationState(seqContinuationStates.get(i));
        }
      }

      // If this response is related to session affinity endpoints -Server initiated session
      Dispatcher dispatcher =
          (Dispatcher)
              synapseOutMsgCtx.getProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_DISPATCHER);
      if (dispatcher != null && dispatcher.isServerInitiatedSession()) {
        dispatcher.updateSession(synapseInMessageContext);
      }

      StatisticsReporter.reportForAllOnResponseReceived(synapseInMessageContext);

      // send the response message through the synapse mediation flow
      try {
        synapseOutMsgCtx.getEnvironment().injectMessage(synapseInMessageContext);
      } catch (SynapseException syne) {
        Stack stack = synapseInMessageContext.getFaultStack();
        if (stack != null && !stack.isEmpty()) {
          ((FaultHandler) stack.pop()).handleFault(synapseInMessageContext, syne);
        } else {
          log.error(
              "Synapse encountered an exception, "
                  + "No error handlers found - [Message Dropped]\n"
                  + syne.getMessage());
        }
      }
    }
  }
  public void invokeBusinessLogic(
      org.apache.axis2.context.MessageContext msgContext,
      org.apache.axis2.context.MessageContext newMsgContext)
      throws org.apache.axis2.AxisFault {

    try {

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

      SiteSkeletonInterface skel = (SiteSkeletonInterface) obj;
      // Out Envelop
      org.apache.axiom.soap.SOAPEnvelope envelope = null;
      // Find the axisOperation that has been set by the Dispatch phase.
      org.apache.axis2.description.AxisOperation op =
          msgContext.getOperationContext().getAxisOperation();
      if (op == null) {
        throw new org.apache.axis2.AxisFault(
            "Operation is not located, if this is doclit style the SOAP-ACTION should specified via the SOAP Action to use the RawXMLProvider");
      }

      java.lang.String methodName;
      if ((op.getName() != null)
          && ((methodName =
                  org.apache.axis2.util.JavaUtils.xmlNameToJavaIdentifier(
                      op.getName().getLocalPart()))
              != null)) {

        if ("passInfo".equals(methodName)) {

          org.example.www.site.PassInfoResponse passInfoResponse9 = null;
          org.example.www.site.PassInfo wrappedParam =
              (org.example.www.site.PassInfo)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.example.www.site.PassInfo.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          passInfoResponse9 = skel.passInfo(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), passInfoResponse9, false);
        } else if ("searchSite".equals(methodName)) {

          org.example.www.site.SearchSiteResponse searchSiteResponse11 = null;
          org.example.www.site.SearchSite wrappedParam =
              (org.example.www.site.SearchSite)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.example.www.site.SearchSite.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          searchSiteResponse11 = skel.searchSite(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), searchSiteResponse11, false);
        } else if ("getSite".equals(methodName)) {

          org.example.www.site.GetSiteResponse getSiteResponse13 = null;
          org.example.www.site.GetSite wrappedParam =
              (org.example.www.site.GetSite)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.example.www.site.GetSite.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getSiteResponse13 = skel.getSite(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), getSiteResponse13, false);
        } else if ("parallelInfo".equals(methodName)) {

          org.example.www.site.ParallelInfoResponse parallelInfoResponse15 = null;
          org.example.www.site.ParallelInfo wrappedParam =
              (org.example.www.site.ParallelInfo)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.example.www.site.ParallelInfo.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          parallelInfoResponse15 = skel.parallelInfo(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), parallelInfoResponse15, false);

        } else {
          throw new java.lang.RuntimeException("method not found");
        }

        newMsgContext.setEnvelope(envelope);
      }
    } catch (java.lang.Exception e) {
      throw org.apache.axis2.AxisFault.makeFault(e);
    }
  }
  /**
   * 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());
    }
  }
Пример #25
0
  public InvocationResponse invoke(MessageContext messageContext) throws AxisFault {

    int tenantID = PublisherUtil.getTenantId(messageContext);

    Map<Integer, EventingConfigData> tenantSpecificEventConfig =
        TenantEventConfigData.getTenantSpecificEventingConfigData();
    EventingConfigData eventingConfigData = tenantSpecificEventConfig.get(tenantID);

    if (eventingConfigData != null && eventingConfigData.isMessageTracingEnable()) {

      if (log.isDebugEnabled()) {
        log.debug("Message tracing enabled.");
      }

      AxisService service = messageContext.getAxisService();

      // Temporary fix for track API manager calls
      if (service == null
          || (SystemFilter.isFilteredOutService(service.getAxisServiceGroup())
              && !AgentUtil.allowedServices(service.getName()))
          || service.isClientSide()) {
        return InvocationResponse.CONTINUE;
      } else {

        String activityUUID = HandlerUtils.getUniqueId();
        Object transportHeaders = messageContext.getProperty(MessageContext.TRANSPORT_HEADERS);

        if (transportHeaders != null) {
          String aid = (String) ((Map) transportHeaders).get(MessageTracerConstants.ACTIVITY_ID);
          if (aid != null) {
            if (aid.equals(MessageTracerConstants.EMPTY_STRING)) {
              ((Map) messageContext.getProperty(MessageContext.TRANSPORT_HEADERS))
                  .put(MessageTracerConstants.ACTIVITY_ID, activityUUID);
              if (log.isDebugEnabled()) {
                log.debug("Propagated AID was empty, IN generating new AID");
              }
            } else {
              activityUUID = aid;
              if (log.isDebugEnabled()) {
                log.debug("IN using propagated AID");
              }
            }
          } else {
            ((Map) messageContext.getProperty(MessageContext.TRANSPORT_HEADERS))
                .put(MessageTracerConstants.ACTIVITY_ID, activityUUID);
            if (log.isDebugEnabled()) {
              log.debug("Propagated AID was null, IN generating new AID");
            }
          }
        } else {
          Map<String, String> headers = new TreeMap<String, String>();
          headers.put(MessageTracerConstants.ACTIVITY_ID, activityUUID);
          messageContext.setProperty(MessageContext.TRANSPORT_HEADERS, headers);
          if (log.isDebugEnabled()) {
            log.debug("Transport headers absent, IN generating new AID");
          }
        }

        messageContext.setProperty(MessageTracerConstants.TENANT_ID, tenantID);

        TracingInfo tracingInfo = new TracingInfo();
        tracingInfo.setActivityId(activityUUID);
        tracingInfo.setServer(AgentUtil.getServerName());
        tracingInfo.setMessageDirection(BAMDataPublisherConstants.IN_DIRECTION);
        tracingInfo.setHost(PublisherUtil.getHostAddress());
        tracingInfo.setServiceName(messageContext.getAxisService().getName());
        tracingInfo.setOperationName(messageContext.getAxisOperation().getName().getLocalPart());
        MessageContext inMessageContext =
            messageContext.getOperationContext().getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN);
        if (inMessageContext != null) {
          Object requestProperty =
              inMessageContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
          AgentUtil.extractInfoFromHttpHeaders(tracingInfo, requestProperty);
        }

        try {
          if (eventingConfigData.isDumpBodyEnable()) {
            try {
              Class cls =
                  Class.forName(
                      MessageTracerConstants
                          .ORG_APACHE_SYNAPSE_TRANSPORT_PASSTHRU_UTIL_RELAY_UTILS_CLASS_NAME);
              Class[] paramClasses = new Class[] {MessageContext.class, Boolean.TYPE};
              Method method =
                  cls.getMethod(MessageTracerConstants.BUILD_MESSAGE_METHOD_NAME, paramClasses);
              method.invoke(null, messageContext, false);
            } catch (ClassNotFoundException ignore) {
              // ignore
            } catch (Exception e) {
              throw new AxisFault("Error in building input message: " + e.getMessage(), e);
            }
            SOAPEnvelope soapEnvelope = messageContext.getEnvelope();
            SOAPBody body = soapEnvelope.getBody();
            if (body != null) {
              tracingInfo.setPayload(body.toString());
            }

            SOAPHeader header = soapEnvelope.getHeader();
            if (header != null) {
              tracingInfo.setHeader(header.toString());
            }
          }

          tracingInfo.setTimestamp(System.currentTimeMillis());

          if (MessageContext.IN_FLOW == messageContext.getFLOW()) {
            tracingInfo.setStatus(MessageTracerConstants.STATUS_SUCCESS);
          } else if (MessageContext.IN_FAULT_FLOW == messageContext.getFLOW()) {
            tracingInfo.setStatus(MessageTracerConstants.STATUS_FAULT);
          }

          publisher.publish(tenantID, tracingInfo);
        } catch (OMException e) {
          log.error("Unable to get SOAP details " + e.getMessage(), e);
        }
      }
    }
    return InvocationResponse.CONTINUE;
  }
  public void receive(org.apache.axis2.context.MessageContext mc) throws AxisFault {

    boolean traceOn = proxy.getAspectConfiguration().isTracingEnabled();
    boolean traceOrDebugOn = traceOn || log.isDebugEnabled();

    CustomLogSetter.getInstance().setLogAppender(proxy.getArtifactContainerName());

    String remoteAddr =
        (String) mc.getProperty(org.apache.axis2.context.MessageContext.REMOTE_ADDR);

    if (traceOrDebugOn) {
      traceOrDebug(
          traceOn,
          "Proxy Service "
              + name
              + " received a new message"
              + (remoteAddr != null ? " from : " + remoteAddr : "..."));
      traceOrDebug(
          traceOn, ("Message To: " + (mc.getTo() != null ? mc.getTo().getAddress() : "null")));
      traceOrDebug(
          traceOn, ("SOAPAction: " + (mc.getSoapAction() != null ? mc.getSoapAction() : "null")));
      traceOrDebug(
          traceOn, ("WSA-Action: " + (mc.getWSAAction() != null ? mc.getWSAAction() : "null")));

      if (traceOn && trace.isTraceEnabled()) {
        String[] cids = mc.getAttachmentMap().getAllContentIDs();
        if (cids != null && cids.length > 0) {
          for (String cid : cids) {
            trace.trace("With attachment content ID : " + cid);
          }
        }
        trace.trace("Envelope : " + mc.getEnvelope());
      }
    }

    MessageContext synCtx = MessageContextCreatorForAxis2.getSynapseMessageContext(mc);
    Integer statisticReportingIndex = null;
    // Statistic reporting
    boolean isStatisticsEnabled = RuntimeStatisticCollector.isStatisticsEnabled();
    if (isStatisticsEnabled) {
      statisticReportingIndex =
          OpenEventCollector.reportEntryEvent(
              synCtx, this.name, proxy.getAspectConfiguration(), ComponentType.PROXYSERVICE);
    }

    Object inboundServiceParam =
        proxy.getParameterMap().get(SynapseConstants.INBOUND_PROXY_SERVICE_PARAM);
    Object inboundMsgCtxParam = mc.getProperty(SynapseConstants.IS_INBOUND);

    // check whether the message is from Inbound EP
    if (inboundMsgCtxParam == null || !(boolean) inboundMsgCtxParam) {
      // check whether service parameter is set to true or null, then block this request
      if (inboundServiceParam != null && (Boolean.valueOf((String) inboundServiceParam))) {
        /*
        return because same proxy is exposed via InboundEP and service parameter(inbound.only) is set to
        true, which disable normal http transport proxy
        */
        if (!synCtx.getFaultStack().isEmpty()) {
          if (log.isDebugEnabled()) {
            log.debug(
                "Executing fault handler - message discarded due to the proxy is allowed only via InboundEP");
          }
          (synCtx.getFaultStack().pop())
              .handleFault(
                  synCtx,
                  new Exception(
                      "Proxy Service "
                          + name
                          + " message discarded due to the proxy is allowed only via InboundEP"));
        } else {
          if (log.isDebugEnabled()) {
            log.debug(
                "Proxy Service "
                    + name
                    + " message discarded due to the proxy is "
                    + "allowed only via InboundEP");
          }
        }
        return;
      }
    }

    TenantInfoConfigurator configurator = synCtx.getEnvironment().getTenantInfoConfigurator();
    if (configurator != null) {
      configurator.extractTenantInfo(synCtx);
    }
    TransportInDescription trpInDesc = mc.getTransportIn();
    if (trpInDesc != null) {
      synCtx.setProperty(SynapseConstants.TRANSPORT_IN_NAME, trpInDesc.getName());
    }

    // get service log for this message and attach to the message context also set proxy name
    Log serviceLog = LogFactory.getLog(SynapseConstants.SERVICE_LOGGER_PREFIX + name);
    ((Axis2MessageContext) synCtx).setServiceLog(serviceLog);

    synCtx.setProperty(SynapseConstants.PROXY_SERVICE, name);
    //        synCtx.setTracingState(proxy.getTraceState());

    synCtx.setProperty(SynapseConstants.IS_CLIENT_DOING_REST, mc.isDoingREST());
    synCtx.setProperty(SynapseConstants.IS_CLIENT_DOING_SOAP11, mc.isSOAP11());

    try {
      if (synCtx.getEnvironment().isDebuggerEnabled()) {
        SynapseDebugManager debugManager = synCtx.getEnvironment().getSynapseDebugManager();
        debugManager.acquireMediationFlowLock();
        debugManager.advertiseMediationFlowStartPoint(synCtx);
        if (!synCtx.isResponse()) {
          SynapseWireLogHolder wireLogHolder =
              (SynapseWireLogHolder)
                  ((Axis2MessageContext) synCtx)
                      .getAxis2MessageContext()
                      .getProperty(SynapseDebugInfoHolder.SYNAPSE_WIRE_LOG_HOLDER_PROPERTY);
          if (wireLogHolder == null) {
            wireLogHolder = new SynapseWireLogHolder();
          }
          if (synCtx.getProperty(SynapseConstants.PROXY_SERVICE) != null
              && !synCtx.getProperty(SynapseConstants.PROXY_SERVICE).toString().isEmpty()) {
            wireLogHolder.setProxyName(
                synCtx.getProperty(SynapseConstants.PROXY_SERVICE).toString());
          }
          ((Axis2MessageContext) synCtx)
              .getAxis2MessageContext()
              .setProperty(SynapseDebugInfoHolder.SYNAPSE_WIRE_LOG_HOLDER_PROPERTY, wireLogHolder);
        }
      }
      synCtx.setProperty(SynapseConstants.RESPONSE_STATE, new ResponseState());
      List handlers = synCtx.getEnvironment().getSynapseHandlers();
      Iterator<SynapseHandler> iterator = handlers.iterator();
      while (iterator.hasNext()) {
        SynapseHandler handler = iterator.next();
        if (!handler.handleRequestInFlow(synCtx)) {
          return;
        }
      }

      Mediator mandatorySeq = synCtx.getConfiguration().getMandatorySequence();
      if (mandatorySeq != null) {
        if (log.isDebugEnabled()) {
          log.debug(
              "Start mediating the message in the "
                  + "pre-mediate state using the mandatory sequence");
        }

        if (!mandatorySeq.mediate(synCtx)) {
          if (log.isDebugEnabled()) {
            log.debug(
                "Request message for the proxy service "
                    + name
                    + " dropped in "
                    + "the pre-mediation state by the mandatory sequence : \n"
                    + synCtx);
          }
          return;
        }
      }

      // setup fault sequence - i.e. what happens when something goes wrong with this message
      proxy.registerFaultHandler(synCtx);

      boolean inSequenceResult = true;

      // Using inSequence for the incoming message mediation
      if (proxy.getTargetInSequence() != null) {

        Mediator inSequence = synCtx.getSequence(proxy.getTargetInSequence());
        if (inSequence != null) {
          traceOrDebug(
              traceOn,
              "Using sequence named : "
                  + proxy.getTargetInSequence()
                  + " for incoming message mediation");
          inSequenceResult = inSequence.mediate(synCtx);

        } else {
          handleException("Unable to find in-sequence : " + proxy.getTargetInSequence(), synCtx);
        }

      } else if (proxy.getTargetInLineInSequence() != null) {
        traceOrDebug(
            traceOn, "Using the anonymous " + "in-sequence of the proxy service for mediation");
        inSequenceResult = proxy.getTargetInLineInSequence().mediate(synCtx);
      }

      // if inSequence returns true, forward message to endpoint
      if (inSequenceResult) {
        if (proxy.getTargetEndpoint() != null) {
          Endpoint endpoint = synCtx.getEndpoint(proxy.getTargetEndpoint());

          if (endpoint != null) {
            traceOrDebug(
                traceOn, "Forwarding message to the endpoint : " + proxy.getTargetEndpoint());
            endpoint.send(synCtx);

          } else {
            handleException(
                "Unable to find the endpoint specified : " + proxy.getTargetEndpoint(), synCtx);
          }

        } else if (proxy.getTargetInLineEndpoint() != null) {
          traceOrDebug(
              traceOn,
              "Forwarding the message to the anonymous " + "endpoint of the proxy service");
          proxy.getTargetInLineEndpoint().send(synCtx);
        }
      }

    } catch (SynapseException syne) {

      if (!synCtx.getFaultStack().isEmpty()) {
        warn(traceOn, "Executing fault handler due to exception encountered", synCtx);
        ((FaultHandler) synCtx.getFaultStack().pop()).handleFault(synCtx, syne);

      } else {
        warn(
            traceOn,
            "Exception encountered but no fault handler found - " + "message dropped",
            synCtx);
      }
    } finally {
      // Statistic reporting
      if (isStatisticsEnabled) {
        CloseEventCollector.tryEndFlow(
            synCtx, this.name, ComponentType.PROXYSERVICE, statisticReportingIndex, true);
      }
      if (synCtx.getEnvironment().isDebuggerEnabled()) {
        SynapseDebugManager debugManager = synCtx.getEnvironment().getSynapseDebugManager();
        debugManager.advertiseMediationFlowTerminatePoint(synCtx);
        debugManager.releaseMediationFlowLock();
      }
    }
  }
Пример #27
0
  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);
      }
    }
  }
  public boolean dispatch(MessageContext messageContext) {

    if (log.isDebugEnabled()) {
      log.debug(
          "Sending the message to client with message processor ["
              + messageProcessor.getName()
              + "]");
    }

    // The below code is just for keeping the backward compatibility with the old code.
    if (targetEndpoint == null) {
      targetEndpoint =
          (String) messageContext.getProperty(ForwardingProcessorConstants.TARGET_ENDPOINT);
    }

    MessageContext outCtx = null;
    SOAPEnvelope originalEnvelop = messageContext.getEnvelope();

    if (targetEndpoint != null) {
      Endpoint ep = messageContext.getEndpoint(targetEndpoint);

      try {

        // Send message to the client
        while (!isSuccessful && !isTerminated) {
          try {
            // For each retry we need to have a fresh copy of the actual message. otherwise retry
            // may not
            // work as expected.
            messageContext.setEnvelope(MessageHelper.cloneSOAPEnvelope(originalEnvelop));
            OMElement firstChild = null; //
            org.apache.axis2.context.MessageContext origAxis2Ctx =
                ((Axis2MessageContext) messageContext).getAxis2MessageContext();
            if (JsonUtil.hasAJsonPayload(origAxis2Ctx)) {
              firstChild = origAxis2Ctx.getEnvelope().getBody().getFirstElement();
            } // Had to do this because MessageHelper#cloneSOAPEnvelope does not clone
            // OMSourcedElemImpl correctly.
            if (JsonUtil.hasAJsonPayload(firstChild)) { //
              OMElement clonedFirstElement =
                  messageContext.getEnvelope().getBody().getFirstElement();
              if (clonedFirstElement != null) {
                clonedFirstElement.detach();
                messageContext.getEnvelope().getBody().addChild(firstChild);
              }
            } // Had to do this because MessageHelper#cloneSOAPEnvelope does not clone
            // OMSourcedElemImpl correctly.
            origAxis2Ctx.setProperty(
                HTTPConstants.NON_ERROR_HTTP_STATUS_CODES, getNonRetryStatusCodes());
            outCtx = sender.send(ep, messageContext);
            isSuccessful = true;

          } catch (Exception e) {

            // this means send has failed due to some reason so we have to retry it
            if (e instanceof SynapseException) {
              isSuccessful = isNonRetryErrorCode(e.getCause().getMessage());
            }
            if (!isSuccessful) {
              log.error(
                  "BlockingMessageSender of message processor ["
                      + this.messageProcessor.getName()
                      + "] failed to send message to the endpoint");
            }
          }

          if (isSuccessful) {
            if (outCtx != null) {
              if ("true"
                  .equals(outCtx.getProperty(ForwardingProcessorConstants.BLOCKING_SENDER_ERROR))) {

                // this means send has failed due to some reason so we have to retry it
                isSuccessful =
                    isNonRetryErrorCode(
                        (String) outCtx.getProperty(SynapseConstants.ERROR_MESSAGE));

                if (isSuccessful) {
                  sendThroughReplySeq(outCtx);
                } else {
                  // This means some error has occurred so must try to send down the fault sequence.
                  log.error(
                      "BlockingMessageSender of message processor ["
                          + this.messageProcessor.getName()
                          + "] failed to send message to the endpoint");
                  sendThroughFaultSeq(outCtx);
                }
              } else {
                // Send the message down the reply sequence if there is one
                sendThroughReplySeq(outCtx);
                messageConsumer.ack();
                attemptCount = 0;
                isSuccessful = true;

                if (log.isDebugEnabled()) {
                  log.debug(
                      "Successfully sent the message to endpoint ["
                          + ep.getName()
                          + "]"
                          + " with message processor ["
                          + messageProcessor.getName()
                          + "]");
                }
              }
            } else {
              // This Means we have invoked an out only operation
              // remove the message and reset the count
              messageConsumer.ack();
              attemptCount = 0;
              isSuccessful = true;

              if (log.isDebugEnabled()) {
                log.debug(
                    "Successfully sent the message to endpoint ["
                        + ep.getName()
                        + "]"
                        + " with message processor ["
                        + messageProcessor.getName()
                        + "]");
              }
            }
          }

          if (!isSuccessful) {
            // Then we have to retry sending the message to the client.
            prepareToRetry();
          } else {
            if (messageProcessor.isPaused()) {
              this.messageProcessor.resumeService();
              log.info(
                  "Resuming the service of message processor [" + messageProcessor.getName() + "]");
            }
          }
        }
      } catch (Exception e) {
        log.error(
            "Message processor ["
                + messageProcessor.getName()
                + "] failed to send the message to"
                + " client",
            e);
      }
    } else {
      // No Target Endpoint defined for the Message
      // So we do not have a place to deliver.
      // Here we log a warning and remove the message
      // todo: we can improve this by implementing a target inferring mechanism

      log.warn(
          "Property "
              + ForwardingProcessorConstants.TARGET_ENDPOINT
              + " not found in the message context , Hence removing the message ");

      messageConsumer.ack();
    }

    return true;
  }
  public void invokeBusinessLogic(
      org.apache.axis2.context.MessageContext msgContext,
      org.apache.axis2.context.MessageContext newMsgContext)
      throws org.apache.axis2.AxisFault {

    try {

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

      GSNWebServiceSkeleton skel = (GSNWebServiceSkeleton) obj;
      // Out Envelop
      org.apache.axiom.soap.SOAPEnvelope envelope = null;
      // Find the axisOperation that has been set by the Dispatch phase.
      org.apache.axis2.description.AxisOperation op =
          msgContext.getOperationContext().getAxisOperation();
      if (op == null) {
        throw new org.apache.axis2.AxisFault(
            "Operation is not located, if this is doclit style the SOAP-ACTION should specified via the SOAP Action to use the RawXMLProvider");
      }

      java.lang.String methodName;
      if ((op.getName() != null)
          && ((methodName =
                  org.apache.axis2.util.JavaUtils.xmlNameToJava(op.getName().getLocalPart()))
              != null)) {

        if ("getVirtualSensorsDetails".equals(methodName)) {

          gsn.webservice.standard.GetVirtualSensorsDetailsResponse
              getVirtualSensorsDetailsResponse1 = null;
          gsn.webservice.standard.GetVirtualSensorsDetails wrappedParam =
              (gsn.webservice.standard.GetVirtualSensorsDetails)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.GetVirtualSensorsDetails.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getVirtualSensorsDetailsResponse1 = skel.getVirtualSensorsDetails(wrappedParam);

          envelope =
              toEnvelope(getSOAPFactory(msgContext), getVirtualSensorsDetailsResponse1, false);
        } else if ("getNextData".equals(methodName)) {

          gsn.webservice.standard.GetNextDataResponse getNextDataResponse3 = null;
          gsn.webservice.standard.GetNextData wrappedParam =
              (gsn.webservice.standard.GetNextData)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.GetNextData.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getNextDataResponse3 = skel.getNextData(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), getNextDataResponse3, false);
        } else if ("listWrapperURLs".equals(methodName)) {

          gsn.webservice.standard.ListWrapperURLsResponse listWrapperURLsResponse5 = null;
          gsn.webservice.standard.ListWrapperURLs wrappedParam =
              (gsn.webservice.standard.ListWrapperURLs)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.ListWrapperURLs.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          listWrapperURLsResponse5 = skel.listWrapperURLs(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), listWrapperURLsResponse5, false);
        } else if ("getLatestMultiData".equals(methodName)) {

          gsn.webservice.standard.GetLatestMultiDataResponse getLatestMultiDataResponse7 = null;
          gsn.webservice.standard.GetLatestMultiData wrappedParam =
              (gsn.webservice.standard.GetLatestMultiData)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.GetLatestMultiData.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getLatestMultiDataResponse7 = skel.getLatestMultiData(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), getLatestMultiDataResponse7, false);
        } else if ("unregisterQuery".equals(methodName)) {

          gsn.webservice.standard.UnregisterQueryResponse unregisterQueryResponse9 = null;
          gsn.webservice.standard.UnregisterQuery wrappedParam =
              (gsn.webservice.standard.UnregisterQuery)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.UnregisterQuery.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          unregisterQueryResponse9 = skel.unregisterQuery(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), unregisterQueryResponse9, false);
        } else if ("createVirtualSensor".equals(methodName)) {

          gsn.webservice.standard.CreateVirtualSensorResponse createVirtualSensorResponse11 = null;
          gsn.webservice.standard.CreateVirtualSensor wrappedParam =
              (gsn.webservice.standard.CreateVirtualSensor)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.CreateVirtualSensor.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          createVirtualSensorResponse11 = skel.createVirtualSensor(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), createVirtualSensorResponse11, false);
        } else if ("getMultiData".equals(methodName)) {

          gsn.webservice.standard.GetMultiDataResponse getMultiDataResponse13 = null;
          gsn.webservice.standard.GetMultiData wrappedParam =
              (gsn.webservice.standard.GetMultiData)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.GetMultiData.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getMultiDataResponse13 = skel.getMultiData(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), getMultiDataResponse13, false);
        } else if ("registerQuery".equals(methodName)) {

          gsn.webservice.standard.RegisterQueryResponse registerQueryResponse15 = null;
          gsn.webservice.standard.RegisterQuery wrappedParam =
              (gsn.webservice.standard.RegisterQuery)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.RegisterQuery.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          registerQueryResponse15 = skel.registerQuery(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), registerQueryResponse15, false);
        } else if ("getContainerInfo".equals(methodName)) {

          gsn.webservice.standard.GetContainerInfoResponse getContainerInfoResponse17 = null;
          gsn.webservice.standard.GetContainerInfo wrappedParam =
              (gsn.webservice.standard.GetContainerInfo)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.GetContainerInfo.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getContainerInfoResponse17 = skel.getContainerInfo(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), getContainerInfoResponse17, false);
        } else if ("listVirtualSensorNames".equals(methodName)) {

          gsn.webservice.standard.ListVirtualSensorNamesResponse listVirtualSensorNamesResponse19 =
              null;
          gsn.webservice.standard.ListVirtualSensorNames wrappedParam =
              (gsn.webservice.standard.ListVirtualSensorNames)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.ListVirtualSensorNames.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          listVirtualSensorNamesResponse19 = skel.listVirtualSensorNames(wrappedParam);

          envelope =
              toEnvelope(getSOAPFactory(msgContext), listVirtualSensorNamesResponse19, false);
        } else if ("deleteVirtualSensor".equals(methodName)) {

          gsn.webservice.standard.DeleteVirtualSensorResponse deleteVirtualSensorResponse21 = null;
          gsn.webservice.standard.DeleteVirtualSensor wrappedParam =
              (gsn.webservice.standard.DeleteVirtualSensor)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.DeleteVirtualSensor.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          deleteVirtualSensorResponse21 = skel.deleteVirtualSensor(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), deleteVirtualSensorResponse21, false);

        } else {
          throw new java.lang.RuntimeException("method not found");
        }

        newMsgContext.setEnvelope(envelope);
      }
    } catch (java.lang.Exception e) {
      throw org.apache.axis2.AxisFault.makeFault(e);
    }
  }
  /**
   * 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);
      }
    }
  }