Java Code Examples for org.apache.servicecomb.core.Invocation#getContext()

The following examples show how to use org.apache.servicecomb.core.Invocation#getContext() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProviderQpsFlowControlHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
  if (invocation.getHandlerIndex() > 0) {
    // handlerIndex > 0, which means this handler is executed in handler chain.
    // As this flow control logic has been executed in advance, this time it should be ignored.
    invocation.next(asyncResp);
    return;
  }

  // The real executing position of this handler is no longer in handler chain, but in AbstractRestInvocation.
  // Therefore, the Invocation#next() method should not be called below.
  if (!Config.INSTANCE.isProviderEnabled()) {
    return;
  }

  String microserviceName = invocation.getContext(Const.SRC_MICROSERVICE);
  QpsController qpsController =
      StringUtils.isEmpty(microserviceName)
          ? qpsControllerMgr.getGlobalQpsController()
          : qpsControllerMgr.getOrCreate(microserviceName, invocation);
  isLimitNewRequest(qpsController, asyncResp);
}
 
Example 2
Source File: RouterServerListFilter.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private Map<String, String> addHeaders(Invocation invocation) {
  Map<String, String> headers = new HashMap<>();
  if (invocation.getContext(ROUTER_HEADER) != null) {
    Map<String, String> canaryContext = null;
    try {
      canaryContext = JsonUtils.OBJ_MAPPER
          .readValue(invocation.getContext(ROUTER_HEADER),
              new TypeReference<Map<String, String>>() {
              });
    } catch (JsonProcessingException e) {
      LOGGER.error("canary context serialization failed");
    }
    if (canaryContext != null) {
      headers.putAll(canaryContext);
    }
  }
  invocation.getInvocationArguments().forEach((k, v) -> headers.put(k, v == null ? null : v.toString()));
  headers.putAll(invocation.getContext());
  return headers;
}
 
Example 3
Source File: TestProviderQpsFlowControlHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testGlobalQpsControl(final @Injectable Invocation invocation,
    final @Injectable AsyncResponse asyncResp) throws Exception {
  new Expectations() {
    {
      invocation.getHandlerIndex();
      result = 0;
      invocation.getContext(Const.SRC_MICROSERVICE);
      result = "test";
      invocation.getOperationMeta();
      result = QpsControllerManagerTest.getMockOperationMeta("pojo", "server", "opr");
      invocation.getSchemaId();
      result = "server";
      asyncResp.producerFail((Throwable) any);
      result = new RuntimeException("test error");
    }
  };

  ProviderQpsFlowControlHandler gHandler = new ProviderQpsFlowControlHandler();
  gHandler.handle(invocation, asyncResp);

  ArchaiusUtils.setProperty(Config.PROVIDER_LIMIT_KEY_GLOBAL, 3);

  expectedException.expect(RuntimeException.class);
  expectedException.expectMessage("test error");

  gHandler.handle(invocation, asyncResp);
  gHandler.handle(invocation, asyncResp);
}
 
Example 4
Source File: ProviderAuthHanlder.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {

  String token = invocation.getContext(Const.AUTH_TOKEN);
  if (null != token && authenticationTokenManager.valid(token)) {
    invocation.next(asyncResp);
  } else {
    asyncResp.producerFail(new InvocationException(new HttpStatus(401, "UNAUTHORIZED"), "UNAUTHORIZED"));
  }
}
 
Example 5
Source File: InvocationContextAccessItem.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void appendClientFormattedItem(InvocationFinishEvent finishEvent, StringBuilder builder) {
  Invocation invocation = finishEvent.getInvocation();
  if (null == invocation || invocation.getContext() == null
      || StringUtils.isEmpty(finishEvent.getInvocation().getContext().get(varName))) {
    builder.append(NOT_FOUND);
    return;
  }
  builder.append(finishEvent.getInvocation().getContext().get(varName));
}
 
Example 6
Source File: TraceIdAccessItem.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void appendClientFormattedItem(InvocationFinishEvent finishEvent, StringBuilder builder) {
  Invocation invocation = finishEvent.getInvocation();
  if (invocation == null || invocation.getContext() == null
      || StringUtils.isEmpty(invocation.getContext().get(TRACE_ID))) {
    builder.append(InvocationContextAccessItem.NOT_FOUND);
    return;
  }
  builder.append(invocation.getContext().get(TRACE_ID));
}
 
