io.vertx.core.Handler Java Examples

The following examples show how to use io.vertx.core.Handler. 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: VertxUndertowEngine.java    From quarkus-http with 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 #2
Source File: DynamoSpaceConfigClient.java    From xyz-hub with 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 #3
Source File: DynamoSpaceConfigClient.java    From xyz-hub with 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 #4
Source File: MemMapResultRangeJsonVerticleTest.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: SpaceConfigClient.java    From xyz-hub with 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 #6
Source File: JDBCConnectorConfigClient.java    From xyz-hub with 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 #7
Source File: BaseDl4JVerticalTest.java    From konduit-serving with 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 #8
Source File: Node.java    From xyz-hub with 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 #9
Source File: MemMapWholeArrayVerticleTest.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: JsonRpcHttpService.java    From besu with 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 #11
Source File: RpcClient.java    From xyz-hub with 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 #12
Source File: KnativeRecorder.java    From camel-k-runtime with 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 #13
Source File: RemoteFunctionClient.java    From xyz-hub with 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 #14
Source File: FeatureTaskHandler.java    From xyz-hub with 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 #15
Source File: RemoteFunctionClient.java    From xyz-hub with 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 #16
Source File: InMemSpaceConfigClient.java    From xyz-hub with 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 #17
Source File: WebSocketService.java    From besu with 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 #18
Source File: ConnectorConfigClient.java    From xyz-hub with 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 #19
Source File: GraphQLHttpService.java    From besu with 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 #20
Source File: VertxJobsServiceTest.java    From kogito-runtimes with 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 File: ConnectorConfigClient.java    From xyz-hub with 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 File: VertxServerHttpResponseTest.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldWriteFile() {
    given(mockHttpServerResponse.sendFile(any(), anyLong(), anyLong(), any())).will(invocation -> {
        Handler<AsyncResult<Void>> handler = invocation.getArgument(3);
        handler.handle(Future.succeededFuture());
        return mockHttpServerResponse;
    });

    response.writeWith(Paths.get("/tmp/test"), 0, 0)
        .block();

    verify(mockHttpServerResponse).sendFile(eq("/tmp/test"), eq(0L), eq(0L), any());
}
 
Example #23
Source File: KnativeHttpServer.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
public KnativeHttpServer(CamelContext context, String host, int port, String path, Handler<RoutingContext> handler) {
    this.context = context;
    this.host = host;
    this.port = port;
    this.path = path;
    this.requests = new LinkedBlockingQueue<>();
    this.handler = handler != null
        ? handler
        : event -> {
            event.response().setStatusCode(200);
            event.response().end();
        };
}
 
Example #24
Source File: RedisCacheClient.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
@Override
  public void get(String key, Handler<String> handler) {
    getClient().get(key, asyncResult -> {
      if (asyncResult.failed()) {
//				logger.error("Error when trying to read key " + key + " from redis cache", asyncResult.cause());
      }
      handler.handle(asyncResult.result());
    });
  }
 
Example #25
Source File: LambdaFunctionClient.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes the remote lambda function and returns the decompressed response as bytes.
 */
@Override
protected void invoke(final Marker marker, byte[] bytes, boolean fireAndForget, final Handler<AsyncResult<byte[]>> callback) {
  final RemoteFunctionConfig remoteFunction = getConnectorConfig().remoteFunction;
  logger.debug(marker, "Invoking remote lambda function with id '{}' Event size is: {}", remoteFunction.id, bytes.length);

  InvokeRequest invokeReq = new InvokeRequest()
      .withFunctionName(((AWSLambda) remoteFunction).lambdaARN)
      .withPayload(ByteBuffer.wrap(bytes))
      .withInvocationType(fireAndForget ? InvocationType.Event : InvocationType.RequestResponse);

  asyncClient.invokeAsync(invokeReq, new AsyncHandler<InvokeRequest, InvokeResult>() {
    @Override
    public void onError(Exception exception) {
      if (callback == null) {
        logger.error(marker, "Error sending event to remote lambda function", exception);
      }
      else {
        callback.handle(Future.failedFuture(getWHttpException(marker, exception)));
      }
    }

    @Override
    public void onSuccess(InvokeRequest request, InvokeResult result) {
      byte[] responseBytes = new byte[result.getPayload().remaining()];
      result.getPayload().get(responseBytes);
      callback.handle(Future.succeededFuture(responseBytes));
    }
  });
}
 
Example #26
Source File: InMemConnectorConfigClient.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
@Override
protected void storeConnector(Marker marker, Connector connector, Handler<AsyncResult<Connector>> handler) {
  if (connector.id == null) {
    connector.id = RandomStringUtils.randomAlphanumeric(10);
  }
  storageMap.put(connector.id, connector);
  handler.handle(Future.succeededFuture(connector));
}
 
Example #27
Source File: TestPythonJsonNdArrayScalarInput.java    From konduit-serving with 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 #28
Source File: LambdaBootstrap.java    From aws-lambda-native-vertx with 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 #29
Source File: JwtDummyHandler.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
public void parseCredentials(RoutingContext context, Handler<AsyncResult<JsonObject>> handler) {
  try {
    handler.handle(Future.succeededFuture(new JsonObject().put("jwt", getDummyJwt()).put("options", options)));
  } catch (Exception e) {
    handler.handle(Future.failedFuture(new HttpException(UNAUTHORIZED, "DUMMY Authorization failed.", e)));
  }
}
 
Example #30
Source File: JDBCSpaceConfigClient.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
@Override
protected void getSelectedSpaces(Marker marker, SpaceAuthorizationCondition authorizedCondition,
    SpaceSelectionCondition selectedCondition,
    Handler<AsyncResult<List<Space>>> handler) {
  //BUILD THE QUERY
  List<String> whereConjunctions = new ArrayList<>();
  String baseQuery = String.format("SELECT config FROM %s", SPACE_TABLE);
  List<String> authorizationWhereClauses = generateWhereClausesFor(authorizedCondition);
  if (!authorizationWhereClauses.isEmpty()) {
    authorizationWhereClauses.add("config->'shared' = 'true'");
  }

  List<String> selectionWhereClauses = generateWhereClausesFor(selectedCondition);
  if (!selectedCondition.shared && selectionWhereClauses.isEmpty()) {
    selectionWhereClauses.add("config->'shared' != 'true'");
  }

  if (!authorizationWhereClauses.isEmpty()) {
    whereConjunctions.add("(" + StringUtils.join(authorizationWhereClauses, " OR ") + ")");
  }
  if (!selectionWhereClauses.isEmpty()) {
    whereConjunctions.add("(" + StringUtils.join(selectionWhereClauses, " OR ") + ")");
  }

  String query = baseQuery + (whereConjunctions.isEmpty() ? "" :
      " WHERE " + StringUtils.join(whereConjunctions, " AND "));

  querySpaces(handler, query);
}