/**
   * Initialize child mediators recursively
   *
   * @param se synapse environment
   */
  public void init(SynapseEnvironment se) {
    if (log.isDebugEnabled()) {
      log.debug("Initializing child mediators of mediator : " + getType());
    }

    for (int i = 0; i < mediators.size(); i++) {
      Mediator mediator = mediators.get(i);
      mediator.setMediatorPosition(i);

      if (mediator instanceof ManagedLifecycle) {
        ((ManagedLifecycle) mediator).init(se);
      }

      if (mediator.isContentAware()) {
        if (log.isDebugEnabled()) {
          log.debug(
              mediator.getType()
                  + " is content aware, setting sequence <"
                  + getType()
                  + "> as content aware");
        }
        contentAware = true;
      }
    }
  }
Example #2
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, 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 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;
  }
  /**
   * Sending the out message through the fault sequence.
   *
   * @param msgCtx Synapse {@link MessageContext} to be sent through the fault sequence.
   */
  public void sendThroughFaultSeq(MessageContext msgCtx) {
    if (faultSeq == null) {
      log.warn(
          "Failed to send the message through the fault sequence. Sequence name does not Exist.");
      return;
    }
    Mediator mediator = msgCtx.getSequence(faultSeq);

    if (mediator == null) {
      log.warn(
          "Failed to send the message through the fault sequence. Sequence ["
              + faultSeq
              + "] does not Exist.");
      return;
    }

    mediator.mediate(msgCtx);
  }
  public OMElement serializeMediator(OMElement parent, Mediator m) {

    AggregateMediator mediator = null;
    if (!(m instanceof AggregateMediator)) {
      handleException("Unsupported mediator passed in for serialization : " + m.getType());
    } else {
      mediator = (AggregateMediator) m;
    }

    OMElement aggregator = fac.createOMElement("aggregate", synNS);
    saveTracingState(aggregator, mediator);

    assert mediator != null;
    if (mediator.getCorrelateExpression() != null) {
      OMElement corelateOn = fac.createOMElement("correlateOn", synNS);
      SynapseXPathSerializer.serializeXPath(
          mediator.getCorrelateExpression(), corelateOn, "expression");
      aggregator.addChild(corelateOn);
    }

    OMElement completeCond = fac.createOMElement("completeCondition", synNS);
    if (mediator.getCompletionTimeoutMillis() != 0) {
      completeCond.addAttribute(
          "timeout", Long.toString(mediator.getCompletionTimeoutMillis() / 1000), nullNS);
    }
    OMElement messageCount = fac.createOMElement("messageCount", synNS);
    if (mediator.getMinMessagesToComplete() != 0) {
      messageCount.addAttribute(
          "min", Integer.toString(mediator.getMinMessagesToComplete()), nullNS);
    }
    if (mediator.getMaxMessagesToComplete() != 0) {
      messageCount.addAttribute(
          "max", Integer.toString(mediator.getMaxMessagesToComplete()), nullNS);
    }
    completeCond.addChild(messageCount);
    aggregator.addChild(completeCond);

    OMElement onCompleteElem = fac.createOMElement("onComplete", synNS);
    if (mediator.getAggregationExpression() != null) {
      SynapseXPathSerializer.serializeXPath(
          mediator.getAggregationExpression(), onCompleteElem, "expression");
    }
    if (mediator.getOnCompleteSequenceRef() != null) {
      onCompleteElem.addAttribute("sequence", mediator.getOnCompleteSequenceRef(), nullNS);
    } else if (mediator.getOnCompleteSequence() != null) {
      new SequenceMediatorSerializer()
          .serializeChildren(onCompleteElem, mediator.getOnCompleteSequence().getList());
    }
    aggregator.addChild(onCompleteElem);

    if (parent != null) {
      parent.addChild(aggregator);
    }

    return aggregator;
  }
  /**
   * Sending the out message through the reply sequence.
   *
   * @param outCtx Synapse out {@link MessageContext} to be sent through the reply sequence.
   */
  public void sendThroughReplySeq(MessageContext outCtx) {
    if (replySeq == null) {
      this.messageProcessor.deactivate();
      log.error(
          "Failed to send the out message. Reply sequence does not Exist. Deactivated the message processor");
      return;
    }
    Mediator mediator = outCtx.getSequence(replySeq);

    if (mediator == null) {
      this.messageProcessor.deactivate();
      log.error(
          "Failed to send the out message. Reply sequence ["
              + replySeq
              + "] does not exist. Deactivated the message processor");
      return;
    }

    mediator.mediate(outCtx);
  }
  public OMElement serializeSpecificMediator(Mediator m) {

    if (!(m instanceof RelayTransformerMediator)) {
      handleException("Unsupported mediator passed in for serialization : " + m.getType());
    }

    RelayTransformerMediator mediator = (RelayTransformerMediator) m;
    OMElement relayTransformer = fac.createOMElement("relayTransformer", synNS);

    if (mediator.getXsltKey() != null) {
      // Serialize Value using ValueSerializer
      ValueSerializer keySerializer = new ValueSerializer();
      keySerializer.serializeValue(mediator.getXsltKey(), XMLConfigConstants.KEY, relayTransformer);
    } else {
      handleException("Invalid relayTransformer mediator. XSLT registry key is required");
    }
    saveTracingState(relayTransformer, mediator);

    if (mediator.getSource() != null) {

      SynapseXPathSerializer.serializeXPath(mediator.getSource(), relayTransformer, "source");
    }
    if (mediator.getTargetPropertyName() != null) {
      relayTransformer.addAttribute(
          fac.createOMAttribute("target", nullNS, mediator.getTargetPropertyName()));
    }
    if (mediator.getInputType() != null) {
      relayTransformer.addAttribute(
          fac.createOMAttribute("input", nullNS, mediator.getInputType()));
    }
    serializeProperties(relayTransformer, mediator.getProperties());
    List<MediatorProperty> features = mediator.getFeatures();
    if (!features.isEmpty()) {
      for (MediatorProperty mp : features) {
        OMElement prop = fac.createOMElement("feature", synNS, relayTransformer);
        if (mp.getName() != null) {
          prop.addAttribute(fac.createOMAttribute("name", nullNS, mp.getName()));
        } else {
          handleException("The Feature name is missing");
        }
        if (mp.getValue() != null) {
          prop.addAttribute(fac.createOMAttribute("value", nullNS, mp.getValue()));
        } else {
          handleException("The Feature value is missing");
        }
      }
    }
    serializeMediatorProperties(relayTransformer, mediator.getAttributes(), ATTRIBUTE_Q);

    ResourceMapSerializer.serializeResourceMap(relayTransformer, mediator.getResourceMap());

    return relayTransformer;
  }
  public void sendThroughReplySeq(MessageContext outCtx) {
    if (replySeq == null) {
      this.messageProcessor.deactivate();
      log.error(
          "Can't Send the Out Message , Sequence name "
              + replySeq
              + " does not Exist. Deactivated the"
              + " message processor");
      return;
    }
    Mediator mediator = outCtx.getSequence(replySeq);

    if (mediator == null) {
      this.messageProcessor.deactivate();
      log.error(
          "Can't Send the Out Message , Sequence object "
              + replySeq
              + " does not Exist. Deactivated the"
              + " message processor");
      return;
    }

    mediator.mediate(outCtx);
  }
  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();
      }
    }
  }
