public boolean mediate(MessageContext synCtx, ContinuationState contState) {
    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Aggregate mediator : Mediating from ContinuationState");
    }

    boolean result;

    SequenceMediator onCompleteSequence = getOnCompleteSequence();
    RuntimeStatisticCollector.openLogForContinuation(
        synCtx, onCompleteSequence.getSequenceNameForStatistics(synCtx));
    if (!contState.hasChild()) {
      result = onCompleteSequence.mediate(synCtx, contState.getPosition() + 1);
    } else {
      FlowContinuableMediator mediator =
          (FlowContinuableMediator) onCompleteSequence.getChild(contState.getPosition());
      RuntimeStatisticCollector.openLogForContinuation(
          synCtx, ((Mediator) mediator).getMediatorName());

      result = mediator.mediate(synCtx, contState.getChildContState());

      ((Mediator) mediator).reportStatistic(synCtx, null, false);
    }
    onCompleteSequence.reportStatistic(synCtx, null, false);
    return result;
  }
Ejemplo n.º 2
0
  public void connect(MessageContext messageContext) throws ConnectException {
    SynapseLog log = getLog(messageContext);
    log.auditLog("Start: create account");
    String friendlyName =
        (String)
            ConnectorUtils.lookupTemplateParamater(messageContext, TwilioUtil.PARAM_FRIENDLY_NAME);

    // Build a filter for the AccountList
    Map<String, String> params = new HashMap<String, String>();

    // If a friendly name has been provided for the account;
    // if not will use the current date and time (Default by Twilio).
    if (friendlyName != null) {
      params.put(TwilioUtil.TWILIO_FRIENDLY_NAME, friendlyName);
    }

    try {
      TwilioRestClient twilioRestClient = TwilioUtil.getTwilioRestClient(messageContext);

      AccountFactory accountFactory = twilioRestClient.getAccountFactory();
      Account account = accountFactory.create(params);

      OMElement omResponse = TwilioUtil.parseResponse("account.create.success");
      TwilioUtil.addElement(omResponse, TwilioUtil.TWILIO_ACCOUNT_SID, account.getSid());
      TwilioUtil.preparePayload(messageContext, omResponse);
    } catch (Exception e) {
      log.error(e.getMessage());
      TwilioUtil.handleException(e, "0001", messageContext);
      throw new SynapseException(e);
    }
    log.auditLog("End: create account");
  }
Ejemplo n.º 3
0
 public void addIds(
     String strOperation, String strParamName, MessageContext synCtx, SynapseLog synLog) {
   SOAPEnvelope envelope = synCtx.getEnvelope();
   OMFactory fac = OMAbstractFactory.getOMFactory();
   SOAPBody body = envelope.getBody();
   Iterator<OMElement> bodyChildElements = body.getChildrenWithLocalName(strOperation);
   if (bodyChildElements.hasNext()) {
     try {
       OMElement bodyElement = bodyChildElements.next();
       Iterator<OMElement> cElements = bodyElement.getChildElements();
       if (cElements != null && cElements.hasNext()) {
         cElements.next();
       }
       String strSobject = (String) ConnectorUtils.lookupTemplateParamater(synCtx, strParamName);
       OMElement sObjects = AXIOMUtil.stringToOM(strSobject);
       Iterator<OMElement> sObject = sObjects.getChildElements();
       OMNamespace omNsurn = fac.createOMNamespace("urn:partner.soap.sforce.com", "urn");
       // Loops sObject
       while (sObject.hasNext()) {
         OMElement currentElement = sObject.next();
         OMElement newElement = fac.createOMElement("ids", omNsurn);
         // Add the fields
         newElement.addChild(fac.createOMText(currentElement.getText()));
         bodyElement.addChild(newElement);
       }
     } catch (Exception e) {
       synLog.error("Saleforce adaptor - error injecting sObjects to payload : " + e);
     }
   }
 }
Ejemplo n.º 4
0
  public boolean mediate(MessageContext synCtx, ContinuationState continuationState) {
    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Invoke mediator : Mediating from ContinuationState");
    }

    boolean result;
    int subBranch = ((ReliantContinuationState) continuationState).getSubBranch();

    if (subBranch == 0) {
      // Default flow
      TemplateMediator templateMediator =
          (TemplateMediator) synCtx.getSequenceTemplate(targetTemplate);

      if (!continuationState.hasChild()) {
        result = templateMediator.mediate(synCtx, continuationState.getPosition() + 1);
        if (result) {
          templateMediator.popFuncContextFrom(synCtx);
        }
      } else {
        FlowContinuableMediator mediator =
            (FlowContinuableMediator) templateMediator.getChild(continuationState.getPosition());
        result = mediator.mediate(synCtx, continuationState.getChildContState());
      }
    } else {
      // Pre fetching invoke mediator flow
      String prefetchInvokeKey = key.evaluateValue(synCtx);
      InvokeMediator prefetchInvoke =
          (InvokeMediator) synCtx.getDefaultConfiguration(prefetchInvokeKey);

      ContinuationState childContinuationState = continuationState.getChildContState();
      result = prefetchInvoke.mediate(synCtx, childContinuationState);

      if (result && !childContinuationState.hasChild()) {
        // Pre fetching invoke mediator flow completed.
        // Remove ContinuationState represent the prefetchInvoke mediator and
        // flip the subbranch to default flow
        continuationState.removeLeafChild();
        ((ReliantContinuationState) continuationState).setSubBranch(0);
        // after prefetch invoke mediator flow, execute default flow
        result = mediate(synCtx, false);
      }
    }
    return result;
  }
