org.apache.servicecomb.swagger.invocation.exception.InvocationException Java Examples

The following examples show how to use org.apache.servicecomb.swagger.invocation.exception.InvocationException. 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: AuthenticationFilter.java    From scaffold with Apache License 2.0 7 votes vote down vote up
@Override
public Response afterReceiveRequest(Invocation invocation, HttpServletRequestEx httpServletRequestEx) {
  if (isInvocationNeedValidate(invocation.getMicroserviceName(), invocation.getOperationName())) {
    String token = httpServletRequestEx.getHeader(AUTHORIZATION);
    if (StringUtils.isNotEmpty(token)) {
      String userName = template
          .getForObject("cse://" + USER_SERVICE_NAME + "/validate?token={token}", String.class, token);
      if (StringUtils.isNotEmpty(userName)) {
        //Add header
        invocation.getContext().put(EDGE_AUTHENTICATION_NAME, userName);
      } else {
        return Response
            .failResp(new InvocationException(Status.UNAUTHORIZED, "authentication failed, invalid token"));
      }
    } else {
      return Response.failResp(
          new InvocationException(Status.UNAUTHORIZED, "authentication failed, missing AUTHORIZATION header"));
    }
  }
  return null;
}
 
Example #2
Source File: ProducerOperationFilterTest.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void should_unify_IllegalArgumentException_message_when_convert_exception() throws NoSuchMethodException {
  setInvokeSyncMethod();
  new Expectations() {
    {
      invocation.toProducerArguments();
      result = new Object[] {1};
    }
  };

  CompletableFuture<Response> future = filter.onFilter(invocation, FilterNode.EMPTY);
  assertThat(future).hasFailedWithThrowableThat()
      .isInstanceOf(IllegalArgumentException.class)
      .hasMessage("wrong number of arguments");

  InvocationException throwable = Exceptions
      .convert(invocation, catchThrowable(() -> future.get()), INTERNAL_SERVER_ERROR);
  assertThat(throwable).hasCauseInstanceOf(IllegalArgumentException.class);
  CommonExceptionData data = (CommonExceptionData) throwable.getErrorData();
  assertThat(data.getMessage()).isEqualTo("Parameters not valid or types not match.");
}
 
Example #3
Source File: PaymentServiceImpl.java    From scaffold with Apache License 2.0 6 votes vote down vote up
@Override
@PostMapping(path = "deposit")
@Transactional(isolation = Isolation.SERIALIZABLE)
public ResponseEntity<Boolean> deposit(@RequestBody PaymentDTO payment) {
  if (validatePayment(payment)) {
    if (checkBalance(payment)) {
      if (recordPayment(payment, PaymentType.DEPOSIT)) {
        if (recordDeposit(payment)) {
          if (cutWithBank(payment)) {
            return new ResponseEntity<>(true, HttpStatus.OK);
          }
          throw new InvocationException(BAD_REQUEST, "cut with bank failed");
        }
        throw new InvocationException(BAD_REQUEST, "record deposit failed");
      }
      throw new InvocationException(BAD_REQUEST, "record payment failed");
    }
    throw new InvocationException(BAD_REQUEST, "check balance failed");
  }
  throw new InvocationException(BAD_REQUEST, "incorrect payment request");
}
 
Example #4
Source File: SagaController.java    From servicecomb-saga-actuator with Apache License 2.0 6 votes vote down vote up
@ApiResponses({
    @ApiResponse(code = 200, response = String.class, message = "success"),
    @ApiResponse(code = 400, response = String.class, message = "illegal request content"),
})
@CrossOrigin
@RequestMapping(value = "requests", method = GET)
public ResponseEntity<SagaExecutionQueryResult> queryExecutions(
    @RequestParam(name = "pageIndex") String pageIndex,
    @RequestParam(name = "pageSize") String pageSize,
    @RequestParam(name = "startTime") String startTime,
    @RequestParam(name = "endTime") String endTime) {
  if (isRequestParamValid(pageIndex, pageSize, startTime, endTime)) {
    try {
      return ResponseEntity.ok(queryService.querySagaExecution(pageIndex, pageSize, startTime, endTime));
    } catch (ParseException ignored) {
      throw new InvocationException(BAD_REQUEST, "illegal request content");
    }
  } else {
    throw new InvocationException(BAD_REQUEST, "illegal request content");
  }
}
 
