io.vertx.core.eventbus.ReplyFailure Java Examples

The following examples show how to use io.vertx.core.eventbus.ReplyFailure. 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: ServiceProxyTest.java    From vertx-service-proxy with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallWithMessageParamWrongType() {
  JsonObject message = new JsonObject();
  message.put("object", new JsonObject().put("foo", "bar"));
  message.put("str", 76523); // <- wrong one
  message.put("i", 1234);
  message.put("char", (int)'X'); // chars are mapped to ints
  message.put("enum", SomeEnum.BAR.toString()); // enums are mapped to strings
  vertx.eventBus().request(SERVICE_WITH_DEBUG_ADDRESS, message, new DeliveryOptions().addHeader("action", "invokeWithMessage").setSendTimeout(500), onFailure(t -> {
    assertTrue(t instanceof ServiceException);
    ServiceException se = (ServiceException) t;
    // This will as operation will fail to be invoked
    assertEquals(ReplyFailure.RECIPIENT_FAILURE, se.failureType());
    assertEquals(ClassCastException.class.getCanonicalName(), se.getDebugInfo().getString("causeName"));
    assertFalse(se.getDebugInfo().getJsonArray("causeStackTrace").isEmpty());
    testComplete();
  }));
  await();
}
 
Example #2
Source File: ServiceProxyTest.java    From vertx-service-proxy with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallWithMessageInvalidAction() {
  JsonObject message = new JsonObject();
  message.put("object", new JsonObject().put("foo", "bar"));
  message.put("str", "blah");
  message.put("i", 1234);
  vertx.eventBus().request(SERVICE_WITH_DEBUG_ADDRESS, message, new DeliveryOptions().addHeader("action", "yourmum").setSendTimeout(500), onFailure(t -> {
    assertTrue(t instanceof ServiceException);
    ServiceException se = (ServiceException) t;
    // This will as operation will fail to be invoked
    assertEquals(ReplyFailure.RECIPIENT_FAILURE, se.failureType());
    assertEquals(IllegalStateException.class.getCanonicalName(), se.getDebugInfo().getString("causeName"));
    testComplete();
  }));
  await();
}
 
Example #3
Source File: MetricsTest.java    From vertx-dropwizard-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventBusMetricsReplyRecipientFailure() {
  vertx.eventBus().consumer("foo").handler(msg -> msg.fail(1, "blah"));

  vertx.eventBus().request("foo", "bar", new DeliveryOptions(), ar -> {
    assertTrue(ar.failed());
    testComplete();
  });

  await();

  JsonObject metrics = metricsService.getMetricsSnapshot(vertx.eventBus());
  assertCount(metrics.getJsonObject("messages.reply-failures"), 1L);
  assertCount(metrics.getJsonObject("messages.reply-failures." + ReplyFailure.RECIPIENT_FAILURE), 1L);
}
 
Example #4
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 #5
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 #6
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 #7
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 #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: MetricsTest.java    From vertx-dropwizard-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventBusMetricsReplyTimeout() {
  vertx.eventBus().consumer("foo").handler(msg -> {});

  vertx.eventBus().request("foo", "bar", new DeliveryOptions().setSendTimeout(300), ar -> {
    assertTrue(ar.failed());
    testComplete();
  });

  await();

  JsonObject metrics = metricsService.getMetricsSnapshot(vertx.eventBus());
  assertCount(metrics.getJsonObject("messages.reply-failures"), 1L);
  assertCount(metrics.getJsonObject("messages.reply-failures." + ReplyFailure.TIMEOUT), 1L);
}
 
Example #10
Source File: MetricsTest.java    From vertx-dropwizard-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventBusMetricsReplyNoHandlers() {
  vertx.eventBus().request("foo", "bar", new DeliveryOptions().setSendTimeout(300), ar -> {
    assertTrue(ar.failed());
    testComplete();
  });

  await();

  JsonObject metrics = metricsService.getMetricsSnapshot(vertx.eventBus());
  assertCount(metrics.getJsonObject("messages.reply-failures"), 1L);
  assertCount(metrics.getJsonObject("messages.reply-failures." + ReplyFailure.NO_HANDLERS), 1L);
}
 
