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

The following examples show how to use org.apache.servicecomb.core.Invocation#addContext() . 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: InheritInvocationContextFilter.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether users can inherit specified InvocationContext from outer request
 */
@Override
public Response afterReceiveRequest(Invocation invocation, HttpServletRequestEx requestEx) {
  String invocationContextHeader = requestEx.getHeader(Const.CSE_CONTEXT);
  if (StringUtils.isEmpty(invocationContextHeader)) {
    return null;
  }

  try {
    @SuppressWarnings("unchecked")
    Map<String, String> invocationContext =
        JsonUtils.readValue(invocationContextHeader.getBytes(StandardCharsets.UTF_8), Map.class);
    // Here only the specific invocation context "allowInherit" can be inherited,
    // and other context key-value pairs are ignored.
    // If you want to inherit invocation context from outer requests,
    // it's better to implement such a white-list logic to filter the invocation context.
    // CAUTION: to avoid potential security problem, please do not add all invocation context key-value pairs
    // into InvocationContext without checking or filtering.
    if (!StringUtils.isEmpty(invocationContext.get("allowInherit"))) {
      invocation.addContext("allowInherit", invocationContext.get("allowInherit"));
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
  return null;
}
 
Example 2
Source File: CseClientHttpRequest.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
protected Invocation prepareInvocation(Map<String, Object> swaggerArguments) {
  Invocation invocation =
      InvocationFactory.forConsumer(requestMeta.getReferenceConfig(),
          requestMeta.getOperationMeta(),
          requestMeta.getOperationMeta().buildBaseConsumerRuntimeType(),
          swaggerArguments);

  invocation.getHandlerContext().put(RestConst.REST_CLIENT_REQUEST_PATH,
      path + (this.uri.getRawQuery() == null ? "" : "?" + this.uri.getRawQuery()));

  if (context != null) {
    invocation.addContext(context.getContext());
    invocation.addLocalContext(context.getLocalContext());
  }

  if (responseType != null &&
      !(responseType instanceof Class && Part.class.isAssignableFrom((Class<?>) responseType))) {
    invocation.setSuccessResponseType(TypeFactory.defaultInstance().constructType(responseType));
  }

  invocation.getHandlerContext().put(RestConst.CONSUMER_HEADER, httpHeaders);
  return invocation;
}
 
Example 3
Source File: RouterInvokeFilter.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
/**
 * pass through headers
 *
 * @param invocation
 * @param httpServletRequestEx
 * @return
 */
@Override
public Response afterReceiveRequest(Invocation invocation,
    HttpServletRequestEx httpServletRequestEx) {
  if (!isHaveHeadersRule()) {
    return null;
  }
  if (!RouterRuleCache.isServerContainRule(invocation.getMicroserviceName())) {
    return null;
  }
  if (loadHeaders()) {
    Map<String, String> headerMap = getHeaderMap(httpServletRequestEx);
    try {
      invocation.addContext(ROUTER_HEADER, JsonUtils.OBJ_MAPPER.writeValueAsString(headerMap));
    } catch (JsonProcessingException e) {
      LOGGER.error("canary context serialization failed");
    }
  }
  return null;
}
 
Example 4
Source File: TestHighwayCodec.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecodeRequestTraceId(@Mocked Endpoint endpoint) throws Exception {
  commonMock();

  Invocation invocation = new Invocation(endpoint, operationMeta, null);

  invocation.addContext("X-B3-traceId", "test1");
  Assert.assertEquals("test1", invocation.getContext("X-B3-traceId"));

  RequestHeader headers = new RequestHeader();
  Map<String, String> context = new HashMap<>();
  headers.setContext(context);
  HighwayCodec.decodeRequest(invocation, headers, operationProtobuf, bodyBuffer);
  Assert.assertEquals("test1", invocation.getContext("X-B3-traceId"));

  context.put("X-B3-traceId", "test2");
  HighwayCodec.decodeRequest(invocation, headers, operationProtobuf, bodyBuffer);
  Assert.assertEquals("test2", invocation.getContext("X-B3-traceId"));
}
 
Example 5
Source File: ConsumerAuthHandler.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 {

  Optional<String> token = Optional.ofNullable(athenticationTokenManager.getToken());
  if (!token.isPresent()) {
    asyncResp.consumerFail(
        new IllegalStateException("rejected by consumer authentication handler"));
    return;
  }
  invocation.addContext(Const.AUTH_TOKEN, token.get());
  invocation.next(asyncResp);
}
 
Example 6
Source File: InvocationFactory.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static Invocation forConsumer(ReferenceConfig referenceConfig, OperationMeta operationMeta,
    InvocationRuntimeType invocationRuntimeType, Map<String, Object> swaggerArguments) {
  Invocation invocation = new Invocation(referenceConfig,
      operationMeta,
      invocationRuntimeType,
      swaggerArguments);
  invocation.addContext(Const.SRC_MICROSERVICE, getMicroserviceName());
  return invocation;
}
 
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())));
        }
      }
    });
  }
}