io.vertx.core.eventbus.ReplyException Java Examples

The following examples show how to use io.vertx.core.eventbus.ReplyException. 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: ApiVerticle.java    From gushici with GNU General Public License v3.0 6 votes vote down vote up
private void returnError(RoutingContext routingContext) {
    JsonObject result = new JsonObject();
    int errorCode = routingContext.statusCode() > 0 ? routingContext.statusCode() : 500;
    // 不懂 Vert.x 为什么 EventBus 和 Web 是两套异常系统
    if (routingContext.failure() instanceof ReplyException) {
        errorCode = ((ReplyException) routingContext.failure()).failureCode();
    }
    result.put("error-code", errorCode);
    if (routingContext.failure() != null) {
        result.put("reason", routingContext.failure().getMessage());
    }
    setCommonHeader(routingContext.response()
        .setStatusCode(errorCode)
        .putHeader("content-type", "application/json; charset=utf-8"))
        .end(result.encodePrettily());
}
 
Example #2
Source File: DataService.java    From gushici with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param message example: {format: "png", categories: [shenghuo, buyi]}
 */
private void getGushiciFromRedis(Message<JsonObject> message) {
    JsonArray realCategory = new JsonArray()
        .add("png".equals(message.body().getString("format")) ? "img" : "json")
        .addAll(message.body().getJsonArray("categories"));
    checkAndGetKey(realCategory)
        .compose(key -> Future.<String>future(s -> redisClient.srandmember(key, s))) // 从 set 随机返回一个对象
        .setHandler(res -> {
            if (res.succeeded()) {
                message.reply(res.result());
            } else {
                if (res.cause() instanceof ReplyException) {
                    ReplyException exception = (ReplyException) res.cause();
                    message.fail(exception.failureCode(), exception.getMessage());
                } else {
                    message.fail(500, res.cause().getMessage());
                }
            }
        });
}
 