Example #11
0
  void process(MessageContext synCtx) {
    if (log.isDebugEnabled()) {
      log.debug(
          "Processing message with ID: "
              + synCtx.getMessageID()
              + " through the "
              + "API: "
              + name);
    }

    synCtx.setProperty(RESTConstants.SYNAPSE_REST_API, getName());
    synCtx.setProperty(RESTConstants.SYNAPSE_REST_API_VERSION, versionStrategy.getVersion());
    synCtx.setProperty(RESTConstants.REST_API_CONTEXT, context);

    // Remove the API context part from the REST_URL_POSTFIX
    String restURLPostfix =
        (String)
            ((Axis2MessageContext) synCtx)
                .getAxis2MessageContext()
                .getProperty(NhttpConstants.REST_URL_POSTFIX);
    if (restURLPostfix != null) {
      if (!restURLPostfix.startsWith("/")) {
        restURLPostfix = "/" + restURLPostfix;
      }
      if (restURLPostfix.startsWith(context)) {
        restURLPostfix = restURLPostfix.substring(context.length());
        if (versionStrategy instanceof URLBasedVersionStrategy) {
          String version = versionStrategy.getVersion();
          if (restURLPostfix.startsWith(version)) {
            restURLPostfix = restURLPostfix.substring(version.length());
          } else if (restURLPostfix.startsWith("/" + version)) {
            restURLPostfix = restURLPostfix.substring(version.length() + 1);
          }
        }
        ((Axis2MessageContext) synCtx)
            .getAxis2MessageContext()
            .setProperty(NhttpConstants.REST_URL_POSTFIX, restURLPostfix);
      }
    }

    for (Handler handler : handlers) {
      if (log.isDebugEnabled()) {
        log.debug(
            "Processing message with ID: "
                + synCtx.getMessageID()
                + " through "
                + "handler: "
                + handler.getClass().getName());
      }

      boolean proceed;
      if (synCtx.isResponse()) {
        proceed = handler.handleResponse(synCtx);
      } else {
        proceed = handler.handleRequest(synCtx);
      }

      if (!proceed) {
        return;
      }
    }

    if (synCtx.isResponse()) {
      String resourceName = (String) synCtx.getProperty(RESTConstants.SYNAPSE_RESOURCE);
      if (resourceName != null) {
        Resource resource = resources.get(resourceName);
        if (resource != null) {
          resource.process(synCtx);
        }
      } else if (log.isDebugEnabled()) {
        log.debug("No resource information on the response: " + synCtx.getMessageID());
      }
      return;
    }

    String path = RESTUtils.getFullRequestPath(synCtx);
    String subPath;
    if (versionStrategy.getVersionType().equals(VersionStrategyFactory.TYPE_URL)) {
      // for URL based
      // request --> http://{host:port}/context/version/path/to/resource
      subPath = path.substring(context.length() + versionStrategy.getVersion().length() + 1);
    } else {
      subPath = path.substring(context.length());
    }
    if ("".equals(subPath)) {
      subPath = "/";
    }
    synCtx.setProperty(RESTConstants.REST_SUB_REQUEST_PATH, subPath);

    org.apache.axis2.context.MessageContext msgCtx =
        ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    String hostHeader = getHostHeader(msgCtx);
    if (hostHeader != null) {
      synCtx.setProperty(
          RESTConstants.REST_URL_PREFIX, msgCtx.getIncomingTransportName() + "://" + hostHeader);
    }

    Set<Resource> acceptableResources = new HashSet<Resource>();
    for (Resource r : resources.values()) {
      if (r.canProcess(synCtx)) {
        acceptableResources.add(r);
      }
    }

    boolean processed = false;
    if (!acceptableResources.isEmpty()) {
      for (RESTDispatcher dispatcher : RESTUtils.getDispatchers()) {
        Resource resource = dispatcher.findResource(synCtx, acceptableResources);
        if (resource != null) {
          resource.process(synCtx);
          processed = true;
          break;
        }
      }
    }

    if (!processed) {
      if (log.isDebugEnabled()) {
        log.debug("No matching resource was found for the request: " + synCtx.getMessageID());
      }

      Mediator sequence = synCtx.getSequence(RESTConstants.NO_MATCHING_RESOURCE_HANDLER);
      if (sequence != null) {
        sequence.mediate(synCtx);
      }
    }
  }
 protected void setCommonProperties(
     Mediator mediator, org.wso2.developerstudio.eclipse.gmf.esb.Mediator visualElement) {
   executeSetValueCommand(visualElement, ESB_ELEMENT__DESCRIPTION, mediator.getShortDescription());
   executeAddAllCommand(
       visualElement.getCommentsList(), ((AbstractMediator) mediator).getCommentsList());
 }
  /** {@inheritDoc} */
  public OMElement serializeSpecificMediator(Mediator mediator) {
    if (!(mediator instanceof EntitlementMediator)) {
      handleException("Unsupported mediator passed in for serialization : " + mediator.getType());
    }

    EntitlementMediator entitlement = null;
    OMElement entitlementElem = null;

    entitlement = (EntitlementMediator) mediator;
    entitlementElem = fac.createOMElement("entitlementService", synNS);
    saveTracingState(entitlementElem, entitlement);
    entitlementElem.addAttribute(
        fac.createOMAttribute("remoteServiceUrl", nullNS, entitlement.getRemoteServiceUrl()));
    entitlementElem.addAttribute(
        fac.createOMAttribute(
            "remoteServiceUserName", nullNS, entitlement.getRemoteServiceUserName()));
    entitlementElem.addAttribute(
        fac.createOMAttribute(
            "remoteServicePassword", nullNS, entitlement.getRemoteServicePassword()));

    if (entitlement.getCallbackClass() != null) {
      entitlementElem.addAttribute(
          fac.createOMAttribute("callbackClass", nullNS, entitlement.getCallbackClass()));
    }

    if (entitlement.getCacheType() != null) {
      entitlementElem.addAttribute(
          fac.createOMAttribute("cacheType", nullNS, entitlement.getCacheType()));
    }

    if (entitlement.getInvalidationInterval() != 0) {
      entitlementElem.addAttribute(
          fac.createOMAttribute(
              "invalidationInterval",
              nullNS,
              Integer.toString(entitlement.getInvalidationInterval())));
    }

    if (entitlement.getMaxCacheEntries() != 0) {
      entitlementElem.addAttribute(
          fac.createOMAttribute(
              "maxCacheEntries", nullNS, Integer.toString(entitlement.getMaxCacheEntries())));
    }

    if (entitlement.getClient() != null) {
      entitlementElem.addAttribute(
          fac.createOMAttribute(EntitlementConstants.CLIENT, nullNS, entitlement.getClient()));
    }

    if (entitlement.getThriftHost() != null) {
      entitlementElem.addAttribute(
          fac.createOMAttribute(
              EntitlementConstants.THRIFT_HOST, nullNS, entitlement.getThriftHost()));
    }

    if (entitlement.getThriftPort() != null) {
      entitlementElem.addAttribute(
          fac.createOMAttribute(
              EntitlementConstants.THRIFT_PORT, nullNS, entitlement.getThriftPort()));
    }

    if (entitlement.getReuseSession() != null) {
      entitlementElem.addAttribute(
          fac.createOMAttribute(
              EntitlementConstants.REUSE_SESSION, nullNS, entitlement.getReuseSession()));
    }

    String onReject = entitlement.getOnRejectSeqKey();
    if (onReject != null) {
      entitlementElem.addAttribute(
          fac.createOMAttribute(XMLConfigConstants.ONREJECT, nullNS, onReject));
    } else {
      Mediator m = entitlement.getOnRejectMediator();
      SequenceMediatorSerializer serializer = new SequenceMediatorSerializer();
      if (m != null && m instanceof SequenceMediator) {
        OMElement element = serializer.serializeAnonymousSequence(null, (SequenceMediator) m);
        element.setLocalName(XMLConfigConstants.ONREJECT);
        entitlementElem.addChild(element);
      }
    }
    String onAccept = entitlement.getOnAcceptSeqKey();
    if (onAccept != null) {
      entitlementElem.addAttribute(
          fac.createOMAttribute(XMLConfigConstants.ONACCEPT, nullNS, onAccept));
    } else {
      Mediator m = entitlement.getOnAcceptMediator();
      SequenceMediatorSerializer serializer = new SequenceMediatorSerializer();
      if (m != null && m instanceof SequenceMediator) {
        OMElement element = serializer.serializeAnonymousSequence(null, (SequenceMediator) m);
        element.setLocalName(XMLConfigConstants.ONACCEPT);
        entitlementElem.addChild(element);
      }
    }
    String obligation = entitlement.getObligationsSeqKey();
    if (obligation != null) {
      entitlementElem.addAttribute(
          fac.createOMAttribute(EntitlementMediatorFactory.OBLIGATIONS, nullNS, obligation));
    } else {
      Mediator m = entitlement.getObligationsMediator();
      SequenceMediatorSerializer serializer = new SequenceMediatorSerializer();
      if (m != null && m instanceof SequenceMediator) {
        OMElement element = serializer.serializeAnonymousSequence(null, (SequenceMediator) m);
        element.setLocalName(EntitlementMediatorFactory.OBLIGATIONS);
        entitlementElem.addChild(element);
      }
    }
    String advice = entitlement.getAdviceSeqKey();
    if (advice != null) {
      entitlementElem.addAttribute(
          fac.createOMAttribute(EntitlementMediatorFactory.ADVICE, nullNS, advice));
    } else {
      Mediator m = entitlement.getAdviceMediator();
      SequenceMediatorSerializer serializer = new SequenceMediatorSerializer();
      if (m != null && m instanceof SequenceMediator) {
        OMElement element = serializer.serializeAnonymousSequence(null, (SequenceMediator) m);
        element.setLocalName(EntitlementMediatorFactory.ADVICE);
        entitlementElem.addChild(element);
      }
    }

    return entitlementElem;
  }
 public void setStatisticIdForMediators(ArtifactHolder holder) {
   for (Mediator mediator : mediators) {
     mediator.setComponentStatisticsId(holder);
   }
 }