Ejemplo n.º 5
0
  public boolean mediate(MessageContext synCtx, ContinuationState contState) {
    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Aggregate mediator : Mediating from ContinuationState");
    }

    boolean result;

    if (!contState.hasChild()) {
      result = getOnCompleteSequence().mediate(synCtx, contState.getPosition() + 1);
    } else {
      FlowContinuableMediator mediator =
          (FlowContinuableMediator) getOnCompleteSequence().getChild(contState.getPosition());
      result = mediator.mediate(synCtx, contState.getChildContState());
    }
    return result;
  }
Ejemplo n.º 6
0
  /**
   * This will implement the mediate method of the Mediator interface and will provide the
   * functionality of cloning message into the specified targets and mediation
   *
   * @param synCtx - MessageContext which is subjected to the cloning
   * @return boolean true if this needs to be further mediated (continueParent=true)
   */
  public boolean mediate(MessageContext synCtx) {

    if (synCtx.getEnvironment().isDebugEnabled()) {
      if (super.divertMediationRoute(synCtx)) {
        return true;
      }
    }

    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Start : Clone mediator");

      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Message : " + synCtx.getEnvelope());
      }
    }

    // get the targets list, clone the message for the number of targets and then
    // mediate the cloned messages using the targets
    Iterator<Target> iter = targets.iterator();
    int i = 0;
    while (iter.hasNext()) {
      if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug(
            "Submitting "
                + (i + 1)
                + " of "
                + targets.size()
                + " messages for "
                + (isSequential() ? "sequential processing" : "parallel processing"));
      }

      MessageContext clonedMsgCtx = getClonedMessageContext(synCtx, i++, targets.size());
      ContinuationStackManager.addReliantContinuationState(
          clonedMsgCtx, i - 1, getMediatorPosition());
      iter.next().mediate(clonedMsgCtx);
    }

    // if the continuation of the parent message is stopped from here set the RESPONSE_WRITTEN
    // property to SKIP to skip the blank http response
    OperationContext opCtx =
        ((Axis2MessageContext) synCtx).getAxis2MessageContext().getOperationContext();
    if (!continueParent && opCtx != null) {
      opCtx.setProperty(Constants.RESPONSE_WRITTEN, "SKIP");
    }

    // finalize tracing and debugging
    synLog.traceOrDebug("End : Clone mediator");

    // if continue parent is true mediators after the clone will be called for the further
    // mediation of the message which is subjected for clonning (parent message)
    return continueParent;
  }
Ejemplo n.º 7
0
  private boolean mediate(MessageContext synCtx, boolean executePreFetchingSequence) {
    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug(
          "Invoking Target EIP Sequence "
              + targetTemplate
              + " paramNames : "
              + pName2ExpressionMap.keySet());
      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Message : " + synCtx.getEnvelope());
      }
    }
    // get the target function template and invoke by passing populated
    // parameters
    Mediator mediator = synCtx.getSequenceTemplate(targetTemplate);

    if (mediator == null) {
      handleException("Sequence template " + targetTemplate + " cannot be found", synCtx);
    }

    // executing key reference if found defined at configuration.
    if (executePreFetchingSequence && key != null) {
      String defaultConfiguration = key.evaluateValue(synCtx);
      Mediator m = synCtx.getDefaultConfiguration(defaultConfiguration);
      if (m == null) {
        handleException("Sequence named " + key + " cannot be found", synCtx);

      } else {
        if (synLog.isTraceOrDebugEnabled()) {
          synLog.traceOrDebug("Executing with key " + key);
        }
        ContinuationStackManager.addReliantContinuationState(synCtx, 1, getMediatorPosition());
        boolean result = m.mediate(synCtx);

        if (result) {
          ContinuationStackManager.removeReliantContinuationState(synCtx);
        } else {
          return false;
        }
      }
    }

    if (mediator != null && mediator instanceof TemplateMediator) {
      populateParameters(synCtx, ((TemplateMediator) mediator).getName());
      if (executePreFetchingSequence) {
        ContinuationStackManager.addReliantContinuationState(synCtx, 0, getMediatorPosition());
      }
      boolean result = mediator.mediate(synCtx);
      if (result && executePreFetchingSequence) {
        ContinuationStackManager.removeReliantContinuationState(synCtx);
      }
      return result;
    }
    return false;
  }
  public boolean mediate(MessageContext synCtx) {
    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Start : UUIDGenerator mediator");

      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Message : " + synCtx.getEnvelope());
      }
    }

    try {
      // Initialize SecureRandom
      // This is a lengthy operation, to be done only upon
      // initialization of the application
      SecureRandom prng = null;
      prng = SecureRandom.getInstance("SHA1PRNG");

      // generate a random number
      String randomNum = Integer.toString(prng.nextInt());

      // get its digest
      MessageDigest sha = MessageDigest.getInstance("SHA-1");
      byte[] result = sha.digest(randomNum.getBytes());

      String uuid = hexEncode(result);

      synCtx.setProperty(GEN_UUID, uuid);

      UUID stdUuid = UUID.randomUUID();
      String stdUuidWithDashes = stdUuid.toString();
      String stdUuidNoDashes = stdUuidWithDashes.replaceAll("-", "");
      synCtx.setProperty(STD_36_UUID, stdUuidWithDashes);
      synCtx.setProperty(STD_32_UUID, stdUuidNoDashes);

      return true;
    } catch (NoSuchAlgorithmException e) {
      log.error(e.getMessage(), e);
      throw new SynapseException(e.getMessage(), e);
    }
  }