Example #3
Source File: MessageConsumerFailureTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
void verifyFailure(String address, String expectedMessage, boolean explicit) throws InterruptedException {
    BlockingQueue<Object> synchronizer = new LinkedBlockingQueue<>();
    eventBus.request(address, "hello", ar -> {
        try {
            if (ar.cause() != null) {
                synchronizer.put(ar.cause());
            } else {
                synchronizer.put(false);
            }
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    });
    Object ret = synchronizer.poll(2, TimeUnit.SECONDS);
    assertTrue(ret instanceof ReplyException);
    ReplyException replyException = (ReplyException) ret;
    if (!explicit) {
        assertEquals(ConsumeEvent.FAILURE_CODE, replyException.failureCode());
    } else {
        assertEquals(ConsumeEvent.EXPLICIT_FAILURE_CODE, replyException.failureCode());
    }
    assertEquals(expectedMessage, replyException.getMessage());
}
 
Example #4
Source File: ProxyHandler.java    From vertx-service-proxy with Apache License 2.0 6 votes vote down vote up
private Handler<Message<JsonObject>> configureHandler(List<Function<Message<JsonObject>, Future<Message<JsonObject>>>> interceptors) {
  Handler<Message<JsonObject>> handler = this;
  if (interceptors != null) {
    for (Function<Message<JsonObject>, Future<Message<JsonObject>>> interceptor : interceptors) {
      Handler<Message<JsonObject>> prev = handler;
      handler = msg -> {
        Future<Message<JsonObject>> fut = interceptor.apply(msg);
        fut.onComplete(ar -> {
          if (ar.succeeded()) {
            prev.handle(msg);
          } else {
            ReplyException exception = (ReplyException) ar.cause();
            msg.fail(exception.failureCode(), exception.getMessage());
          }
        });
      };
    }
  }
  return handler;
}
 
Example #5
Source File: BusTest.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
private void assertSend(TestContext context, String address, Object body, DeliveryOptions options, int times) {
  context.assertTrue(times > 0, "Could not send message " + body + " to address " + address);
  vertx.eventBus().request(address, body, options, ar -> {
    if (ar.failed()) {
      ReplyException ex = (ReplyException) ar.cause();
      if (ex.failureType() == NO_HANDLERS) {
        // Wait 10 ms to be sure consumer is deployed
        vertx.setTimer(10, id -> {
          assertSend(context, address, body, options, times - 1);
        });
      } else {
        context.fail();
      }
    }
  });
}
 
Example #6
Source File: AbstractRequestResponseEndpoint.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private ServiceInvocationException getServiceInvocationException(final Throwable error) {

        if (error instanceof ServiceInvocationException) {
            return (ServiceInvocationException) error;
        } else if (error instanceof ReplyException) {
            final ReplyException ex = (ReplyException) error;
            switch (ex.failureType()) {
            case TIMEOUT:
                return new ServerErrorException(
                        HttpURLConnection.HTTP_UNAVAILABLE,
                        "request could not be processed at the moment");
            default:
                return new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        } else {
            return new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
    }
 
Example #7
Source File: RequestResponseEndpoint.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private ServiceInvocationException getServiceInvocationException(final Throwable error) {

        if (error instanceof ServiceInvocationException) {
            return (ServiceInvocationException) error;
        } else if (error instanceof ReplyException) {
            final ReplyException ex = (ReplyException) error;
            switch (ex.failureType()) {
            case TIMEOUT:
                return new ServerErrorException(
                        HttpURLConnection.HTTP_UNAVAILABLE,
                        "request could not be processed at the moment");
            default:
                return new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        } else {
            return new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
    }
 
Example #8
Source File: ApiVerticle.java    From gushici with GNU General Public License v3.0 5 votes vote down vote up
private void returnGushici(RoutingContext routingContext, String obj, JsonObject params) {
    switch (params.getString("format")) {
        case "json": {
            returnJson(routingContext, new JsonObject(obj));
            break;
        }
        case "svg": {
            setCommonHeader(routingContext.response()
                .putHeader("Content-Type", "image/svg+xml; charset=utf-8"))
                .end(ConvertUtil.getSvg(new JsonObject(obj).getString("content"),
                            params.getDouble("font-size"),
                            params.getDouble("spacing")));
            break;
        }
        case "txt": {
            setCommonHeader(routingContext.response()
                .putHeader("Content-Type", "text/plain; charset=utf-8"))
                .end(new JsonObject(obj).getString("content"));
            break;
        }
        case "png": {
            ConvertUtil.getImageFromBase64(obj).setHandler(res -> {
                if (res.succeeded()) {
                    setCommonHeader(routingContext.response()
                        .putHeader("Content-Type", "image/png"))
                        .putHeader("Content-Length", res.result().length() + "")
                        .write(res.result()).end();
                } else {
                    routingContext.fail(res.cause());
                }
            });
            break;
        }
        default:
            routingContext.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 400, "参数错误"));
    }
}
 
Example #9
Source File: ClusteredTest.java    From vertx-service-proxy with Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalServiceShouldBeUnreachable() {
  AtomicReference<Throwable> result = new AtomicReference<>();
  Service service = Service.createProxy(consumerNode.get(), "my.local.service");
  service.hello("vert.x", (ar) -> {
    assertThat(ar.succeeded()).isFalse().withFailMessage("Local service should not be accessible from a different node in the cluster");
    assertThat(ar.cause()).isNotNull();
    assertThat(ar.cause()).isInstanceOf(ReplyException.class);
    ReplyException exception = (ReplyException) ar.cause();
    assertThat(exception.failureType()).isEqualTo(ReplyFailure.NO_HANDLERS);
    result.set(ar.cause());
  });
  Awaitility.await().atMost(10, TimeUnit.SECONDS).until(() -> result.get() != null);
}
 
Example #10
Source File: ServiceProxyTest.java    From vertx-service-proxy with Apache License 2.0 5 votes vote down vote up
private void checkCause(Throwable cause) {
  assertNotNull(cause);
  assertTrue(cause instanceof ReplyException);
  assertFalse(cause instanceof ServiceException);
  ReplyException re = (ReplyException) cause;
  assertEquals(ReplyFailure.NO_HANDLERS, re.failureType());
  testComplete();
}
 
Example #11
Source File: ServiceProxyTest.java    From vertx-service-proxy with Apache License 2.0 5 votes vote down vote up
@Test
public void testLongDelivery2() {
  TestService proxyLong = TestService.createProxyLongDelivery(vertx, SERVICE_ADDRESS);
  proxyLong.longDeliveryFailed(onFailure(t -> {
    assertNotNull(t);
    assertTrue(t instanceof ReplyException);
    assertFalse(t instanceof ServiceException);
    ReplyException re = (ReplyException) t;
    assertEquals(ReplyFailure.TIMEOUT, re.failureType());
    testComplete();
  }));
  await();
}
 
Example #12
Source File: ServiceProxyTest.java    From vertx-service-proxy with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailingMethod() {
  proxy.failingMethod(onFailure(t -> {
    assertTrue(t instanceof ReplyException);
    ServiceException se = (ServiceException) t;
    assertEquals(ReplyFailure.RECIPIENT_FAILURE, se.failureType());
    assertEquals("wibble", se.getMessage());
    assertTrue(se.getDebugInfo().isEmpty());
    testComplete();
  }));
  await();
}
 
Example #13
Source File: FrameHelper.java    From vertx-tcp-eventbus-bridge with Apache License 2.0 5 votes vote down vote up
public static void sendErrFrame(String address, String replyAddress, ReplyException failure, WriteStream<Buffer> handler) {
  final JsonObject payload = new JsonObject()
      .put("type", "err")
      .put("address", replyAddress)
      .put("sourceAddress", address)
      .put("failureCode", failure.failureCode())
      .put("failureType", failure.failureType().name())
      .put("message", failure.getMessage());

  writeFrame(payload, handler);
}
 
Example #14
Source File: VertxObservers.java    From weld-vertx with Apache License 2.0 5 votes vote down vote up
public void consumerSendTimeout(@Observes @VertxConsumer(TEST_BUS_TIMEOUT) VertxEvent event) {
    assertEquals(TEST_BUS_TIMEOUT, event.getAddress());
    event.messageTo(TEST_SLOW_HANDLER).setDeliveryOptions(new DeliveryOptions().setSendTimeout(10)).send("foo", (r) -> {
        if (r.failed()) {
            ReplyException exception = (ReplyException) r.cause();
            if (exception.failureType().equals(ReplyFailure.TIMEOUT)) {
                SYNCHRONIZER.add("timeout");
            }
        }
    });
}
 
Example #15
Source File: SwaggerRouter.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
private static void manageError( ReplyException cause, HttpServerResponse response) {
    if(isExistingHttStatusCode(cause.failureCode())) {
        response.setStatusCode(cause.failureCode());
        if(StringUtils.isNotEmpty(cause.getMessage())) {
            response.setStatusMessage(cause.getMessage());
        }
    } else {
        response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
    }
    response.end();
}
 
Example #16
Source File: DataService.java    From gushici with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param categories 用户请求的类别 [img, shenghuo ,buyi]
 * @return 返回一个随机类别的 key (set)
 */
private Future<String> checkAndGetKey(JsonArray categories) {
    Future<String> result = Future.future();
    List<String> toRandom = keysInRedis.getKeys(categories);
    if (toRandom.size() >= 1) {
        result.complete(toRandom.get(random.nextInt(toRandom.size())));
    } else {
        result.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 404, "没有结果,请检查API"));
    }
    return result;
}
 
Example #17
Source File: ConvertUtil.java    From gushici with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param obj base64 加密后的图片
 * @return Buffer 流
 */
public static Future<Buffer> getImageFromBase64(String obj) {
    Future<Buffer> result = Future.future();
    if (obj == null) {
        result.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 500, "图片读取失败"));
        return result;
    }

    Base64.Decoder decoder = Base64.getDecoder();
    byte[] bs;
    bs = decoder.decode(obj);
    Buffer buffer = Buffer.buffer(bs);
    result.complete(buffer);
    return result;
}
 
