Java Code Examples for io.vertx.core.Handler#handle()

The following examples show how to use io.vertx.core.Handler#handle() . 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: MockedRemoteFunctionClient.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
@Override
protected void invoke(Marker marker, byte[] bytes, boolean fireAndForget, Handler<AsyncResult<byte[]>> callback) {
    long executionTime = (long) (Math.random() * (double) (maxExecutionTime - minExecutionTime) + minExecutionTime);

    MockedRequest req = new MockedRequest(callback) {
        @Override
        public void run() {
            try {
                Thread.sleep(executionTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            endTime = Service.currentTimeMillis();
            long eT = this.endTime - this.startTime;
            logger.info("Request " + requestId + " was executed with desired executionTime: " + executionTime + "ms and actual eT: " + eT + "ms; relEndTime: " + (endTime - testStart));
            callback.handle(Future.succeededFuture());
        }
    };

    threadPool.schedule(req, 0, TimeUnit.MILLISECONDS);
}
 
Example 2
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 3
Source File: DynamoSpaceConfigClient.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
@Override
public void storeSpace(Marker marker, Space space, Handler<AsyncResult<Space>> handler) {
  try {
    logger.info(marker, "Storing space with ID: {}", space.getId());

    final Map<String, Object> itemData = XyzSerializable.STATIC_MAPPER.get().convertValue(space, new TypeReference<Map<String, Object>>() {});
    itemData.put("shared", space.isShared() ? 1 : 0); // shared value must be a number because it's also used as index

    sanitize(itemData);
    spaces.putItem(Item.fromMap(itemData));

    deleteSpaceFromPackage(marker, space);
    storeSpaceIntoPackages(marker, space);

    logger.info(marker, "Space with ID: {} has been successfully stored", space.getId());
    handler.handle(Future.succeededFuture(space));
  } catch (AmazonDynamoDBException e) {
    logger.error(marker, "Failure storing a space into DynamoDB", e);
    handler.handle(Future.failedFuture(e));
  }
}
 
Example 4
Source File: RemoteFunctionClient.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
protected void submit(final Marker marker, byte[] bytes, boolean fireAndForget, final Handler<AsyncResult<byte[]>> callback) {
  Handler<AsyncResult<byte[]>> cb = r -> {
    //This is the point where the request's response came back so measure the throughput
    invokeCompleted();
    if (r.succeeded()) {
      try {
        callback.handle(Future.succeededFuture(handleByteResponse(r.result())));
      }
      catch (HttpException | IOException e) {
        callback.handle(Future.failedFuture(e));
      }
    }
    else {
      callback.handle(r);
    }
  };

  //This is the point where new requests arrive so measure the arrival time
  invokeStarted();

  if (!compareAndIncrementUpTo(getMaxConnections(), usedConnections)) {
    enqueue(marker, bytes, fireAndForget, cb);
    return;
  }
  _invoke(marker, bytes, fireAndForget, cb);
}
 
Example 5
Source File: RpcClient.java    From xyz-hub with 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 6
Source File: TomlAuth.java    From besu with Apache License 2.0 5 votes vote down vote up
private void checkPasswordHash(
    final String password,
    final String passwordHash,
    final Handler<AsyncResult<Void>> resultHandler) {
  boolean passwordMatches = BCrypt.checkpw(password, passwordHash);
  if (passwordMatches) {
    resultHandler.handle(Future.succeededFuture());
  } else {
    resultHandler.handle(Future.failedFuture("Invalid password"));
  }
}
 
Example 7
Source File: DynamoConnectorConfigClient.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
@Override
protected void getAllConnectors(Marker marker, Handler<AsyncResult<List<Connector>>> handler) {
  final List<Connector> result = new ArrayList<>();
  try {
    connectors.scan().pages().forEach(p -> p.forEach(i -> {
      final Connector connector = Json.decodeValue(i.toJSON(), Connector.class);
      result.add(connector);
    }));
    handler.handle(Future.succeededFuture(result));
  }
  catch (Exception e) {
    handler.handle(Future.failedFuture(new RuntimeException("Error retrieving all connectors.", e)));
  }
}
 
Example 8
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 9
Source File: JDBCSpaceConfigClient.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
@Override
protected void storeSpace(Marker marker, Space space, Handler<AsyncResult<Space>> handler) {
  SQLQuery query = null;
  try {
    query = new SQLQuery(String.format(
        "INSERT INTO %s(id, owner, cid, config) VALUES (?, ?, ?, cast(? as JSONB)) ON CONFLICT (id) DO UPDATE SET owner = excluded.owner, cid = excluded.cid, config = excluded.config",
        SPACE_TABLE), space.getId(), space.getOwner(), space.getCid(),
        XyzSerializable.STATIC_MAPPER.get().writeValueAsString(space));
    updateWithParams(space, query, handler);
  } catch (JsonProcessingException e) {
    handler.handle(Future.failedFuture(new EncodeException("Failed to encode as JSON: " + e.getMessage(), e)));
  }
}
 
Example 10
Source File: FeatureTaskHandler.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
private static <X extends FeatureTask<?, X>>void getCountForSpace(X task, Handler<AsyncResult<Long>> handler) {
  final CountFeaturesEvent countEvent = new CountFeaturesEvent();
  countEvent.setSpace(task.getEvent().getSpace());
  countEvent.setParams(task.getEvent().getParams());

  try {
    RpcClient.getInstanceFor(task.storage)
        .execute(task.getMarker(), countEvent, (AsyncResult<XyzResponse> eventHandler) -> {
          if (eventHandler.failed()) {
            handler.handle(Future.failedFuture((eventHandler.cause())));
            return;
          }
          Long count;
          final XyzResponse response = eventHandler.result();
          if (response instanceof CountResponse) {
            count = ((CountResponse) response).getCount();
          } else if (response instanceof FeatureCollection) {
            count = ((FeatureCollection) response).getCount();
          } else {
            handler.handle(Future.failedFuture(Api.responseToHttpException(response)));
            return;
          }
          handler.handle(Future.succeededFuture(count));
        });
  } catch (Exception e) {
    handler.handle(Future.failedFuture((e)));
  }
}
 
Example 11
Source File: InMemSpaceConfigClient.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
@Override
public void storeSpace(Marker marker, Space space, Handler<AsyncResult<Space>> handler) {
  if (space.getId() == null) {
    space.setId(RandomStringUtils.randomAlphanumeric(10));
  }
  spaceMap.put(space.getId(), space);
  handler.handle(Future.succeededFuture(space));
}
 
Example 12
Source File: SpaceConfigClient.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
public void get(Marker marker, String spaceId, Handler<AsyncResult<Space>> handler) {
  Space cached = cache.get(spaceId);
  if (cached != null) {
    logger.info(marker, "space[{}]: Loaded space with title \"{}\" from cache", spaceId, cached.getTitle());
    handler.handle(Future.succeededFuture(cached));
    return;
  }

  /*
  In case we get the query for a space of which a previous request is already in flight we wait for its response and call the callback
  then. This is a performance optimization for highly parallel requests coming from the user at once.
   */
  boolean isFirstRequest = pendingHandlers.putIfAbsent(spaceId, new ConcurrentLinkedQueue<>()) == null;
  pendingHandlers.get(spaceId).add(handler);
  if (!isFirstRequest) {
    return;
  }

  getSpace(marker, spaceId, ar -> {
    ConcurrentLinkedQueue<Handler<AsyncResult<Space>>> handlersToCall = pendingHandlers.remove(spaceId);
    if (ar.succeeded()) {
      Space space = ar.result();
      if (space != null) {
        cache.put(spaceId, space);
        logger.info(marker, "space[{}]: Loaded space with title: \"{}\"", spaceId, space.getTitle());
      } else {
        logger.info(marker, "space[{}]: Space with this ID was not found", spaceId);
      }
      cache.put(spaceId, space);
      handlersToCall.forEach(h -> h.handle(Future.succeededFuture(ar.result())));
    } else {
      logger.error(marker, "space[{}]: Failed to load the space, reason: {}", spaceId, ar.cause());
      handlersToCall.forEach(h -> h.handle(Future.failedFuture(ar.cause())));
    }
  });
}
 
Example 13
Source File: InMemSpaceConfigClient.java    From xyz-hub with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Handler<AsyncResult<Void>> onReady) {
  onReady.handle(Future.succeededFuture());
}
 
Example 14
Source File: InMemSpaceConfigClient.java    From xyz-hub with Apache License 2.0 4 votes vote down vote up
@Override
public void deleteSpace(Marker marker, String spaceId, Handler<AsyncResult<Space>> handler) {
  Space space = spaceMap.remove(spaceId);
  handler.handle(Future.succeededFuture(space));
}
 
Example 15
Source File: DynamoConnectorConfigClient.java    From xyz-hub with Apache License 2.0 4 votes vote down vote up
@Override
protected void storeConnector(Marker marker, Connector connector, Handler<AsyncResult<Connector>> handler) {
  logger.debug(marker, "Storing connector ID {} into Dynamo Table {}", connector.id, dynamoClient.tableName);
  connectors.putItem(Item.fromJSON(Json.encode(connector)));
  handler.handle(Future.succeededFuture());
}
 
Example 16
Source File: RpcClient.java    From xyz-hub with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
private void parseResponse(Marker marker, final Typed payload, final Handler<AsyncResult<XyzResponse>> callback) {
  try {
    if (payload == null)
      throw new NullPointerException("Response payload is null");
    if (payload instanceof ErrorResponse) {
      ErrorResponse errorResponse = (ErrorResponse) payload;
      logger.warn(marker, "The connector responded with an error of type {}: {}", errorResponse.getError(),
          errorResponse.getErrorMessage());

      switch (errorResponse.getError()) {
        case NOT_IMPLEMENTED:
          throw new HttpException(NOT_IMPLEMENTED, "The connector is unable to process this request.");
        case CONFLICT:
          throw new HttpException(CONFLICT, "A conflict occurred when updating a feature: " + errorResponse.getErrorMessage());
        case FORBIDDEN:
          throw new HttpException(FORBIDDEN, "The user is not authorized.");
        case TOO_MANY_REQUESTS:
          throw new HttpException(TOO_MANY_REQUESTS,
              "The connector cannot process the message due to a limitation in an upstream service or a database.");
        case ILLEGAL_ARGUMENT:
          throw new HttpException(BAD_REQUEST, errorResponse.getErrorMessage());
        case TIMEOUT:
          throw new HttpException(GATEWAY_TIMEOUT, "Connector timeout error.");
        case EXCEPTION:
        case BAD_GATEWAY:
          throw new HttpException(BAD_GATEWAY, "Connector error.");
      }
    }
    if (payload instanceof XyzResponse) {
      //noinspection rawtypes
      callback.handle(Future.succeededFuture((XyzResponse) payload));
      return;
    }

    logger.warn(marker, "The connector responded with an unexpected response type {}", payload.getClass().getSimpleName());
    callback.handle(Future.failedFuture(new HttpException(BAD_GATEWAY, "The connector responded with unexpected response type.")));
  } catch (HttpException e) {
    callback.handle(Future.failedFuture(e));
  }
}
 
Example 17
Source File: JDBCConfig.java    From xyz-hub with Apache License 2.0 4 votes vote down vote up
public static synchronized void init(Handler<AsyncResult<Void>> onReady) {
  if (initialized) {
    onReady.handle(Future.succeededFuture());
    return;
  }

  initialized = true;

  client.getConnection(res -> {
    if (res.failed()) {
      logger.error("Initializing of the config table failed.", res.cause());
      onReady.handle(Future.failedFuture(res.cause()));
      return;
    }
    SQLConnection connection = res.result();

    String query = "SELECT schema_name FROM information_schema.schemata WHERE schema_name='xyz_config'";
    connection.query(query, out -> {
      if (out.succeeded() && out.result().getNumRows() > 0) {
        logger.info("schema already created");
        onReady.handle(Future.succeededFuture());
        connection.close();
        return;
      }
      List<String> batchQueries = Arrays.asList(
          String.format("CREATE SCHEMA %s", SCHEMA),
          String.format("CREATE table  %s (id VARCHAR(50) primary key, config JSONB)", CONNECTOR_TABLE),
          String.format("CREATE table  %s (id VARCHAR(50) primary key, owner VARCHAR (50), cid VARCHAR (50), config JSONB)", SPACE_TABLE)
      );

      Future<Void> onComplete = Future.future();
      Future<Void> step1Completer = Future.future();

      // step 1
      Runnable step1 = () -> connection.setAutoCommit(false, step1Completer.completer());

      // step 2
      step1Completer.compose(r -> {
        Future<List<Integer>> f = Future.future();
        connection.batch(batchQueries, f.completer());
        return f;
      }).compose(r -> connection.setAutoCommit(true, onComplete.completer()), onComplete);

      // step 3
      onComplete.setHandler(ar -> {
        if (ar.failed()) {
          logger.error("Initializing of the config table failed.", ar.cause());
        } else {
          logger.info("Initializing of the config table was successful.");
        }
        onReady.handle(ar);
        connection.close();
      });

      step1.run();
    });
  });
}
 
Example 18
Source File: NoopCacheClient.java    From xyz-hub with Apache License 2.0 4 votes vote down vote up
@Override
public void get(String key, Handler<String> handler) {
	handler.handle(null);
	return;
}
 
Example 19
Source File: TestWriteStream.java    From vertx-spring-boot with Apache License 2.0 4 votes vote down vote up
@Override
public WriteStream<T> write(T data, Handler<AsyncResult<Void>> handler) {
    received.add(data);
    handler.handle(Future.succeededFuture());
    return this;
}
 
Example 20
Source File: InMemConnectorConfigClient.java    From xyz-hub with Apache License 2.0 4 votes vote down vote up
@Override
protected void getAllConnectors(Marker marker, Handler<AsyncResult<List<Connector>>> handler) {
  List<Connector> connectors = new ArrayList<>(storageMap.values());
  handler.handle(Future.succeededFuture(connectors));
}