Ejemplo n.º 9
0
  public void addSobjects(
      String strOperation,
      String strParamName,
      MessageContext synCtx,
      SynapseLog synLog,
      String strExternalId) {
    SOAPEnvelope envelope = synCtx.getEnvelope();
    OMFactory fac = OMAbstractFactory.getOMFactory();
    SOAPBody body = envelope.getBody();
    Iterator<OMElement> bodyChildElements = body.getChildrenWithLocalName(strOperation);
    if (bodyChildElements.hasNext()) {
      try {
        OMElement bodyElement = bodyChildElements.next();
        if (strExternalId != null) {
          OMNamespace omNs = fac.createOMNamespace("urn:partner.soap.sforce.com", "urn");
          OMElement value = fac.createOMElement("externalIDFieldName", omNs);
          value.addChild(fac.createOMText(strExternalId));
          bodyElement.addChild(value);
        }
        String strSobject = (String) ConnectorUtils.lookupTemplateParamater(synCtx, strParamName);
        OMElement sObjects = AXIOMUtil.stringToOM(strSobject);
        Iterator<OMElement> sObject = sObjects.getChildElements();
        String strType =
            sObjects.getAttributeValue(new QName(SalesforceUtil.SALESFORCE_CREATE_SOBJECTTYPE));
        OMElement tmpElement = null;
        OMNamespace omNsurn = fac.createOMNamespace("urn:partner.soap.sforce.com", "urn");
        OMNamespace omNsurn1 = fac.createOMNamespace("urn:sobject.partner.soap.sforce.com", "urn1");
        // Loops sObject
        while (sObject.hasNext()) {
          OMElement currentElement = sObject.next();
          OMElement newElement = fac.createOMElement("sObjects", omNsurn);
          // Add Object type
          if (strType != null) {
            tmpElement = fac.createOMElement("type", omNsurn1);
            tmpElement.addChild(fac.createOMText(strType));
            newElement.addChild(tmpElement);
          }
          // Add the fields
          Iterator<OMElement> sObjectFields = currentElement.getChildElements();
          while (sObjectFields.hasNext()) {
            OMElement sObjectField = sObjectFields.next();
            tmpElement = fac.createOMElement(sObjectField.getLocalName(), omNsurn1);
            tmpElement.addChild(fac.createOMText(sObjectField.getText()));
            newElement.addChild(tmpElement);
          }

          bodyElement.addChild(newElement);
        }
      } catch (Exception e) {
        synLog.error("Saleforce adaptor - error injecting sObjects to payload : " + e);
      }
    }
  }
Ejemplo n.º 10
0
  public boolean mediate(MessageContext synCtx, ContinuationState continuationState) {
    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Clone mediator : Mediating from ContinuationState");
    }

    boolean result;
    int subBranch = ((ReliantContinuationState) continuationState).getSubBranch();

    if (!continuationState.hasChild()) {
      result =
          targets.get(subBranch).getSequence().mediate(synCtx, continuationState.getPosition() + 1);
    } else {
      FlowContinuableMediator mediator =
          (FlowContinuableMediator)
              targets.get(subBranch).getSequence().getChild(continuationState.getPosition());
      result = mediator.mediate(synCtx, continuationState.getChildContState());
    }
    return result;
  }