Example #18
Source File: RestKiqrServerVerticle.java    From kiqr with Apache License 2.0 5 votes vote down vote up
private void forwardErrorCode(RoutingContext routingContext, AsyncResult<Message<Object>> reply) {
    ReplyException ex = (ReplyException) reply.cause();
    ex.printStackTrace();
    HttpServerResponse response = routingContext.response();
    response.setStatusCode(ex.failureCode());
    response.end();
}
 
Example #19
Source File: AllKeyValuesQueryVerticleTest.java    From kiqr with Apache License 2.0 4 votes vote down vote up
@Test
public void illegalStateStoreExceptionOnStoreInitialization(TestContext context){
    KafkaStreams streamMock = mock(KafkaStreams.class);

    when(streamMock.store(eq("store"), any(QueryableStoreType.class) )).thenThrow( InvalidStateStoreException.class);

    rule.vertx().deployVerticle(new AllKeyValuesQueryVerticle("host", streamMock), context.asyncAssertSuccess(deployment->{

        StoreWideQuery query = new StoreWideQuery("store", Serdes.String().getClass().getName(), Serdes.String().getClass().getName());

        rule.vertx().eventBus().send(Config.ALL_KEY_VALUE_QUERY_ADDRESS_PREFIX + "host", query, context.asyncAssertFailure(handler ->{

            context.assertTrue(handler instanceof ReplyException);
            ReplyException ex = (ReplyException) handler;
            context.assertEquals(500, ex.failureCode());

        }));

    }));

}
 