Example #5
Source File: UserServiceImpl.java    From scaffold with Apache License 2.0 6 votes vote down vote up
@Override
@PostMapping(path = "login")
public ResponseEntity<Boolean> login(@RequestBody UserDTO user) {
  if (validateUser(user)) {
    UserEntity dbUser = repository.findByName(user.getName());
    if (dbUser != null) {
      if (dbUser.getPassword().equals(user.getPassword())) {
        String token = tokenStore.generate(user.getName());
        HttpHeaders headers = generateAuthenticationHeaders(token);
        //add authentication header
        return new ResponseEntity<>(true, headers, HttpStatus.OK);
      }
      throw new InvocationException(BAD_REQUEST, "wrong password");
    }
    throw new InvocationException(BAD_REQUEST, "user name not exist");
  }
  throw new InvocationException(BAD_REQUEST, "incorrect user");
}
 
Example #6
Source File: UserServiceImpl.java    From servicecomb-samples with Apache License 2.0 6 votes vote down vote up
public SessionInfo getSession(String sessionId) {
  if (sessionId == null) {
    throw new InvocationException(405, "", "invalid session.");
  }
  SessionInfoModel sessionInfo = sessionMapper.getSessioinInfo(sessionId);
  if (sessionInfo != null) {
    if (System.currentTimeMillis() - sessionInfo.getActiveTime().getTime() > 10 * 60 * 1000) {
      LOGGER.info("user session expired.");
      return null;
    } else {
      sessionMapper.updateSessionInfo(sessionInfo.getSessiondId());
      return SessionInfoModel.toSessionInfo(sessionInfo);
    }
  }
  return null;
}
 
Example #7
Source File: FileServiceImpl.java    From servicecomb-samples with Apache License 2.0 6 votes vote down vote up
public boolean deleteFile(String id) {
    String session = ContextUtils.getInvocationContext().getContext("session-info");
    if (session == null) {
        throw new InvocationException(403, "", "not allowed");
    } else {
        SessionInfo sessionInfo = null;
        try {
            sessionInfo = JsonUtils.readValue(session.getBytes("UTF-8"), SessionInfo.class);
        } catch (Exception e) {
            throw new InvocationException(403, "", "session not allowed");
        }
        if (sessionInfo == null || !sessionInfo.getRoleName().equals("admin")) {
            throw new InvocationException(403, "", "not allowed");
        }
    }
    return fileService.deleteFile(id);
}
 
Example #8
Source File: FileServiceImpl.java    From servicecomb-samples with Apache License 2.0 6 votes vote down vote up
public boolean deleteFile(String id) {
    String session = ContextUtils.getInvocationContext().getContext("session-info");
    if (session == null) {
        throw new InvocationException(403, "", "not allowed");
    } else {
        SessionInfo sessionInfo = null;
        try {
            sessionInfo = JsonUtils.readValue(session.getBytes("UTF-8"), SessionInfo.class);
        } catch (Exception e) {
            throw new InvocationException(403, "", "session not allowed");
        }
        if (sessionInfo == null || !sessionInfo.getRoleName().equals("admin")) {
            throw new InvocationException(403, "", "not allowed");
        }
    }
    return fileService.deleteFile(id);
}
 
Example #9
Source File: FlightBookingController.java    From servicecomb-saga-actuator with Apache License 2.0 6 votes vote down vote up
@ApiResponses({
    @ApiResponse(code = 200, response = String.class, message = "authenticated user"),
    @ApiResponse(code = 403, response = String.class, message = "unauthenticated user")
})
@RequestMapping(value = "bookings", method = POST, consumes = APPLICATION_FORM_URLENCODED_VALUE, produces = TEXT_PLAIN_VALUE)
public ResponseEntity<String> book(@RequestAttribute String customerId) {
  if (!customers.contains(customerId)) {
    throw new InvocationException(FORBIDDEN, "No such customer with id " + customerId);
  }

  return ResponseEntity.ok(String.format("{\n"
          + "  \"body\": \"Flight booked with id %s for customer %s\"\n"
          + "}",
      UUID.randomUUID().toString(),
      customerId));
}
 