Ejemplo n.º 11
0
  public void connect(MessageContext messageContext) throws ConnectException {
    SynapseLog log = getLog(messageContext);
    log.auditLog("Start: get member");

    String queueSid =
        (String) ConnectorUtils.lookupTemplateParamater(messageContext, TwilioUtil.PARAM_QUEUE_SID);
    String callSid =
        (String) ConnectorUtils.lookupTemplateParamater(messageContext, TwilioUtil.PARAM_CALL_SID);

    try {
      TwilioRestClient twilioRestClient = TwilioUtil.getTwilioRestClient(messageContext);
      TwilioRestResponse response =
          twilioRestClient.request(
              TwilioUtil.API_URL
                  + "/"
                  + TwilioUtil.API_VERSION
                  + "/"
                  + TwilioUtil.API_ACCOUNTS
                  + "/"
                  + twilioRestClient.getAccountSid()
                  + "/"
                  + TwilioUtil.API_QUEUES
                  + "/"
                  + queueSid
                  + "/"
                  + TwilioUtil.API_MEMBERS
                  + "/"
                  + callSid,
              "GET",
              null);

      OMElement omResponse = TwilioUtil.parseResponse(response);
      TwilioUtil.preparePayload(messageContext, omResponse);
    } catch (Exception e) {
      log.error(e);
      throw new SynapseException(e);
    }
    log.auditLog("End: get member");
  }
Ejemplo n.º 12
0
  /**
   * Apply the Regular expression on to the String value and choose the matching group. If a
   * matching not found same string passed in to this method will be returned. If a pattern is not
   * specified same String passed to this method will be returned.
   *
   * @param value String value against the regular expression is matched
   * @param synLog log
   * @return the matched string group
   */
  private String getMatchedValue(String value, SynapseLog synLog) {

    String matchedValue = value;
    // if we cannot find a match set the value to empty string
    Matcher matcher = pattern.matcher(value);
    if (matcher.matches()) {

      if (matcher.groupCount() >= group) {
        matchedValue = matcher.group(group);
      } else {
        if (synLog.isTraceOrDebugEnabled()) {
          String msg =
              "Failed to get a match for regx : "
                  + pattern.toString()
                  + " with the property value :"
                  + value
                  + " for group :"
                  + group;
          synLog.traceOrDebug(msg);
        }
      }

    } else {
      if (synLog.isTraceOrDebugEnabled()) {
        String msg =
            "Unable to find a match for regx : "
                + pattern.toString()
                + " with the property value :"
                + value;
        synLog.traceOrDebug(msg);
      }
      return ""; // if not matched ideally should return empty string
    }

    return matchedValue;
  }
  public boolean mediate(MessageContext synCtx, int mediatorPosition) {

    boolean returnVal = true;
    int parentsEffectiveTraceState = synCtx.getTracingState();
    // if I have been explicitly asked to enable or disable tracing, set it to the message
    // to pass it on; else, do nothing -> i.e. let the parents state flow
    setEffectiveTraceState(synCtx);
    int myEffectiveTraceState = synCtx.getTracingState();
    try {
      SynapseLog synLog = getLog(synCtx);
      if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Sequence <" + getType() + "> :: mediate()");
        synLog.traceOrDebug("Mediation started from mediator position : " + mediatorPosition);
      }

      if (contentAware) {
        try {
          if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("Building message. Sequence <" + getType() + "> is content aware");
          }
          RelayUtils.buildMessage(((Axis2MessageContext) synCtx).getAxis2MessageContext(), false);
        } catch (Exception e) {
          handleException("Error while building message", e, synCtx);
        }
      }

      for (int i = mediatorPosition; i < mediators.size(); i++) {
        // ensure correct trace state after each invocation of a mediator
        Mediator mediator = mediators.get(i);
        Integer statisticReportingIndex =
            mediator.reportOpenStatistics(synCtx, i == mediatorPosition);
        synCtx.setTracingState(myEffectiveTraceState);
        if (!mediator.mediate(synCtx)) {
          mediator.reportCloseStatistics(synCtx, statisticReportingIndex);
          returnVal = false;
          break;
        }
        mediator.reportCloseStatistics(synCtx, statisticReportingIndex);
      }
    } catch (SynapseException synEx) {
      throw synEx;
    } catch (Exception ex) {
      String errorMsg = ex.getMessage();
      if (errorMsg == null) {
        errorMsg = "Runtime error occurred while mediating the message";
      }
      handleException(errorMsg, ex, synCtx);
    } finally {
      synCtx.setTracingState(parentsEffectiveTraceState);
    }

    return returnVal;
  }
  public void connect(MessageContext synCtx) {

    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Start : Salesforce update SObjects mediator");

      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Message : " + synCtx.getEnvelope());
      }
    }

    SalesforceUtil salesforceUtil = SalesforceUtil.getSalesforceUtil();
    salesforceUtil.addSobjects("update", SalesforceUtil.SALESFORCE_SOBJECTS, synCtx, synLog, null);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("End : Salesforce update SObjects mediator");

      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Message : " + synCtx.getEnvelope());
      }
    }
  }
  public void connect(MessageContext synCtx) {

    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Start : Salesforce Empty Recycle Bin mediator");

      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Message : " + synCtx.getEnvelope());
      }
    }

    SalesforceUtil salesforceUtil = SalesforceUtil.getSalesforceUtil();
    salesforceUtil.addIds("emptyRecycleBin", SalesforceUtil.SALESFORCE_SOBJECTS, synCtx, synLog);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("End : Salesforce Empty Recycle Bin mediator");

      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Message : " + synCtx.getEnvelope());
      }
    }
  }
  private void makePOXFault(MessageContext synCtx, SynapseLog synLog) {

    OMFactory fac = synCtx.getEnvelope().getOMFactory();
    OMElement faultPayload = fac.createOMElement(new QName("Exception"));

    if (faultDetail != null) {

      if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Setting the fault detail : " + faultDetail + " as the POX Fault");
      }

      faultPayload.setText(faultDetail);

    } else if (faultDetailExpr != null) {

      String faultDetail = faultDetailExpr.stringValueOf(synCtx);

      if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Setting the fault detail : " + faultDetail + " as the POX Fault");
      }

      faultPayload.setText(faultDetail);

    } else if (faultReasonValue != null) {

      if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Setting the fault reason : " + faultReasonValue + " as the POX Fault");
      }

      faultPayload.setText(faultReasonValue);

    } else if (faultReasonExpr != null) {

      String faultReason = faultReasonExpr.stringValueOf(synCtx);
      faultPayload.setText(faultReason);

      if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Setting the fault reason : " + faultReason + " as the POX Fault");
      }
    }

    SOAPBody body = synCtx.getEnvelope().getBody();
    if (body != null) {

      if (body.getFirstElement() != null) {
        body.getFirstElement().detach();
      }

      synCtx.setFaultResponse(true);
      ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProcessingFault(true);

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

      body.addChild(faultPayload);
    }
  }
  /**
   * Actual transformation of the current message into a fault message
   *
   * @param synCtx the current message context
   * @param soapVersion SOAP version of the resulting fault desired
   * @param synLog the Synapse log to use
   */
  private void makeSOAPFault(MessageContext synCtx, int soapVersion, SynapseLog synLog) {

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

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

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

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

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

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

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

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

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

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

    synLog.traceOrDebug("End : Fault mediator");
  }