Example #20
Source File: KeyValueQueryFacadeVerticleTest.java    From kiqr with Apache License 2.0 4 votes vote down vote up
@Test
public void forwardingFailureDuringInstanceLookup(TestContext context){

    ShareableStreamsMetadataProvider mock = mock(ShareableStreamsMetadataProvider.class);
    StreamsMetadata host = new StreamsMetadata(new HostInfo("host", 1), Collections.emptySet(), Collections.emptySet());
    when(mock.metadataForKey(anyString(), any(), any(Serializer.class))).thenReturn(null);
    rule.vertx().sharedData().getLocalMap("metadata").put("metadata", mock);


    rule.vertx().deployVerticle(new KeyBasedQueryFacadeVerticle<KeyBasedQuery, ScalarKeyValueQueryResponse>(Config.KEY_VALUE_QUERY_FACADE_ADDRESS, Config.KEY_VALUE_QUERY_ADDRESS_PREFIX), context.asyncAssertSuccess(deployment->{

        KeyBasedQuery query = new KeyBasedQuery("store", Serdes.String().getClass().getName(), "key".getBytes(), Serdes.String().getClass().getName());

        rule.vertx().eventBus().send(Config.KEY_VALUE_QUERY_FACADE_ADDRESS, query, context.asyncAssertFailure(handler ->{

            context.assertTrue(handler instanceof ReplyException);
            ReplyException ex = (ReplyException) handler;
            context.assertEquals(404, ex.failureCode());

        }));
    }));

}
 
Example #21
Source File: WindowQueryVerticleTest.java    From kiqr with Apache License 2.0 4 votes vote down vote up
@Test
public void noValidKeySerde(TestContext context){
    KafkaStreams streamMock = mock(KafkaStreams.class);

    rule.vertx().deployVerticle(new WindowedQueryVerticle("host", streamMock), context.asyncAssertSuccess(deployment->{

        WindowedQuery query = new WindowedQuery("store", "i am not a serde", "key".getBytes(),  Serdes.String().getClass().getName(), 0, 1);

        rule.vertx().eventBus().send(Config.WINDOWED_QUERY_ADDRESS_PREFIX + "host", query, context.asyncAssertFailure(handler ->{

            context.assertTrue(handler instanceof ReplyException);
            ReplyException ex = (ReplyException) handler;
            context.assertEquals(400, ex.failureCode());

        }));

    }));

}
 