Example #10
Source File: TestRestProducerInvocation.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void invokeSendFail(@Mocked InvocationException expected) {
  restProducerInvocation = new MockUp<RestProducerInvocation>() {
    @Mock
    void sendFailResponse(Throwable throwable) {
      throwableOfSendFailResponse = throwable;
    }

    @Mock
    void findRestOperation() {
      throw expected;
    }

    @Mock
    void scheduleInvocation() {
      throw new IllegalStateException("must not invoke scheduleInvocation");
    }
  }.getMockInstance();

  restProducerInvocation.invoke(transport, requestEx, responseEx, httpServerFilters);

  Assert.assertSame(expected, throwableOfSendFailResponse);
}
 
Example #11
Source File: TestAbstractRestInvocation.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void sendFailResponseHaveProduceProcessor() {
  Holder<Response> result = new Holder<>();
  restInvocation = new AbstractRestInvocationForTest() {
    @Override
    protected void doInvoke() {
    }

    @Override
    protected void sendResponseQuietly(Response response) {
      result.value = response;
    }
  };
  initRestInvocation();
  restInvocation.produceProcessor = ProduceProcessorManager.INSTANCE.findDefaultPlainProcessor();

  Throwable e = new InvocationException(Status.BAD_GATEWAY, "");
  restInvocation.sendFailResponse(e);
  Assert.assertSame(e, result.value.getResult());
  Assert.assertSame(
      ProduceProcessorManager.INSTANCE.findDefaultPlainProcessor(), restInvocation.produceProcessor);
}
 
Example #12
Source File: AuthHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
protected void doHandle(Invocation invocation, AsyncResponse asyncResp, Boolean authSucc, Throwable authException) {
  if (authException != null) {
    asyncResp.consumerFail(new InvocationException(Status.UNAUTHORIZED, (Object) authException.getMessage()));
    return;
  }

  if (!authSucc) {
    asyncResp.consumerFail(new InvocationException(Status.UNAUTHORIZED, (Object) "auth failed"));
  }

  LOGGER.debug("auth success.");
  try {
    invocation.next(asyncResp);
  } catch (Throwable e) {
    asyncResp.consumerFail(e);
  }
}
 
Example #13
Source File: RestProducerInvocation.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public void invoke(Transport transport, HttpServletRequestEx requestEx, HttpServletResponseEx responseEx,
    List<HttpServerFilter> httpServerFilters) {
  this.transport = transport;
  this.requestEx = requestEx;
  this.responseEx = responseEx;
  this.httpServerFilters = httpServerFilters;
  requestEx.setAttribute(RestConst.REST_REQUEST, requestEx);

  try {
    findRestOperation();
  } catch (InvocationException e) {
    sendFailResponse(e);
    return;
  }

  scheduleInvocation();
}
 
Example #14
Source File: TestImpl.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public String testException(int code) {
  String strCode = String.valueOf(code);
  switch (code) {
    case 200:
      return strCode;
    case 456:
      throw new InvocationException(code, strCode, strCode + " error");
    case 556:
      throw new InvocationException(code, strCode, Arrays.asList(strCode + " error"));
    case 557:
      throw new InvocationException(code, strCode, Arrays.asList(Arrays.asList(strCode + " error")));
    default:
      break;
  }

  return "not expected";
}
 
Example #15
Source File: AuthHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
protected void doHandle(Invocation invocation, AsyncResponse asyncResp, Boolean authSucc, Throwable authException) {
  if (authException != null) {
    asyncResp.consumerFail(new InvocationException(Status.UNAUTHORIZED, (Object) authException.getMessage()));
    return;
  }

  if (!authSucc) {
    asyncResp.consumerFail(new InvocationException(Status.UNAUTHORIZED, (Object) "auth failed"));
  }

  LOGGER.debug("auth success.");
  try {
    invocation.next(asyncResp);
  } catch (Throwable e) {
    asyncResp.consumerFail(e);
  }
}
 
Example #16
Source File: RestBodyHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Buffer buff) {
  if (failed) {
    return;
  }
  uploadSize += buff.length();
  if (bodyLimit != -1 && uploadSize > bodyLimit) {
    failed = true;
    // enqueue a delete for the error uploads
    context.fail(new InvocationException(Status.REQUEST_ENTITY_TOO_LARGE,
        Status.REQUEST_ENTITY_TOO_LARGE.getReasonPhrase()));
    context.vertx().runOnContext(v -> deleteFileUploads());
  } else {
    // multipart requests will not end up in the request body
    // url encoded should also not, however jQuery by default
    // post in urlencoded even if the payload is something else
    if (!isMultipart /* && !isUrlEncoded */) {
      body.appendBuffer(buff);
    }
  }
}
 