Ejemplo n.º 18
0
  /**
   * Perform Script mediation
   *
   * @param synCtx the Synapse message context
   * @return the boolean result from the script invocation
   */
  public boolean mediate(MessageContext synCtx) {

    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Start : Script mediator");

      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Message : " + synCtx.getEnvelope());
      }
    }

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug(
          "Scripting language : "
              + language
              + " source "
              + (key == null ? ": specified inline " : " loaded with key : " + key)
              + (function != null ? " function : " + function : ""));
    }

    boolean returnValue;
    if (multiThreadedEngine) {
      returnValue = invokeScript(synCtx);
    } else {
      // TODO: change to use a pool of script engines (requires an update to BSF)
      synchronized (scriptEngine.getClass()) {
        returnValue = invokeScript(synCtx);
      }
    }

    if (synLog.isTraceTraceEnabled()) {
      synLog.traceTrace("Result message after execution of script : " + synCtx.getEnvelope());
    }

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("End : Script mediator return value : " + returnValue);
    }

    return returnValue;
  }
  public boolean mediate(MessageContext synCtx) {

    if (synCtx.getEnvironment().isDebugEnabled()) {
      if (super.divertMediationRoute(synCtx)) {
        return true;
      }
    }

    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Start : Fault mediator");

      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Message : " + synCtx.getEnvelope());
      }
    }

    switch (soapVersion) {
      case SOAP11:
        makeSOAPFault(synCtx, SOAP11, synLog);
        break;
      case SOAP12:
        makeSOAPFault(synCtx, SOAP12, synLog);
        break;
      case POX:
        makePOXFault(synCtx, synLog);
        break;

      default:
        {
          // if this is a POX or REST message then make a POX fault
          if (synCtx.isDoingPOX() || synCtx.isDoingGET()) {

            makePOXFault(synCtx, synLog);

          } else {

            // determine from current message's SOAP envelope namespace
            SOAPEnvelope envelop = synCtx.getEnvelope();
            if (envelop != null) {

              if (SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(
                  envelop.getNamespace().getNamespaceURI())) {
                makeSOAPFault(synCtx, SOAP12, synLog);

              } else {
                makeSOAPFault(synCtx, SOAP11, synLog);
              }

            } else {
              // default to SOAP 11
              makeSOAPFault(synCtx, SOAP11, synLog);
            }
          }
        }
    }

    final Pipe pipe =
        (Pipe)
            (((Axis2MessageContext) synCtx))
                .getAxis2MessageContext()
                .getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
    if (pipe != null) {
      // cleaning the OUTPUT PIPE with older references
      // if there is a [protocal violation when sending out message etc.]
      pipe.getBuffer().clear();
      pipe.resetOutputStream();
    }

    // if the message has to be marked as a response mark it as response
    if (markAsResponse) {
      synCtx.setResponse(true);
      synCtx.setTo(synCtx.getReplyTo());
    }

    return true;
  }