Example #22
Source File: WindowQueryVerticleTest.java    From kiqr with Apache License 2.0 4 votes vote down vote up
@Test
public void noValidValueSerde(TestContext context){
    KafkaStreams streamMock = mock(KafkaStreams.class);

    rule.vertx().deployVerticle(new WindowedQueryVerticle("host", streamMock), context.asyncAssertSuccess(deployment->{

        WindowedQuery query = new WindowedQuery("store", Serdes.String().getClass().getName(), "key".getBytes(),  "i am not a serde", 0, 1);

        rule.vertx().eventBus().send(Config.WINDOWED_QUERY_ADDRESS_PREFIX + "host", query, context.asyncAssertFailure(handler ->{

            context.assertTrue(handler instanceof ReplyException);
            ReplyException ex = (ReplyException) handler;
            context.assertEquals(400, ex.failureCode());

        }));

    }));

}
 
Example #23
Source File: WindowQueryVerticleTest.java    From kiqr with Apache License 2.0 4 votes vote down vote up
@Test
public void illegalStateStoreExceptionOnStoreInitialization(TestContext context){
    KafkaStreams streamMock = mock(KafkaStreams.class);

    when(streamMock.store(eq("store"), any(QueryableStoreType.class) )).thenThrow( InvalidStateStoreException.class);

    rule.vertx().deployVerticle(new WindowedQueryVerticle("host", streamMock), context.asyncAssertSuccess(deployment->{

        WindowedQuery query = new WindowedQuery("store", Serdes.String().getClass().getName(), "key".getBytes(),  Serdes.String().getClass().getName(), 0, 1);

        rule.vertx().eventBus().send(Config.WINDOWED_QUERY_ADDRESS_PREFIX + "host", query, context.asyncAssertFailure(handler ->{

            context.assertTrue(handler instanceof ReplyException);
            ReplyException ex = (ReplyException) handler;
            context.assertEquals(500, ex.failureCode());

        }));

    }));

}
 
Example #24
Source File: WindowQueryVerticleTest.java    From kiqr with Apache License 2.0 4 votes vote down vote up
@Test
public void illegalStateStoreExceptionOnQuery(TestContext context){
    KafkaStreams streamMock = mock(KafkaStreams.class);
    ReadOnlyWindowStore<Object, Object> storeMock = mock(ReadOnlyWindowStore.class);
    when(streamMock.store(eq("store"), any(QueryableStoreType.class))).thenReturn(storeMock);
    when(storeMock.fetch(any(), anyLong(), anyLong())).thenThrow(InvalidStateStoreException.class);

    rule.vertx().deployVerticle(new WindowedQueryVerticle("host", streamMock), context.asyncAssertSuccess(deployment->{

        WindowedQuery query = new WindowedQuery("store", Serdes.String().getClass().getName(), "key".getBytes(),  Serdes.String().getClass().getName(), 0, 1);

        rule.vertx().eventBus().send(Config.WINDOWED_QUERY_ADDRESS_PREFIX + "host", query, context.asyncAssertFailure(handler ->{

            context.assertTrue(handler instanceof ReplyException);
            ReplyException ex = (ReplyException) handler;
            context.assertEquals(500, ex.failureCode());

        }));

    }));

}
 