Example #11
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 #12
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 #13
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 #14
Source File: ServiceJWTInterceptor.java    From vertx-service-proxy with Apache License 2.0 4 votes vote down vote up
@Override
public Future<Message<JsonObject>> apply(Message<JsonObject> msg) {
  final String authorization = msg.headers().get("auth-token");

  if (authorization == null) {
    return Future.failedFuture(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 401, "Unauthorized"));
  }

  Promise<Message<JsonObject>> promise = Promise.promise();

  jwtAuth.authenticate(new JsonObject().put("jwt", authorization), authenticate -> {
    if (authenticate.failed()) {
      promise.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 500, authenticate.cause().getMessage()));
      return;
    }

    final User user = authenticate.result();

    if (user == null) {
      promise.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 403, "Forbidden"));
      return;
    }

    final int requiredcount = authorities == null ? 0 : authorities.size();

    if (requiredcount > 0) {

      AtomicInteger count = new AtomicInteger();
      AtomicBoolean sentFailure = new AtomicBoolean();

      Handler<AsyncResult<Boolean>> authHandler = res -> {
        if (res.succeeded()) {
          if (res.result()) {
            if (count.incrementAndGet() == requiredcount) {
              // Has all required authorities
              promise.complete(msg);
            }
          } else {
            if (sentFailure.compareAndSet(false, true)) {
              promise.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 403, "Forbidden"));
            }
          }
        } else {
          promise.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 500, res.cause().getMessage()));
        }
      };
      for (String authority : authorities) {
        if (!sentFailure.get()) {
          user.isAuthorized(authority, authHandler);
        }
      }
    } else {
      // No auth required
      promise.complete(msg);
    }
  });

  return promise.future();
}
 
Example #15
Source File: ServiceAuthInterceptor.java    From vertx-service-proxy with Apache License 2.0 4 votes vote down vote up
@Override
public Future<Message<JsonObject>> apply(Message<JsonObject> msg) {

  final TokenCredentials authorization = new TokenCredentials(msg.headers().get("auth-token"));

  try {
    authorization.checkValid(null);

    Promise<Message<JsonObject>> promise = Promise.promise();

    if (authn == null) {
      promise.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 500, "No AuthenticationProvider present"));
      return promise.future();
    }

    authn.authenticate(authorization, authenticate -> {
      if (authenticate.failed()) {
        promise.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 500, authenticate.cause().getMessage()));
        return;
      }

      final User user = authenticate.result();

      if (user == null) {
        promise.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 401, "Unauthorized"));
        return;
      }

      if (authorizations == null || authorizations.isEmpty()) {
        promise.complete(msg);
        return;
      }

      authz.getAuthorizations(user, getAuthorizations -> {
        if (getAuthorizations.failed()) {
          promise.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 500, authenticate.cause().getMessage()));
        } else {
          AuthorizationContext context = AuthorizationContext.create(user);
          for (Authorization authority : authorizations) {
            if (!authority.match(context)) {
              // failed
              promise.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 403, "Forbidden"));
              return;
            }
          }
          // all authorities have passed
          promise.complete(msg);
        }
      });
    });

    return promise.future();
  } catch (CredentialValidationException e) {
    return Future.failedFuture(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 401, "Unauthorized"));
  }
}
 
Example #16
Source File: ServiceException.java    From vertx-service-proxy with Apache License 2.0 4 votes vote down vote up
public ServiceException(int failureCode, String message, JsonObject debugInfo) {
  super(ReplyFailure.RECIPIENT_FAILURE, failureCode, message);
  this.debugInfo = debugInfo;

}
 
Example #17
Source File: EventBusMetricsImpl.java    From vertx-dropwizard-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public void replyFailure(String address, ReplyFailure failure) {
  replyFailures.mark();
  meter("messages", "reply-failures", failure.name()).mark();
}
 
Example #18
Source File: RequestResponseEndpointTest.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verifies that the endpoint sends a response with a 503 status code to the client if a request
 * times out internally.
 */
@Test
public void testHandleMessageSendsResponseForTimedOutRequests() {

    testHandleMessageSendsResponseWithStatusCode(new ReplyException(ReplyFailure.TIMEOUT), HttpURLConnection.HTTP_UNAVAILABLE);
}
 
Example #19
Source File: VertxEventBusMetrics.java    From vertx-micrometer-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public void replyFailure(String address, ReplyFailure failure) {
  if (!isInternal(address)) {
    replyFailures.get(address, failure.name()).increment();
  }
}