Ejemplo n.º 20
0
  /**
   * Send request in blocking manner
   *
   * @param synInCtx message context
   * @return continue the mediation flow or not
   */
  private boolean handleBlockingCall(MessageContext synInCtx) {

    SynapseLog synLog = getLog(synInCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Start : Call mediator - Blocking Call");
      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Message : " + synInCtx.getEnvelope());
      }
    }

    MessageContext resultMsgCtx = null;
    try {
      if ("true".equals(synInCtx.getProperty(SynapseConstants.OUT_ONLY))) {
        blockingMsgSender.send(endpoint, synInCtx);
      } else {
        resultMsgCtx = blockingMsgSender.send(endpoint, synInCtx);
        if ("true".equals(resultMsgCtx.getProperty(SynapseConstants.BLOCKING_SENDER_ERROR))) {
          handleFault(
              synInCtx, (Exception) resultMsgCtx.getProperty(SynapseConstants.ERROR_EXCEPTION));
        }
      }
    } catch (Exception ex) {
      handleFault(synInCtx, ex);
    }

    if (resultMsgCtx != null) {
      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Response payload received : " + resultMsgCtx.getEnvelope());
      }
      try {
        synInCtx.setEnvelope(resultMsgCtx.getEnvelope());

        if (synLog.isTraceOrDebugEnabled()) {
          synLog.traceOrDebug("End : Call mediator - Blocking Call");
        }
        return true;
      } catch (Exception e) {
        handleFault(synInCtx, e);
      }
    } else {
      if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Service returned a null response");
      }
    }

    return true;
  }