Example #25
Source File: WindowQueryVerticleTest.java    From kiqr with Apache License 2.0 4 votes vote down vote up
@Test
public void unexpectedExceptionOnQuery(TestContext context){
    KafkaStreams streamMock = mock(KafkaStreams.class);
    ReadOnlyWindowStore<Object, Object> storeMock = mock(ReadOnlyWindowStore.class);
    when(streamMock.store(eq("store"), any(QueryableStoreType.class))).thenReturn(storeMock);
    when(storeMock.fetch(any(), anyLong(), anyLong())).thenThrow(IllegalArgumentException.class);


    rule.vertx().deployVerticle(new WindowedQueryVerticle("host", streamMock), context.asyncAssertSuccess(deployment->{

        WindowedQuery query = new WindowedQuery("store", Serdes.String().getClass().getName(), "key".getBytes(),  Serdes.String().getClass().getName(), 0, 1);

        rule.vertx().eventBus().send(Config.WINDOWED_QUERY_ADDRESS_PREFIX + "host", query, context.asyncAssertFailure(handler ->{

            context.assertTrue(handler instanceof ReplyException);
            ReplyException ex = (ReplyException) handler;
            context.assertEquals(500, ex.failureCode());

        }));

    }));

}
 
Example #26
Source File: SwaggerRouter.java    From vertx-swagger with Apache License 2.0 4 votes vote down vote up
private static void configureRoute(Route route, String serviceId, Operation operation, EventBus eventBus, Function<RoutingContext, DeliveryOptions> configureMessage) {
    Optional.ofNullable(operation.getConsumes()).ifPresent(consumes -> consumes.forEach(route::consumes));
    Optional.ofNullable(operation.getProduces()).ifPresent(produces -> produces.forEach(route::produces));

    route.handler(context -> {
        try {
            JsonObject message = new JsonObject();
            operation.getParameters().forEach(parameter -> {
                String name = parameter.getName();
                Object value = PARAMETER_EXTRACTORS.get(parameter.getIn()).extract(name, parameter, context);
                message.put(name, value);
            });

            // callback to configure message e.g. provide message header values
            DeliveryOptions deliveryOptions = configureMessage != null ? configureMessage.apply(context) : new DeliveryOptions();

            addAuthUserHeader(context, deliveryOptions);

            context.request().headers().forEach(entry -> deliveryOptions.addHeader(entry.getKey(), entry.getValue()));
            
            eventBus.<String> send(serviceId, message, deliveryOptions, operationResponse -> {
                if (operationResponse.succeeded()) {
                    manageHeaders(context.response(), operationResponse.result().headers());

                    if (operationResponse.result().body() != null) {
                        context.response().end(operationResponse.result().body());
                    } else {
                        context.response().end();
                    }
                  
                } else {
                    vertxLogger.error("Internal Server Error", operationResponse.cause());
                    manageError((ReplyException)operationResponse.cause(), context.response());
                }
            });
        } catch (Exception e) {
            vertxLogger.error("sending Bad Request", e);
            badRequestEnd(context.response());
        }

    });
}
 
Example #27
Source File: AllKeyValuesQueryVerticleTest.java    From kiqr with Apache License 2.0 4 votes vote down vote up
@Test
public void noValidValueSerde(TestContext context){
    KafkaStreams streamMock = mock(KafkaStreams.class);

    rule.vertx().deployVerticle(new AllKeyValuesQueryVerticle("host", streamMock), context.asyncAssertSuccess(deployment->{

        StoreWideQuery query = new StoreWideQuery("store", Serdes.String().getClass().getName(), "i am not a serde" );

        rule.vertx().eventBus().send(Config.ALL_KEY_VALUE_QUERY_ADDRESS_PREFIX + "host", query, context.asyncAssertFailure(handler ->{

            context.assertTrue(handler instanceof ReplyException);
            ReplyException ex = (ReplyException) handler;
            context.assertEquals(400, ex.failureCode());

        }));

    }));

}
 
