/**
   * Extract transport headers from the synapse message context.
   *
   * @param synCtx synapse message context
   * @return transport headers map
   */
  public static Map<String, Object> extractTransportProperties(MessageContext synCtx) {
    Map<String, Object> transportPropertyMap = new TreeMap<>();

    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;
      Set<String> axis2PropertySet = headersMap.keySet();
      for (String entry : axis2PropertySet) {
        transportPropertyMap.put(entry, headersMap.get(entry));
      }
    }

    // Adding important transport related properties
    if (axis2MessageCtx.getTo() != null) {
      transportPropertyMap.put(SynapseConstants.HEADER_TO, axis2MessageCtx.getTo().getAddress());
    }

    if (axis2MessageCtx.getFrom() != null) {
      transportPropertyMap.put(
          SynapseConstants.HEADER_FROM, axis2MessageCtx.getFrom().getAddress());
    }

    if (axis2MessageCtx.getWSAAction() != null) {
      transportPropertyMap.put("WSAction", axis2MessageCtx.getWSAAction());
    }

    if (axis2MessageCtx.getSoapAction() != null) {
      transportPropertyMap.put("SOAPAction", axis2MessageCtx.getSoapAction());
    }

    if (axis2MessageCtx.getReplyTo() != null) {
      transportPropertyMap.put(
          SynapseConstants.HEADER_REPLY_TO, axis2MessageCtx.getReplyTo().getAddress());
    }

    if (axis2MessageCtx.getMessageID() != null) {
      transportPropertyMap.put(SynapseConstants.HEADER_MESSAGE_ID, axis2MessageCtx.getMessageID());
    }

    // Remove unnecessary properties
    if (transportPropertyMap.get("Cookie") != null) {
      transportPropertyMap.remove("Cookie");
    }

    return transportPropertyMap;
  }
  public boolean processSecurity(String credentials, MessageContext messageContext) {
    String decodedCredentials = new String(new Base64().decode(credentials.getBytes()));
    String userName = decodedCredentials.split(":")[0];
    String password = decodedCredentials.split(":")[1];
    Axis2MessageContext axis2Msgcontext = null;
    org.apache.axis2.context.MessageContext msgContext;
    axis2Msgcontext = (Axis2MessageContext) messageContext;
    msgContext = axis2Msgcontext.getAxis2MessageContext();
    msgContext.setProperty("username", userName);

    return true;

    /*if ("admin".equals(userName) && "admin".equals(password)) {
        return true;
    } else {
        return false;
    }*/

  }
 protected void setUp() throws Exception {
   super.setUp();
   SynapseConfiguration synCfg = new SynapseConfiguration();
   AxisConfiguration config = new AxisConfiguration();
   testCtx =
       new Axis2MessageContext(
           new org.apache.axis2.context.MessageContext(),
           synCfg,
           new Axis2SynapseEnvironment(new ConfigurationContext(config), synCfg));
   ((Axis2MessageContext) testCtx)
       .getAxis2MessageContext()
       .setConfigurationContext(new ConfigurationContext(config));
 }
  public void testRestURLPostfix3() throws Exception {
    API api = new API(TEST_API, "/services/Foo");
    SynapseConfiguration synapseConfig = new SynapseConfiguration();
    synapseConfig.addAPI(TEST_API, api);

    RESTRequestHandler handler = new RESTRequestHandler();

    MessageContext synCtx = getMessageContext(synapseConfig, false, "/services/Foo/test", "GET");
    // When the service path is in the URL, NHTTP transport removes that portion
    // from the postfix
    ((Axis2MessageContext) synCtx)
        .getAxis2MessageContext()
        .setProperty(NhttpConstants.REST_URL_POSTFIX, "/test");
    handler.process(synCtx);
    checkRestURLPostfix(synCtx, "/test");
  }
Exemplo n.º 5
0
  /**
   * clone the provided message context as a new message, and mark as the messageSequence'th message
   * context of a total of messageCount messages
   *
   * @param synCtx - MessageContext which is subjected to the cloning
   * @param messageSequence - the position of this message of the cloned set
   * @param messageCount - total of cloned copies
   * @return MessageContext the cloned message context
   */
  private MessageContext getClonedMessageContext(
      MessageContext synCtx, int messageSequence, int messageCount) {

    MessageContext newCtx = null;
    try {

      newCtx = MessageHelper.cloneMessageContext(synCtx);

      StatisticsRecord statRecord =
          (StatisticsRecord) newCtx.getProperty(SynapseConstants.STATISTICS_STACK);
      if (statRecord != null) {
        for (StatisticsLog statLog : statRecord.getAllStatisticsLogs()) {
          /*
           * Marks that this statistics log is collected by the
           * request flow.
           */
          statLog.setCollectedByRequestFlow(true);
        }
      }
      // Set isServerSide property in the cloned message context
      ((Axis2MessageContext) newCtx)
          .getAxis2MessageContext()
          .setServerSide(((Axis2MessageContext) synCtx).getAxis2MessageContext().isServerSide());

      if (id != null) {
        // set the parent correlation details to the cloned MC -
        //                              for the use of aggregation like tasks
        newCtx.setProperty(EIPConstants.AGGREGATE_CORRELATION + "." + id, synCtx.getMessageID());
        // set the property MESSAGE_SEQUENCE to the MC for aggregation purposes
        newCtx.setProperty(
            EIPConstants.MESSAGE_SEQUENCE + "." + id,
            String.valueOf(messageSequence)
                + EIPConstants.MESSAGE_SEQUENCE_DELEMITER
                + messageCount);
      } else {
        newCtx.setProperty(
            EIPConstants.MESSAGE_SEQUENCE,
            String.valueOf(messageSequence)
                + EIPConstants.MESSAGE_SEQUENCE_DELEMITER
                + messageCount);
      }
    } catch (AxisFault axisFault) {
      handleException("Error cloning the message context", axisFault, synCtx);
    }

    return newCtx;
  }
