Java Code Examples for io.vertx.core.Handler

The following examples show how to use io.vertx.core.Handler. These examples are extracted from open source projects. 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 Project: besu   Source File: GraphQLHttpService.java    License: Apache License 2.0 6 votes vote down vote up
private Handler<RoutingContext> checkWhitelistHostHeader() {
  return event -> {
    final Optional<String> hostHeader = getAndValidateHostHeader(event);
    if (config.getHostsAllowlist().contains("*")
        || (hostHeader.isPresent() && hostIsInAllowlist(hostHeader.get()))) {
      event.next();
    } else {
      final HttpServerResponse response = event.response();
      if (!response.closed()) {
        response
            .setStatusCode(403)
            .putHeader("Content-Type", "application/json; charset=utf-8")
            .end("{\"message\":\"Host not authorized.\"}");
      }
    }
  };
}
 
Example 2
Source Project: besu   Source File: WebSocketService.java    License: Apache License 2.0 6 votes vote down vote up
private Handler<HttpServerRequest> httpHandler() {
  final Router router = Router.router(vertx);

  // Verify Host header to avoid rebind attack.
  router.route().handler(checkAllowlistHostHeader());

  if (authenticationService.isPresent()) {
    router.route("/login").handler(BodyHandler.create());
    router
        .post("/login")
        .produces(APPLICATION_JSON)
        .handler(authenticationService.get()::handleLogin);
  } else {
    router
        .post("/login")
        .produces(APPLICATION_JSON)
        .handler(AuthenticationService::handleDisabledLogin);
  }

  router.route().handler(WebSocketService::handleHttpNotSupported);
  return router;
}
 
Example 3
Source Project: xyz-hub   Source File: RemoteFunctionClient.java    License: Apache License 2.0 6 votes vote down vote up
private void enqueue(final Marker marker, byte[] bytes, boolean fireAndForget, final Handler<AsyncResult<byte[]>> callback) {
  FunctionCall fc = new FunctionCall(marker, bytes, fireAndForget, callback);

  /*if (Service.currentTimeMillis() > lastSizeAdjustment.get() + SIZE_ADJUSTMENT_INTERVAL
      && fc.getByteSize() + queue.getByteSize() > queue.getMaxByteSize()) {
    //Element won't fit into queue so we try to enlarge it
    adjustQueueByteSizes();
  }*/

  //In any case add the element to the queue
  queue.add(fc)
      //Send timeout for discarded (old) calls
      .forEach(timeoutFc ->
          timeoutFc.callback
              .handle(Future.failedFuture(new HttpException(TOO_MANY_REQUESTS, "Remote function is busy or cannot be invoked."))));
}
 
Example 4
Source Project: xyz-hub   Source File: RpcClient.java    License: Apache License 2.0 6 votes vote down vote up
private void processRelocatedEventAsync(RelocatedEvent relocatedEvent, Handler<AsyncResult<byte[]>> callback) {
  Service.vertx.executeBlocking(future -> {
    try {
      InputStream input = relocationClient.processRelocatedEvent(relocatedEvent);
      future.complete(ByteStreams.toByteArray(input));
    }
    catch (Exception e) {
      logger.error("An error when processing a relocated response.", e);
      future.fail(new HttpException(BAD_GATEWAY, "Unable to load the relocated event.", e));
    }
  }, ar -> {
    if (ar.failed()) {
      callback.handle(Future.failedFuture(ar.cause()));
    }
    else {
      callback.handle(Future.succeededFuture((byte[]) ar.result()));
    }
  });
}
 
Example 5
Source Project: besu   Source File: JsonRpcHttpService.java    License: Apache License 2.0 6 votes vote down vote up
private Handler<RoutingContext> checkAllowlistHostHeader() {
  return event -> {
    final Optional<String> hostHeader = getAndValidateHostHeader(event);
    if (config.getHostsAllowlist().contains("*")
        || (hostHeader.isPresent() && hostIsInAllowlist(hostHeader.get()))) {
      event.next();
    } else {
      final HttpServerResponse response = event.response();
      if (!response.closed()) {
        response
            .setStatusCode(403)
            .putHeader("Content-Type", "application/json; charset=utf-8")
            .end("{\"message\":\"Host not authorized.\"}");
      }
    }
  };
}
 