Example 7
Source File: AuthHandler.java    From servicecomb-samples with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResponse) throws Exception {
  if (invocation.getMicroserviceName().equals("user-service")
      && (invocation.getOperationName().equals("login")
          || (invocation.getOperationName().equals("getSession")))) {
    // login:return session id, set cookie by javascript
    invocation.next(asyncResponse);
  } else {
    // check session
    String sessionId = invocation.getContext("session-id");
    if (sessionId == null) {
      throw new InvocationException(403, "", "session is not valid.");
    }

    String sessionInfo = sessionCache.getIfPresent(sessionId);
    if (sessionInfo != null) {
      try {
        // session info stored in InvocationContext. Microservices can get it. 
        invocation.addContext("session-id", sessionId);
        invocation.addContext("session-info", sessionInfo);
        invocation.next(asyncResponse);
      } catch (Exception e) {
        asyncResponse.complete(Response.failResp(new InvocationException(500, "", e.getMessage())));
      }
      return;
    }

    // In edge, handler is executed in reactively. Must have no blocking logic.
    CompletableFuture<SessionInfo> result = userServiceClient.getGetSessionOperation().getSession(sessionId);
    result.whenComplete((info, e) -> {
      if (result.isCompletedExceptionally()) {
        asyncResponse.complete(Response.failResp(new InvocationException(403, "", "session is not valid.")));
      } else {
        if (info == null) {
          asyncResponse.complete(Response.failResp(new InvocationException(403, "", "session is not valid.")));
          return;
        }
        try {
          // session info stored in InvocationContext. Microservices can get it. 
          invocation.addContext("session-id", sessionId);
          String sessionInfoStr = JsonUtils.writeValueAsString(info);
          invocation.addContext("session-info", sessionInfoStr);
          invocation.next(asyncResponse);
          sessionCache.put(sessionId, sessionInfoStr);
        } catch (Exception ee) {
          asyncResponse.complete(Response.failResp(new InvocationException(500, "", ee.getMessage())));
        }
      }
    });
  }
}
 
Example 8
Source File: AuthHandler.java    From servicecomb-samples with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResponse) throws Exception {
  if (invocation.getMicroserviceName().equals("user-service")
      && (invocation.getOperationName().equals("login")
          || (invocation.getOperationName().equals("getSession")))) {
    // login:return session id, set cookie by javascript
    invocation.next(asyncResponse);
  } else {
    // check session
    String sessionId = invocation.getContext("session-id");
    if (sessionId == null) {
      throw new InvocationException(403, "", "session is not valid.");
    }

    String sessionInfo = sessionCache.getIfPresent(sessionId);
    if (sessionInfo != null) {
      try {
        // session info stored in InvocationContext. Microservices can get it. 
        invocation.addContext("session-id", sessionId);
        invocation.addContext("session-info", sessionInfo);
        invocation.next(asyncResponse);
      } catch (Exception e) {
        asyncResponse.complete(Response.failResp(new InvocationException(500, "", e.getMessage())));
      }
      return;
    }

    // In edge, handler is executed in reactively. Must have no blocking logic.
    CompletableFuture<SessionInfo> result = userServiceClient.getGetSessionOperation().getSession(sessionId);
    result.whenComplete((info, e) -> {
      if (result.isCompletedExceptionally()) {
        asyncResponse.complete(Response.failResp(new InvocationException(403, "", "session is not valid.")));
      } else {
        if (info == null) {
          asyncResponse.complete(Response.failResp(new InvocationException(403, "", "session is not valid.")));
          return;
        }
        try {
          // session info stored in InvocationContext. Microservices can get it. 
          invocation.addContext("session-id", sessionId);
          String sessionInfoStr = JsonUtils.writeValueAsString(info);
          invocation.addContext("session-info", sessionInfoStr);
          invocation.next(asyncResponse);
          sessionCache.put(sessionId, sessionInfoStr);
        } catch (Exception ee) {
          asyncResponse.complete(Response.failResp(new InvocationException(500, "", ee.getMessage())));
        }
      }
    });
  }
}