Example #17
Source File: TestMaxHttpUrlLength.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void testUrlNotLongerThan4096() {
  RestTemplate restTemplate = RestTemplateBuilder.create();

  String q = Strings.repeat("q", 4096 - "GET /springmvc/controller/sayhi?name=".length() - " HTTP/1.1\r".length());
  TestMgr.check("hi " + q + " [" + q + "]",
      restTemplate.getForObject("cse://springmvc/springmvc/controller/sayhi?name=" + q,
          String.class));

  q = Strings.repeat("q", 4096 + 1 - "GET /springmvc/controller/sayhi?name=".length() - " HTTP/1.1\r".length());
  try {
    restTemplate.getForObject("cse://springmvc/springmvc/controller/sayhi?name=" + q,
        String.class);
    TestMgr.check(true, false);
  } catch (InvocationException e) {
    TestMgr.check(414, e.getStatusCode());
  }
}
 
Example #18
Source File: TestImpl.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public String testException(int code) {
  String strCode = String.valueOf(code);
  switch (code) {
    case 200:
      return strCode;
    case 456:
      throw new InvocationException(code, strCode, strCode + " error");
    case 556:
      throw new InvocationException(code, strCode, Arrays.asList(strCode + " error"));
    case 557:
      throw new InvocationException(code, strCode, Arrays.asList(Arrays.asList(strCode + " error")));
    default:
      break;
  }

  return "not expected";
}
 
Example #19
Source File: TestVertxRestDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void failureHandlerErrorDataWithInvocation(@Mocked RoutingContext context, @Mocked InvocationException e) {
  RestProducerInvocation restProducerInvocation = new RestProducerInvocation();

  ErrorDataDecoderException edde = new ErrorDataDecoderException(e);
  MockHttpServerResponse response = new MockHttpServerResponse();
  new Expectations() {
    {
      context.get(RestConst.REST_PRODUCER_INVOCATION);
      result = restProducerInvocation;
      context.failure();
      returns(edde, edde);
      context.response();
      result = response;
    }
  };

  Deencapsulation.invoke(dispatcher, "failureHandler", context);

  Assert.assertSame(e, this.throwable);
  Assert.assertTrue(response.responseClosed);
}
 
Example #20
Source File: ConsumerQpsFlowControlHandler.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 (!Config.INSTANCE.isConsumerEnabled()) {
    invocation.next(asyncResp);
    return;
  }

  QpsController qpsController = qpsControllerMgr.getOrCreate(invocation.getMicroserviceName(), invocation);
  if (qpsController.isLimitNewRequest()) {
    // return http status 429
    CommonExceptionData errorData = new CommonExceptionData("rejected by qps flowcontrol");
    asyncResp.consumerFail(
        new InvocationException(QpsConst.TOO_MANY_REQUESTS_STATUS, errorData));
    return;
  }

  invocation.next(asyncResp);
}
 
Example #21
Source File: JaxrsClient.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private static void testClientTimeoutAdd(RestTemplate template, String cseUrlPrefix) {
  Map<String, String> params = new HashMap<>();
  params.put("a", "5");
  params.put("b", "20");
  boolean isExcep = false;
  try {
    template.postForObject(cseUrlPrefix + "add", params, Integer.class);
  } catch (InvocationException e) {
    isExcep = true;
    // implement timeout with same error code and message for rest and highway
    TestMgr.check(408, e.getStatus().getStatusCode());
    TestMgr.check(true,
        e.getErrorData().toString().contains("CommonExceptionData [message=Request Timeout. Details:"));
  }

  TestMgr.check(true, isExcep);
}
 
Example #22
Source File: AbortFault.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void injectFault(Invocation invocation, FaultParam faultParam, AsyncResponse asyncResponse) {
  if (!shouldAbort(invocation, faultParam)) {
    asyncResponse.success(SUCCESS_RESPONSE);
    return;
  }

  // get the config values related to abort percentage.
  int errorCode = FaultInjectionUtil.getFaultInjectionConfig(invocation, "abort.httpStatus");
  if (errorCode == FaultInjectionConst.FAULT_INJECTION_DEFAULT_VALUE) {
    LOGGER.debug("Fault injection: Abort error code is not configured");
    asyncResponse.success(SUCCESS_RESPONSE);
    return;
  }

  // if request need to be abort then return failure with given error code
  CommonExceptionData errorData = new CommonExceptionData(ABORTED_ERROR_MSG);
  asyncResponse.consumerFail(new InvocationException(errorCode, ABORTED_ERROR_MSG, errorData));
}
 