Exemplo n.º 6
0
  /** @param synCtx */
  public void evaluate(MessageContext synCtx) {
    String result;
    if (value != null) {
      result = value;
    } else if (expression != null) {
      result = expression.stringValueOf(synCtx);
    } else {
      throw new SynapseException("A value or expression must be specified");
    }

    if (scope == null || XMLConfigConstants.SCOPE_DEFAULT.equals(scope)) {
      synCtx.setProperty(name, result);
    } else if (XMLConfigConstants.SCOPE_AXIS2.equals(scope)) {
      // Setting property into the  Axis2 Message Context
      Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
      org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
      axis2MessageCtx.setProperty(name, result);
    } else if (XMLConfigConstants.SCOPE_CLIENT.equals(scope)) {
      // 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, result);
    } else if (XMLConfigConstants.SCOPE_TRANSPORT.equals(scope)) {
      // 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, result);
      }
      if (headers == null) {
        Map headersMap = new HashMap();
        headersMap.put(name, result);
        axis2MessageCtx.setProperty(
            org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headersMap);
      }
    }
  }
Exemplo n.º 7
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);
      }
    }
  }
Exemplo n.º 8
0
  public void send(MessageContext synCtx) {

    logSetter();

    Integer statisticReportingIndex = null;
    boolean isStatisticsEnabled = RuntimeStatisticCollector.isStatisticsEnabled();
    if (isStatisticsEnabled) {
      statisticReportingIndex =
          OpenEventCollector.reportEntryEvent(
              synCtx,
              getReportingName(),
              definition.getAspectConfiguration(),
              ComponentType.ENDPOINT);
    }

    boolean traceOn = isTraceOn(synCtx);
    boolean traceOrDebugOn = isTraceOrDebugOn(traceOn);

    if (!initialized) {
      // can't send to a non-initialized endpoint. This is a program fault
      throw new IllegalStateException(
          "not initialized, " + "endpoint must be in initialized state");
    }

    prepareForEndpointStatistics(synCtx);

    if (traceOrDebugOn) {
      String address = definition.getAddress();
      if (address == null && synCtx.getTo() != null && synCtx.getTo().getAddress() != null) {
        // compute address for the default endpoint only for logging purposes
        address = synCtx.getTo().getAddress();
      }

      traceOrDebug(
          traceOn,
          "Sending message through endpoint : " + getName() + " resolving to address = " + address);
      traceOrDebug(
          traceOn,
          "SOAPAction: " + (synCtx.getSoapAction() != null ? synCtx.getSoapAction() : "null"));
      traceOrDebug(
          traceOn,
          "WSA-Action: " + (synCtx.getWSAAction() != null ? synCtx.getWSAAction() : "null"));
      if (traceOn && trace.isTraceEnabled()) {
        trace.trace("Envelope : \n" + synCtx.getEnvelope());
      }
    }

    // push the errorHandler sequence into the current message as the fault handler
    if (errorHandler != null) {
      Mediator errorHandlerMediator = synCtx.getSequence(errorHandler);
      if (errorHandlerMediator != null) {
        if (traceOrDebugOn) {
          traceOrDebug(
              traceOn,
              "Setting the onError handler : "
                  + errorHandler
                  + " for the endpoint : "
                  + endpointName);
        }
        synCtx.pushFaultHandler(new MediatorFaultHandler(errorHandlerMediator));
      } else {
        log.warn(
            "onError handler sequence : "
                + errorHandler
                + " for : "
                + endpointName
                + " cannot be found");
      }
    }

    // register this as the immediate fault handler for this message.
    synCtx.pushFaultHandler(this);
    // add this as the last endpoint to process this message - used by statistics counting code
    synCtx.setProperty(SynapseConstants.LAST_ENDPOINT, this);
    // set message level metrics collector
    org.apache.axis2.context.MessageContext axis2Ctx =
        ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    axis2Ctx.setProperty(BaseConstants.METRICS_COLLECTOR, metricsMBean);

    if (contentAware) {
      try {
        RelayUtils.buildMessage(((Axis2MessageContext) synCtx).getAxis2MessageContext(), false);
        axis2Ctx.setProperty(RelayConstants.FORCE_RESPONSE_EARLY_BUILD, Boolean.TRUE);
        if (forceBuildMC) {
          ((Axis2MessageContext) synCtx).getAxis2MessageContext().getEnvelope().build();
        }
      } catch (Exception e) {
        handleException("Error while building message", e);
      }
    }

    evaluateProperties(synCtx);

    // if the envelope preserving set build the envelope
    MediatorProperty preserveEnv = getProperty(SynapseConstants.PRESERVE_ENVELOPE);
    if (preserveEnv != null
        && JavaUtils.isTrueExplicitly(
            preserveEnv.getValue() != null
                ? preserveEnv.getValue()
                : preserveEnv.getEvaluatedExpression(synCtx))) {
      if (traceOrDebugOn) {
        traceOrDebug(
            traceOn,
            "Preserving the envelope by building it before "
                + "sending, since it is explicitly set");
      }
      synCtx.getEnvelope().build();
    }

    // Send the message through this endpoint
    synCtx.getEnvironment().send(definition, synCtx);

    if (isStatisticsEnabled) {
      CloseEventCollector.closeEntryEvent(
          synCtx, getReportingName(), ComponentType.ENDPOINT, statisticReportingIndex, false);
    }
  }
  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);
    }
  }
Exemplo n.º 10
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;
  }