Example 6
Source Project: konduit-serving   Source File: BaseDl4JVerticalTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Handler<HttpServerRequest> getRequest() {

    return req -> {
        req.bodyHandler(body -> {
            try {
                ClassifierOutput classifierOutput = ObjectMappers.json().readValue(body.toString(),
                        ClassifierOutput.class);
                assertEquals(1, classifierOutput.getDecisions()[0]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("Finish body" + body);
        });
        req.exceptionHandler(Throwable::printStackTrace);
    };
}
 
Example 7
Source Project: quarkus-http   Source File: VertxUndertowEngine.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {

    server = vertx.createHttpServer(options);

    server.requestHandler(request -> {
        VertxHttpExchange delegate = new VertxHttpExchange(request, allocator, blockingExecutor, null, null);
        rootHandler.handle(delegate);
    });

    server.listen(port, host, new Handler<AsyncResult<HttpServer>>() {
        @Override
        public void handle(AsyncResult<HttpServer> event) {
            if (event.failed()) {
                startFuture.fail(event.cause());
            } else {
                startFuture.complete();
            }
        }
    });
}
 
Example 8
Source Project: xyz-hub   Source File: RemoteFunctionClient.java    License: Apache License 2.0 6 votes vote down vote up
private void _invoke(final Marker marker, byte[] bytes, boolean fireAndForget, final Handler<AsyncResult<byte[]>> callback) {
  //long start = System.nanoTime();
  invoke(marker, bytes, fireAndForget, r -> {
    //long end = System.nanoTime();
    //TODO: Activate performance calculation once it's implemented completely
    //recalculatePerformance(end - start, TimeUnit.NANOSECONDS);
    //Look into queue if there is something further to do
    FunctionCall fc = queue.remove();
    if (fc == null) {
      usedConnections.getAndDecrement(); //Free the connection only in case it's not needed for the next invocation
    }
    try {
      callback.handle(r);
    }
    catch (Exception e) {
      logger.error(marker, "Error while calling response handler", e);
    }
    //In case there has been an enqueued element invoke the it
    if (fc != null) {
      _invoke(fc.marker, fc.bytes, fc.fireAndForget, fc.callback);
    }
  });
}
 
Example 9
Source Project: camel-k-runtime   Source File: KnativeRecorder.java    License: Apache License 2.0 6 votes vote down vote up
public RuntimeValue<KnativeComponent> createKnativeComponent(
    Supplier<Vertx> vertx,
    RuntimeValue<Router> router,
    Handler<RoutingContext> bodyHandler) {

    KnativeHttpTransport transport = new KnativeHttpTransport();
    transport.setRouter(new VertxPlatformHttpRouter(vertx.get(), router.getValue()) {
        @Override
        public Handler<RoutingContext> bodyHandler() {
            return bodyHandler;
        }
    });

    KnativeComponent component = new KnativeComponent();
    component.setTransport(transport);

    return new RuntimeValue<>(component);
}
 
Example 10
Source Project: xyz-hub   Source File: Node.java    License: Apache License 2.0 6 votes vote down vote up
private void callHealthCheck(boolean onlyAliveCheck, Handler<AsyncResult<Void>> callback) {
  Service.webClient.get(getUrl().getPort() == -1 ? DEFAULT_PORT : getUrl().getPort(), url.getHost(), HealthApi.MAIN_HEALTCHECK_ENDPOINT)
      .timeout(TimeUnit.SECONDS.toMillis(HEALTH_TIMEOUT))
      .send(ar -> {
        if (ar.succeeded()) {
          HttpResponse<Buffer> response = ar.result();
          if (onlyAliveCheck || response.statusCode() == 200) {
            callback.handle(Future.succeededFuture());
          } else {
            callback.handle(Future.failedFuture("Node with ID " + id + " and IP " + ip + " is not healthy."));
          }
        } else {
          callback.handle(Future.failedFuture("Node with ID " + id + " and IP " + ip + " is not reachable."));
        }
      });
}
 
Example 11
Source Project: xyz-hub   Source File: SpaceConfigClient.java    License: Apache License 2.0 6 votes vote down vote up
public void store(Marker marker, Space space, Handler<AsyncResult<Space>> handler) {
  if (space.getId() == null) {
    space.setId(RandomStringUtils.randomAlphanumeric(10));
  }

  storeSpace(marker, space, ar -> {
    if (ar.succeeded()) {
      invalidateCache(space.getId());
      logger.info(marker, "space[{}]: Stored successfully with title: \"{}\"", space.getId(), space.getTitle());
      handler.handle(Future.succeededFuture(ar.result()));
    } else {
      logger.error(marker, "space[{}]: Failed storing the space", space.getId(), ar.cause());
      handler.handle(Future.failedFuture(ar.cause()));
    }
  });
}
 
Example 12
Source Project: xyz-hub   Source File: DynamoSpaceConfigClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init(Handler<AsyncResult<Void>> onReady) {
  if (dynamoClient.isLocal()) {
    logger.info("DynamoDB running locally, initializing tables.");

    try {
      dynamoClient.createTable(spaces.getTableName(), "id:S,owner:S,shared:N", "id", "owner,shared", "exp");
      dynamoClient.createTable(packages.getTableName(), "packageName:S,spaceId:S", "packageName,spaceId", null, null);
    } catch (AmazonDynamoDBException e) {
      logger.error("Failure during creating tables on DynamoSpaceConfigClient init", e);
      onReady.handle(Future.failedFuture(e));
      return;
    }
  }

  onReady.handle(Future.succeededFuture());
}
 
Example 13
Source Project: xyz-hub   Source File: DynamoSpaceConfigClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void getSpace(Marker marker, String spaceId, Handler<AsyncResult<Space>> handler) {
  try {
    logger.info(marker, "Getting space with ID: {}", spaceId);
    final Item item = spaces.getItem("id", spaceId);

    if (item == null) {
      logger.info(marker, "Getting space with ID: {} returned null", spaceId);
      handler.handle(Future.succeededFuture(null));
      return;
    }

    final Space space = Json.decodeValue(item.toJSON(), Space.class);
    if (space != null) {
      logger.info(marker, "Space ID: {} with title: \"{}\" has been decoded", spaceId, space.getTitle());
    } else {
      logger.info(marker, "Space ID: {} has been decoded to null", spaceId);
    }
    handler.handle(Future.succeededFuture(space));
  } catch (AmazonDynamoDBException e) {
    logger.error(marker, "Failure during getting a space from DynamoDB", e);
    handler.handle(Future.failedFuture(e));
  }
}
 
Example 14
@Override
public Handler<HttpServerRequest> getRequest() {
    Handler<HttpServerRequest> ret = new Handler<HttpServerRequest>() {
        @Override
        public void handle(HttpServerRequest req) {
            //should be json body of classification
            req.bodyHandler(body -> {
                System.out.println("Finish body" + body);
            });

            req.exceptionHandler(exception -> {
                exception.printStackTrace();
            });


        }
    };

    return ret;
}
 
Example 15
Source Project: xyz-hub   Source File: JDBCConnectorConfigClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void getConnector(final Marker marker, final String connectorId, final Handler<AsyncResult<Connector>> handler) {
  final SQLQuery query = new SQLQuery(String.format("SELECT config FROM %s WHERE id = ?", CONNECTOR_TABLE), connectorId);
  client.queryWithParams(query.text(), new JsonArray(query.parameters()), out -> {
    if (out.succeeded()) {
      final Optional<String> config = out.result().getRows().stream().map(r -> r.getString("config")).findFirst();
      if (config.isPresent()) {
        final Connector connector = Json.decodeValue(config.get(), Connector.class);
        logger.debug(marker, "storageId[{}]: Loaded connector from the database.", connectorId);
        handler.handle(Future.succeededFuture(connector));
      } else {
        logger.debug(marker, "storageId[{}]: This configuration does not exist", connectorId);
        handler.handle(Future.failedFuture("The connector config not found for storageId: " + connectorId));
      }
    } else {
      logger.debug(marker, "storageId[{}]: Failed to load configuration, reason: ", connectorId, out.cause());
      handler.handle(Future.failedFuture(out.cause()));
    }
  });
}
 
Example 16
@Override
public Handler<HttpServerRequest> getRequest() {
    Handler<HttpServerRequest> ret = req -> {
        //should be json body of classification
        req.bodyHandler(body -> {
            System.out.println("Finish body" + body);
        });

        req.exceptionHandler(exception -> {
            exception.printStackTrace();
        });


    };

    return ret;
}
 
Example 17
Source Project: xyz-hub   Source File: FeatureTaskHandler.java    License: Apache License 2.0 6 votes vote down vote up
private static <T extends FeatureTask> void notifyConnectors(T task, ConnectorType connectorType, String eventType,
    Payload payload, Handler<AsyncResult<XyzResponse>> callback) {
  //Send the event to all registered & matching listeners / processors
  Map<String, List<ResolvableListenerConnectorRef>> connectorMap = task.space.getEventTypeConnectorRefsMap(connectorType);
  if (connectorMap != null && !connectorMap.isEmpty()) {
    String phase = payload instanceof Event ? "request" : "response";
    String notificationEventType = eventType + "." + phase;

    if (connectorMap.containsKey(notificationEventType)) {
      List<ResolvableListenerConnectorRef> connectors = connectorMap.get(notificationEventType);
      if (connectorType == ConnectorType.LISTENER) {
        notifyListeners(task, connectors, notificationEventType, payload);
        return;
      } else if (connectorType == ConnectorType.PROCESSOR) {
        notifyProcessors(task, connectors, notificationEventType, payload, callback);
        return;
      } else {
        throw new RuntimeException("Unsupported connector type.");
      }
    }
  }
  if (callback != null) {
    callback.handle(Future.succeededFuture(null));
  }
}
 
Example 18
Source Project: xyz-hub   Source File: InMemSpaceConfigClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void getSelectedSpaces(Marker marker, SpaceAuthorizationCondition authorizedCondition, SpaceSelectionCondition selectedCondition,
    Handler<AsyncResult<List<Space>>> handler) {
  //Sets are not even defined that means all access
  Predicate<Space> authorizationFilter = s -> authorizedCondition.spaceIds == null && authorizedCondition.ownerIds == null
      || authorizedCondition.spaceIds != null && authorizedCondition.spaceIds.contains(s.getId())
      || authorizedCondition.ownerIds != null && authorizedCondition.ownerIds.contains(s.getOwner())
      || s.isShared();
  //Sets are not even defined that means don't filter at all by spaceId or ownerId
  Predicate<Space> selectionFilter = s -> authorizedCondition.spaceIds == null && authorizedCondition.ownerIds == null
      || selectedCondition.spaceIds != null && selectedCondition.spaceIds.contains(s.getId())
      || selectedCondition.ownerIds != null && selectedCondition.ownerIds.contains(s.getOwner())
      || selectedCondition.shared && s.isShared();

  List<Space> spaces = spaceMap.values().stream()
      .filter(authorizationFilter)
      .filter(selectionFilter)
      .collect(Collectors.toList());
  handler.handle(Future.succeededFuture(spaces));
}
 
Example 19
Source Project: xyz-hub   Source File: ConnectorConfigClient.java    License: Apache License 2.0 6 votes vote down vote up
public void get(Marker marker, String connectorId, Handler<AsyncResult<Connector>> handler) {
  final Connector connectorFromCache = cache.get(connectorId);

  if (connectorFromCache != null) {
    logger.info(marker, "storageId: {} - The connector was loaded from cache", connectorId);
    handler.handle(Future.succeededFuture(connectorFromCache));
    return;
  }

  getConnector(marker, connectorId, ar -> {
    if (ar.succeeded()) {
      final Connector connector = ar.result();
      cache.put(connectorId, connector);
      handler.handle(Future.succeededFuture(connector));
    } else {
      logger.error(marker, "storageId[{}]: Connector not found", connectorId);
      handler.handle(Future.failedFuture(ar.cause()));
    }
  });
}
 
Example 20
Source Project: kogito-runtimes   Source File: VertxJobsServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testGetScheduleTimeJobNotFound(@Mock HttpRequest<Buffer> request, @Mock HttpResponse<Buffer> response) {
    when(webClient.get(anyString())).thenReturn(request);
    AsyncResult<HttpResponse<Buffer>> asyncResult = mock(AsyncResult.class);
    when(asyncResult.succeeded()).thenReturn(true);
    when(asyncResult.result()).thenReturn(response);
    when(response.statusCode()).thenReturn(404);
    
    doAnswer(invocationOnMock -> {
        Handler<AsyncResult<HttpResponse<Buffer>>> handler = invocationOnMock.getArgument(0);
        executor.submit(() -> handler.handle(asyncResult));
        return null;
    }).when(request).send(any());
    
    assertThatThrownBy(() -> tested.getScheduledTime("123"))
        .hasCauseExactlyInstanceOf(JobNotFoundException.class);
    
    verify(webClient).get("/jobs/123");
}
 
Example 21
Source Project: xyz-hub   Source File: ConnectorConfigClient.java    License: Apache License 2.0 6 votes vote down vote up
private void store(Marker marker, Connector connector, Handler<AsyncResult<Connector>> handler, boolean withInvalidation) {
  if (connector.id == null) {
    connector.id = RandomStringUtils.randomAlphanumeric(10);
  }

  storeConnector(marker, connector, ar -> {
    if (ar.succeeded()) {
      final Connector connectorResult = ar.result();
      if (withInvalidation) {
        invalidateCache(connector.id);
      }
      handler.handle(Future.succeededFuture(connectorResult));
    } else {
      logger.error(marker, "storageId[{}]: Failed to store connector configuration, reason: ", connector.id, ar.cause());
      handler.handle(Future.failedFuture(ar.cause()));
    }
  });
}
 
Example 22
Source Project: aws-lambda-native-vertx   Source File: LambdaBootstrap.java    License: MIT License 5 votes vote down vote up
private void success(String requestURI, Buffer result, Handler<AsyncResult<Void>> handler) {
  client.post(port, host, requestURI)
    .sendBuffer(result, ar -> {
      if (ar.succeeded()) {
        // we don't really care about the response
        handler.handle(Future.succeededFuture());
      } else {
        handler.handle(Future.failedFuture(ar.cause()));
      }
    });
}
 
Example 23
@Override
public Handler<HttpServerRequest> getRequest() {

    return req -> {
        //should be json body of classification
        req.bodyHandler(body -> System.out.println("Finish body" + body));
        req.exceptionHandler(Throwable::printStackTrace);
    };
}
 
Example 24
@Test
public void shouldReceivePongMessages() {
    given(mockServerWebSocket.pongHandler(any())).will(invocation -> {
        Handler<Buffer> handler = invocation.getArgument(0);
        handler.handle(Buffer.buffer("test1"));
        handler.handle(Buffer.buffer("test2"));
        return mockServerWebSocket;
    });

    StepVerifier.create(session.receive())
        .expectNext(getWebSocketMessage(WebSocketMessage.Type.PONG, "test1"))
        .expectNext(getWebSocketMessage(WebSocketMessage.Type.PONG, "test2"))
        .verifyComplete();
}
 
Example 25
Source Project: xyz-hub   Source File: RpcClient.java    License: Apache License 2.0 5 votes vote down vote up
private void invokeWithRelocation(final Marker marker, byte[] bytes, boolean fireAndForget, final Handler<AsyncResult<byte[]>> callback) {
  try {
    final Connector connector = getConnector();
    if (bytes.length > connector.capabilities.maxPayloadSize) { // If the payload is too large to send directly to the connector
      if (!connector.capabilities.relocationSupport) {
        // The size is to large, the event cannot be sent to the connector.
        callback.handle(Future
            .failedFuture(new HttpException(REQUEST_ENTITY_TOO_LARGE, "The request entity size is over the limit for this connector.")));
        return;
      }

      // If relocation is supported, use the relocation client to transfer the event to the connector
      relocateAsync(marker, bytes, ar -> {
        if (ar.failed()) {
          callback.handle(Future.failedFuture(ar.cause()));
          return;
        }
        functionClient.submit(marker, ar.result(), fireAndForget, callback);
      });
    }
    else {
      functionClient.submit(marker, bytes, fireAndForget, callback);
    }
  } catch (Exception e) {
    callback.handle(Future.failedFuture(e));
  }
}
 
Example 26
Source Project: konduit-serving   Source File: PmmlIrisTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Handler<HttpServerRequest> getRequest() {
    return req -> {
        //should be json body of classification
        req.bodyHandler(body -> {
            System.out.println(body.toJson());
            System.out.println("Finish body" + body);
        })
        .exceptionHandler(exception -> context.fail(exception));
    };
}
 
Example 27
Source Project: besu   Source File: WebSocketRequestHandler.java    License: Apache License 2.0 5 votes vote down vote up
private Handler<AsyncResult<Object>> resultHandler(final String id) {
  return result -> {
    if (result.succeeded()) {
      replyToClient(id, Json.encodeToBuffer(result.result()));
    } else {
      replyToClient(
          id, Json.encodeToBuffer(new JsonRpcErrorResponse(null, JsonRpcError.INTERNAL_ERROR)));
    }
  };
}
 
Example 28
Source Project: xyz-hub   Source File: HTTPFunctionClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void invoke(Marker marker, byte[] bytes, boolean fireAndForget, Handler<AsyncResult<byte[]>> callback) {
  //TODO: respect fireAndForget parameter
  final RemoteFunctionConfig remoteFunction = getConnectorConfig().remoteFunction;
  logger.info(marker, "Invoke http remote function '{}' URL is: {} Event size is: {}", remoteFunction.id, url, bytes.length);

  try {
    webClient.postAbs(url)
        .timeout(REQUEST_TIMEOUT)
        .putHeader("content-type", "application/json; charset=" + Charset.defaultCharset().name())
        .sendBuffer(Buffer.buffer(bytes), ar -> {
          if (ar.failed()) {
            if (ar.cause() instanceof TimeoutException) {
              callback.handle(Future.failedFuture(new HttpException(GATEWAY_TIMEOUT, "Connector timeout error.")));
            }
            else {
              callback.handle(Future.failedFuture(ar.cause()));
            }
          }
          else {
            byte[] responseBytes = ar.result().body().getBytes();
            callback.handle(Future.succeededFuture(responseBytes));
          }
        });
  }
  catch (Exception e) {
    logger.error(marker, "Error sending event to remote http service", e);
    callback.handle(Future.failedFuture(new HttpException(BAD_GATEWAY, "Connector error.", e)));
  }
}
 
Example 29
Source Project: konduit-serving   Source File: TestPythonSetupRun.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Handler<HttpServerRequest> getRequest() {

    return req -> {
        //should be json body of classification
        req.bodyHandler(body -> {
            System.out.println(body.toJson());
            System.out.println("Finish body" + body);
        });

        req.exceptionHandler(exception -> context.fail(exception));
    };
}
 
Example 30
Source Project: besu   Source File: HandlerFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static Handler<RoutingContext> timeout(
    final TimeoutOptions globalOptions,
    final Map<String, JsonRpcMethod> methods,
    final boolean decodeJSON) {
  assert methods != null && globalOptions != null;
  return HANDLERS.computeIfAbsent(
      HandlerName.TIMEOUT,
      handlerName ->
          TimeoutHandler.handler(
              Optional.of(globalOptions),
              methods.keySet().stream()
                  .collect(Collectors.toMap(String::new, ignored -> globalOptions)),
              decodeJSON));
}