Ejemplo n.º 21
0
  /**
   * Aggregate messages flowing through this mediator according to the correlation criteria and the
   * aggregation algorithm specified to it
   *
   * @param synCtx - MessageContext to be mediated and aggregated
   * @return boolean true if the complete condition for the particular aggregate is validated
   */
  public boolean mediate(MessageContext synCtx) {

    if (synCtx.getEnvironment().isDebugEnabled()) {
      if (super.divertMediationRoute(synCtx)) {
        return true;
      }
    }

    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Start : Aggregate mediator");

      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Message : " + synCtx.getEnvelope());
      }
    }

    try {
      Aggregate aggregate = null;
      String correlationIdName =
          (id != null
              ? EIPConstants.AGGREGATE_CORRELATION + "." + id
              : EIPConstants.AGGREGATE_CORRELATION);
      // if a correlateExpression is provided and there is a coresponding
      // element in the current message prepare to correlate the messages on that
      Object result = null;
      if (correlateExpression != null) {
        result = correlateExpression.evaluate(synCtx);
        if (result instanceof List) {
          if (((List) result).isEmpty()) {
            handleException(
                "Failed to evaluate correlate expression: " + correlateExpression.toString(),
                synCtx);
          }
        }
      }
      if (result != null) {

        while (aggregate == null) {

          synchronized (lock) {
            if (activeAggregates.containsKey(correlateExpression.toString())) {

              aggregate = activeAggregates.get(correlateExpression.toString());
              if (aggregate != null) {
                if (!aggregate.getLock()) {
                  aggregate = null;
                }
              }

            } else {

              if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug(
                    "Creating new Aggregator - "
                        + (completionTimeoutMillis > 0
                            ? "expires in : " + (completionTimeoutMillis / 1000) + "secs"
                            : "without expiry time"));
              }

              Double minMsg = Double.parseDouble(minMessagesToComplete.evaluateValue(synCtx));
              Double maxMsg = Double.parseDouble(maxMessagesToComplete.evaluateValue(synCtx));

              aggregate =
                  new Aggregate(
                      synCtx.getEnvironment(),
                      correlateExpression.toString(),
                      completionTimeoutMillis,
                      minMsg.intValue(),
                      maxMsg.intValue(),
                      this);

              if (completionTimeoutMillis > 0) {
                synCtx
                    .getConfiguration()
                    .getSynapseTimer()
                    .schedule(aggregate, completionTimeoutMillis);
              }
              aggregate.getLock();
              activeAggregates.put(correlateExpression.toString(), aggregate);
            }
          }
        }

      } else if (synCtx.getProperty(correlationIdName) != null) {
        // if the correlattion cannot be found using the correlateExpression then
        // try the default which is through the AGGREGATE_CORRELATION message property
        // which is the unique original message id of a split or iterate operation and
        // which thus can be used to uniquely group messages into aggregates

        Object o = synCtx.getProperty(correlationIdName);
        String correlation;

        if (o != null && o instanceof String) {
          correlation = (String) o;
          while (aggregate == null) {
            synchronized (lock) {
              if (activeAggregates.containsKey(correlation)) {
                aggregate = activeAggregates.get(correlation);
                if (aggregate != null) {
                  if (!aggregate.getLock()) {
                    aggregate = null;
                  }
                } else {
                  break;
                }
              } else {
                if (synLog.isTraceOrDebugEnabled()) {
                  synLog.traceOrDebug(
                      "Creating new Aggregator - "
                          + (completionTimeoutMillis > 0
                              ? "expires in : " + (completionTimeoutMillis / 1000) + "secs"
                              : "without expiry time"));
                }

                Double minMsg = -1.0;
                if (minMessagesToComplete != null) {
                  minMsg = Double.parseDouble(minMessagesToComplete.evaluateValue(synCtx));
                }
                Double maxMsg = -1.0;
                if (maxMessagesToComplete != null) {
                  maxMsg = Double.parseDouble(maxMessagesToComplete.evaluateValue(synCtx));
                }

                aggregate =
                    new Aggregate(
                        synCtx.getEnvironment(),
                        correlation,
                        completionTimeoutMillis,
                        minMsg.intValue(),
                        maxMsg.intValue(),
                        this);

                if (completionTimeoutMillis > 0) {
                  synchronized (aggregate) {
                    if (!aggregate.isCompleted()) {
                      synCtx
                          .getConfiguration()
                          .getSynapseTimer()
                          .schedule(aggregate, completionTimeoutMillis);
                    }
                  }
                }
                aggregate.getLock();
                activeAggregates.put(correlation, aggregate);
              }
            }
          }

        } else {
          synLog.traceOrDebug("Unable to find aggrgation correlation property");
          return true;
        }
      } else {
        synLog.traceOrDebug("Unable to find aggrgation correlation XPath or property");
        return true;
      }

      // if there is an aggregate continue on aggregation
      if (aggregate != null) {
        // this is a temporary fix
        synCtx.getEnvelope().build();
        boolean collected = aggregate.addMessage(synCtx);
        if (synLog.isTraceOrDebugEnabled()) {
          if (collected) {
            synLog.traceOrDebug("Collected a message during aggregation");
            if (synLog.isTraceTraceEnabled()) {
              synLog.traceTrace("Collected message : " + synCtx);
            }
          }
        }

        // check the completeness of the aggregate and if completed aggregate the messages
        // if not completed return false and block the message sequence till it completes

        if (aggregate.isComplete(synLog)) {
          synLog.traceOrDebug("Aggregation completed - invoking onComplete");
          boolean onCompleteSeqResult = completeAggregate(aggregate);
          synLog.traceOrDebug("End : Aggregate mediator");
          isAggregateComplete = onCompleteSeqResult;
          return onCompleteSeqResult;
        } else {
          aggregate.releaseLock();
        }

      } else {
        // if the aggregation correlation cannot be found then continue the message on the
        // normal path by returning true

        synLog.traceOrDebug("Unable to find an aggregate for this message - skip");
        return true;
      }

    } catch (JaxenException e) {
      handleException("Unable to execute the XPATH over the message", e, synCtx);
    }

    synLog.traceOrDebug("End : Aggregate mediator");

    // When Aggregation is not completed return false to hold the flow
    return false;
  }
Ejemplo n.º 22
0
  /**
   * Send request in non-blocking manner
   *
   * @param synInCtx message context
   * @return continue the mediation flow or not
   */
  private boolean handleNonBlockingCall(MessageContext synInCtx) {
    SynapseLog synLog = getLog(synInCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Start : Call mediator - Non Blocking Call");
      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Message : " + synInCtx.getEnvelope());
      }
    }

    // clear the message context properties related to endpoint in last service invocation
    Set keySet = synInCtx.getPropertyKeySet();
    if (keySet != null) {
      keySet.remove(SynapseConstants.RECEIVING_SEQUENCE);
      keySet.remove(EndpointDefinition.DYNAMIC_URL_VALUE);
    }

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

    // Prepare the outgoing message context
    MessageContext synOutCtx = null;
    if (outOnlyMessage) {
      try {
        synOutCtx = MessageHelper.cloneMessageContext(synInCtx);
      } catch (AxisFault axisFault) {
        handleException("Error occurred while cloning msg context", axisFault, synInCtx);
      }
    } else {
      synOutCtx = synInCtx;
    }

    synOutCtx.setProperty(SynapseConstants.CONTINUATION_CALL, true);
    ContinuationStackManager.updateSeqContinuationState(synOutCtx, getMediatorPosition());

    // If no endpoints are defined, send where implicitly stated
    if (endpoint == null) {

      if (synLog.isTraceOrDebugEnabled()) {
        StringBuffer sb = new StringBuffer();
        sb.append("Calling ")
            .append(synOutCtx.isResponse() ? "response" : "request")
            .append(" message using implicit message properties..");
        sb.append("\nCalling To: ")
            .append(synOutCtx.getTo() != null ? synOutCtx.getTo().getAddress() : "null");
        sb.append("\nSOAPAction: ")
            .append(synOutCtx.getWSAAction() != null ? synOutCtx.getWSAAction() : "null");
        synLog.traceOrDebug(sb.toString());
      }

      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Envelope : " + synOutCtx.getEnvelope());
      }
      synOutCtx.getEnvironment().send(null, synOutCtx);

    } else {
      endpoint.send(synOutCtx);
    }

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("End : Call mediator - Non Blocking Call");
    }

    if (outOnlyMessage) {
      // For out only invocations request flow should continue
      // otherwise flow should stop from here
      return true;
    }
    return false;
  }