Example #23
Source File: TestAbstractRestInvocation.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void initProduceProcessorNull() {
  new Expectations() {
    {
      requestEx.getHeader(HttpHeaders.ACCEPT);
      result = "notExistType";
    }
  };
  restInvocation = new AbstractRestInvocationForTest() {
    @Override
    public void sendFailResponse(Throwable throwable) {
    }
  };
  initRestInvocation();

  expectedException.expect(InvocationException.class);
  expectedException
      .expectMessage(
          "InvocationException: code=406;msg=CommonExceptionData [message=Accept notExistType is not supported]");

  restInvocation.initProduceProcessor();
}
 
Example #24
Source File: ProviderBizkeeperCommand.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isFailedResponse(Response resp) {
  if (resp.isFailed()) {
    if (InvocationException.class.isInstance(resp.getResult())) {
      InvocationException e = (InvocationException) resp.getResult();
      return e.getStatusCode() == ExceptionFactory.PRODUCER_INNER_STATUS_CODE;
    } else {
      return true;
    }
  } else {
    return false;
  }
}
 
Example #25
Source File: UserServiceImpl.java    From scaffold with Apache License 2.0 5 votes vote down vote up
@Override
@PostMapping(path = "logon")
public ResponseEntity<Boolean> logon(@RequestBody UserDTO user) {
  if (validateUser(user)) {
    UserEntity dbUser = repository.findByName(user.getName());
    if (dbUser == null) {
      UserEntity entity = new UserEntity(user.getName(), user.getPassword());
      repository.save(entity);
      return new ResponseEntity<>(true, HttpStatus.OK);
    }
    throw new InvocationException(BAD_REQUEST, "user name had exist");
  }
  throw new InvocationException(BAD_REQUEST, "incorrect user");
}
 
Example #26
Source File: RedisClientUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static String syncQuery(String id) {
  CompletableFuture<String> future = doQuery(id, true);
  try {
    return future.get();
  } catch (InterruptedException | ExecutionException e) {
    throw new InvocationException(Status.INTERNAL_SERVER_ERROR.getStatusCode(),
        Status.INTERNAL_SERVER_ERROR.getReasonPhrase(), (Object) "Failed to query from redis.", e);
  }
}
 
Example #27
Source File: CodeFirstSpringmvc.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@GetMapping(path = "/retrySuccess")
public int retrySuccess(@RequestParam("a") int a, @RequestParam("b") int b) {
  if (firstInovcation.getAndDecrement() > 0) {
    throw new InvocationException(Status.SERVICE_UNAVAILABLE, "try again later.");
  }
  return a + b;
}
 
Example #28
Source File: CodeFirstSpringmvc.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@RequestMapping(path = "/fallback/returnnull/{name}", method = RequestMethod.GET)
@ApiResponses(value = {@ApiResponse(code = 200, response = String.class, message = "xxx"),
    @ApiResponse(code = 490, response = CommonExceptionData.class, message = "xxx")})
public String fallbackReturnNull(@PathVariable(name = "name") String name) {
  if ("throwexception".equals(name)) {
    throw new InvocationException(490, "490", new CommonExceptionData("xxx"));
  }
  return name;
}
 
Example #29
Source File: CodeFirstSpringmvc.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@RequestMapping(path = "/fallback/throwexception/{name}", method = RequestMethod.GET)
@ApiResponses(value = {@ApiResponse(code = 200, response = String.class, message = "xxx"),
    @ApiResponse(code = 490, response = CommonExceptionData.class, message = "xxx")})
public String fallbackThrowException(@PathVariable(name = "name") String name) {
  if ("throwexception".equals(name)) {
    throw new InvocationException(490, "490", new CommonExceptionData("xxx"));
  }
  return name;
}
 
Example #30
Source File: ControllerImpl.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@PostMapping(path = "/sayhello/{name}")
public String sayHello(@PathVariable("name") String name) {
  if ("exception".equals(name)) {
    throw new InvocationException(Status.SERVICE_UNAVAILABLE, "");
  }
  return "hello " + name;
}