Example #28
Source File: EventBusAuthenticationService.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void authenticate(final JsonObject authRequest, final Handler<AsyncResult<HonoUser>> authenticationResultHandler) {

    final DeliveryOptions options = new DeliveryOptions().setSendTimeout(AUTH_REQUEST_TIMEOUT_MILLIS);
    vertx.eventBus().request(AuthenticationConstants.EVENT_BUS_ADDRESS_AUTHENTICATION_IN, authRequest, options, reply -> {
        if (reply.succeeded()) {
            final JsonObject result = (JsonObject) reply.result().body();
            final String token = result.getString(AuthenticationConstants.FIELD_TOKEN);
            log.debug("received token [length: {}] in response to authentication request", token.length());
            try {
                final Jws<Claims> expandedToken = tokenValidator.expand(result.getString(AuthenticationConstants.FIELD_TOKEN));
                authenticationResultHandler.handle(Future.succeededFuture(new HonoUserImpl(expandedToken, token)));
            } catch (final JwtException e) {
                authenticationResultHandler.handle(Future.failedFuture(new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR, e)));
            }
        } else {
            final ServiceInvocationException resultException;
            if (reply.cause() instanceof ReplyException) {
                switch (((ReplyException) reply.cause()).failureType()) {
                    case TIMEOUT:
                        log.debug("timeout processing authentication request", reply.cause());
                        resultException = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, reply.cause());
                        break;
                    case NO_HANDLERS:
                        log.debug("could not process authentication request", reply.cause());
                        resultException = new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR, reply.cause());
                        break;
                    case RECIPIENT_FAILURE:
                        final int statusCode = ((ReplyException) reply.cause()).failureCode();
                        if (statusCode < 400 || statusCode >= 600) {
                            log.error("got illegal status code in authentication response exception: {}", statusCode);
                            resultException = new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR, reply.cause().getMessage());
                        } else {
                            resultException = StatusCodeMapper.from(statusCode, reply.cause().getMessage());
                        }
                        break;
                    default:
                        resultException = new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR, reply.cause());
                }
            } else {
                resultException = new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR, reply.cause());
            }
            authenticationResultHandler.handle(Future.failedFuture(resultException));
        }
    });

}
 
Example #29
Source File: AllKeyValuesQueryVerticleTest.java    From kiqr with Apache License 2.0 4 votes vote down vote up
@Test
public void noValidKeySerde(TestContext context){
    KafkaStreams streamMock = mock(KafkaStreams.class);

    rule.vertx().deployVerticle(new AllKeyValuesQueryVerticle("host", streamMock), context.asyncAssertSuccess(deployment->{

        StoreWideQuery query = new StoreWideQuery("store", "i am not a serde", Serdes.String().getClass().getName());

        rule.vertx().eventBus().send(Config.ALL_KEY_VALUE_QUERY_ADDRESS_PREFIX + "host", query, context.asyncAssertFailure(handler ->{

            context.assertTrue(handler instanceof ReplyException);
            ReplyException ex = (ReplyException) handler;
            context.assertEquals(400, ex.failureCode());

        }));

    }));

}
 
Example #30
Source File: SessionWindowQueryVerticleTest.java    From kiqr with Apache License 2.0 4 votes vote down vote up
@Test
public void unexpectedExceptionOnQuery(TestContext context){
    KafkaStreams streamMock = mock(KafkaStreams.class);
    ReadOnlySessionStore<Object, Object> storeMock = mock(ReadOnlySessionStore.class);
    when(streamMock.store(eq("store"), any(QueryableStoreType.class))).thenReturn(storeMock);
    when(storeMock.fetch(any())).thenThrow(IllegalArgumentException.class);


    rule.vertx().deployVerticle(new SessionWindowQueryVerticle("host", streamMock), context.asyncAssertSuccess(deployment->{

        KeyBasedQuery query = new KeyBasedQuery("store", Serdes.String().getClass().getName(), "key".getBytes(),  Serdes.String().getClass().getName());

        rule.vertx().eventBus().send(Config.SESSION_QUERY_ADDRESS_PREFIX + "host", query, context.asyncAssertFailure(handler ->{

            context.assertTrue(handler instanceof ReplyException);
            ReplyException ex = (ReplyException) handler;
            context.assertEquals(500, ex.failureCode());

        }));

    }));

}