Ejemplo n.º 23
0
  /**
   * Sets a property into the current (local) Synapse Context or into the Axis Message Context or
   * into Transports Header and removes above properties from the corresponding locations.
   *
   * @param synCtx the message context
   * @return true always
   */
  public boolean mediate(MessageContext synCtx) {

    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Start : Property mediator");

      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Message : " + synCtx.getEnvelope());
      }
    }

    if (action == ACTION_SET) {

      Object resultValue = getResultValue(synCtx);

      // if the result value is a String we can apply a reguar expression to
      // choose part of it
      if (resultValue instanceof String && pattern != null) {
        resultValue = getMatchedValue((String) resultValue, synLog);
      }

      if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug(
            "Setting property : "
                + name
                + " at scope : "
                + (scope == null ? "default" : scope)
                + " to : "
                + resultValue
                + " (i.e. "
                + (value != null ? "constant : " + value : "result of expression : " + expression)
                + ")");
      }

      if (scope == null || XMLConfigConstants.SCOPE_DEFAULT.equals(scope)) {
        // Setting property into the  Synapse Context
        synCtx.setProperty(name, resultValue);

      } else if (XMLConfigConstants.SCOPE_AXIS2.equals(scope)
          && synCtx instanceof Axis2MessageContext) {
        // Setting property into the  Axis2 Message Context
        Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
        org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
        axis2MessageCtx.setProperty(name, resultValue);

      } else if (XMLConfigConstants.SCOPE_CLIENT.equals(scope)
          && synCtx instanceof Axis2MessageContext) {
        // Setting property into the  Axis2 Message Context client options
        Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
        org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
        axis2MessageCtx.getOptions().setProperty(name, resultValue);

      } else if (XMLConfigConstants.SCOPE_TRANSPORT.equals(scope)
          && synCtx instanceof Axis2MessageContext) {
        // Setting Transport Headers
        Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
        org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
        Object headers =
            axis2MessageCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);

        if (headers != null && headers instanceof Map) {
          Map headersMap = (Map) headers;
          headersMap.put(name, resultValue);
        }
        if (headers == null) {
          Map headersMap = new HashMap();
          headersMap.put(name, resultValue);
          axis2MessageCtx.setProperty(
              org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headersMap);
        }
      } else if (XMLConfigConstants.SCOPE_OPERATION.equals(scope)
          && synCtx instanceof Axis2MessageContext) {
        // Setting Transport Headers
        Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
        org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
        axis2smc.getAxis2MessageContext().getOperationContext().setProperty(name, resultValue);
      }

    } else {
      if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug(
            "Removing property : " + name + " (scope:" + (scope == null ? "default" : scope) + ")");
      }

      if (scope == null || XMLConfigConstants.SCOPE_DEFAULT.equals(scope)) {
        // Removing property from the  Synapse Context
        Set pros = synCtx.getPropertyKeySet();
        if (pros != null) {
          pros.remove(name);
        }

      } else if ((XMLConfigConstants.SCOPE_AXIS2.equals(scope)
              || XMLConfigConstants.SCOPE_CLIENT.equals(scope))
          && synCtx instanceof Axis2MessageContext) {

        // Removing property from the Axis2 Message Context
        Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
        org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
        axis2MessageCtx.removeProperty(name);

      } else if (XMLConfigConstants.SCOPE_TRANSPORT.equals(scope)
          && synCtx instanceof Axis2MessageContext) {
        // Removing transport headers
        Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
        org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
        Object headers =
            axis2MessageCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        if (headers != null && headers instanceof Map) {
          Map headersMap = (Map) headers;
          headersMap.remove(name);
        } else {
          synLog.traceOrDebug("No transport headers found for the message");
        }
      }
    }
    synLog.traceOrDebug("End : Property mediator");
    return true;
  }