Java Code Examples for io.vertx.core.Future#failedFuture()

The following examples show how to use io.vertx.core.Future#failedFuture() . 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: PostgresClientTest.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
@Test
public void testProcessQueryFails() {
  PostgresClient testClient = PostgresClient.testClient();
  QueryHelper queryHelper = new QueryHelper("test_jsonb_pojo");
  queryHelper.selectQuery = "SELECT foo";

  PgConnection connection = new FakeSqlConnection(Future.failedFuture("Bad query"), false);

  testClient.processQuery(connection, queryHelper, 30, "get",
    totaledResults -> testClient.processResults(totaledResults.set, totaledResults.total, DEFAULT_OFFSET, DEFAULT_LIMIT, TestJsonbPojo.class),
    reply -> {
      assertThat(reply.failed(), is(true));
      assertThat(reply.cause().getMessage(), is("Bad query"));
    }
  );
}
 
Example 2
Source File: VertxBasedAmqpProtocolAdapter.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private static Future<ResourceIdentifier> getResourceIdentifier(final Source source) {

        if (source == null) {
            return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_NOT_FOUND, "no such node"));
        } else {
            final Promise<ResourceIdentifier> result = Promise.promise();
            try {
                if (Strings.isNullOrEmpty(source.getAddress())) {
                    result.fail(new ClientErrorException(HttpURLConnection.HTTP_NOT_FOUND,
                            "no such node"));
                } else {
                    result.complete(ResourceIdentifier.fromString(source.getAddress()));
                }
            } catch (Throwable e) {
                result.fail(e);
            }
            return result.future();
        }
    }
 
Example 3
Source File: DelegatingTenantAmqpEndpoint.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<Message> processGetByCaRequest(final Message request, final String subjectDn,
        final Span span) {

    try {
        final X500Principal dn = new X500Principal(subjectDn);
        log.debug("retrieving tenant [subject DN: {}]", subjectDn);
        return getService().get(dn, span).map(tr -> {
            String tenantId = null;
            if (tr.isOk() && tr.getPayload() != null) {
                tenantId = getTypesafeValueForField(String.class, tr.getPayload(),
                        TenantConstants.FIELD_PAYLOAD_TENANT_ID);
                TracingHelper.TAG_TENANT_ID.set(span, tenantId);
            }
            return TenantConstants.getAmqpReply(TenantConstants.TENANT_ENDPOINT, tenantId, request, tr);
        });
    } catch (final IllegalArgumentException e) {
        TracingHelper.logError(span, "illegal subject DN provided by client: " + subjectDn);
        // the given subject DN is invalid
        log.debug("cannot parse subject DN [{}] provided by client", subjectDn);
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
    }
}
 
Example 4
Source File: ConnectorMockTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
private Future<Map<String, Object>> kafkaConnectApiStatusMock(String host, String connectorName)   {
    ConnectorState connectorState = runningConnectors.get(key(host, connectorName));
    Map<String, Object> statusNode = new HashMap<>();
    statusNode.put("name", connectorName);
    Map<String, Object> connector = new HashMap<>();
    statusNode.put("connector", connector);
    connector.put("state", connectorState.paused ? "PAUSED" : "RUNNING");
    connector.put("worker_id", "somehost0:8083");
    Map<String, Object> task = new HashMap<>();
    task.put("id", 0);
    task.put("state", connectorState.paused ? "PAUSED" : "RUNNING");
    task.put("worker_id", "somehost2:8083");
    List<Map> tasks = singletonList(task);
    statusNode.put("tasks", tasks);

    return connectorState != null ? Future.succeededFuture(statusNode) : Future.failedFuture("No such connector " + connectorName);
}
 
Example 5
Source File: HttpContextTenantAndAuthIdProvider.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Get the tenant and auth-id from the <em>authorization</em> header of the given routing context request.
 *
 * @param ctx The execution context.
 * @param spanContext The OpenTracing context to use for tracking the operation (may be {@code null}).
 * @return A future indicating the outcome of the operation.
 *         <p>
 *         The future will fail if tenant and auth-id information could not be retrieved from the header
 *         or if there was an error obtaining the tenant object. In the latter case the future will be failed with a
 *         {@link org.eclipse.hono.client.ServiceInvocationException}.
 *         <p>
 *         Otherwise the future will contain the created <em>TenantObjectWithAuthId</em>.
 */
protected final Future<TenantObjectWithAuthId> getFromAuthHeader(final RoutingContext ctx,
        final SpanContext spanContext) {
    final String authorizationHeader = ctx.request().headers().get(HttpHeaders.AUTHORIZATION);
    if (authorizationHeader == null) {
        return Future.failedFuture("no auth header found");
    }
    String userName = null;
    try {
        final int idx = authorizationHeader.indexOf(' ');
        if (idx > 0 && "Basic".equalsIgnoreCase(authorizationHeader.substring(0, idx))) {
            final String authorization = authorizationHeader.substring(idx + 1);
            final String decoded = new String(Base64.getDecoder().decode(authorization));
            final int colonIdx = decoded.indexOf(":");
            userName = colonIdx != -1 ? decoded.substring(0, colonIdx) : decoded;
        }
    } catch (final RuntimeException e) {
        LOG.debug("error parsing auth header: {}", e.getMessage());
    }
    if (userName == null) {
        return Future.failedFuture("unsupported auth header value");
    }
    return getFromUserName(userName, spanContext);
}
 
Example 6
Source File: ProtocolGateway.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<Void> executeCommand(final String[] command, final NetSocket socket, final Map<String, Object> dictionary) {

        final String commandName = command[0];
        final String args = command.length > 1 ? command[1] : null;

        LOG.debug("processing command: {}", commandName);
        switch (commandName) {
        case CMD_LOGIN:
            return login(args, socket, dictionary);
        case TelemetryConstants.TELEMETRY_ENDPOINT:
        case TelemetryConstants.TELEMETRY_ENDPOINT_SHORT:
            return sendTelemetry(args, socket, dictionary);
        case EventConstants.EVENT_ENDPOINT:
        case EventConstants.EVENT_ENDPOINT_SHORT:
            return sendEvent(args, socket, dictionary);
        case CMD_SUBSCRIBE:
            return subscribe(socket, dictionary);
        case CMD_UNSUBSCRIBE:
            return unsubscribe(socket, dictionary);
        default:
            LOG.debug("unsupported command [{}]", commandName);
            return Future.failedFuture("no such command");
        }
    }
 
Example 7
Source File: KafkaRebalanceAssemblyOperator.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
protected Future<KafkaRebalanceStatus> computeNextStatus(Reconciliation reconciliation,
                                                       String host, CruiseControlApi apiClient,
                                                       KafkaRebalance kafkaRebalance, State currentState,
                                                       RebalanceAnnotation rebalanceAnnotation, RebalanceOptions.RebalanceOptionsBuilder rebalanceOptionsBuilder) {
    switch (currentState) {
        case New:
            return onNew(reconciliation, host, apiClient, rebalanceOptionsBuilder);
        case PendingProposal:
            return onPendingProposal(reconciliation, host, apiClient, kafkaRebalance, rebalanceAnnotation, rebalanceOptionsBuilder);
        case ProposalReady:
            return onProposalReady(reconciliation, host, apiClient, kafkaRebalance, rebalanceAnnotation, rebalanceOptionsBuilder);
        case Rebalancing:
            return onRebalancing(reconciliation, host, apiClient, kafkaRebalance, rebalanceAnnotation);
        case Stopped:
            return onStop(reconciliation, host, apiClient, rebalanceAnnotation, rebalanceOptionsBuilder);
        case Ready:
            // Rebalance Complete
            return Future.succeededFuture(kafkaRebalance.getStatus());
        case NotReady:
            // Error case
            return onNotReady(reconciliation, host, apiClient, kafkaRebalance, rebalanceAnnotation, rebalanceOptionsBuilder);
        default:
            return Future.failedFuture(new RuntimeException("Unexpected state " + currentState));
    }
}
 
Example 8
Source File: MockTopicStore.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Void> delete(TopicName topicName) {
    Future<Void> response = deleteTopicResponse.apply(topicName);
    if (response.succeeded()) {
        Topic topic = topics.remove(topicName);
        if (topic == null) {
            return Future.failedFuture(new TopicStore.NoSuchEntityExistsException());
        }
    }
    return response;
}
 
Example 9
Source File: TableManagementStore.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static Future<Object> checkUpdateOutcome(final UpdateResult updateResult) {
    if (updateResult.getUpdated() < 0) {
        // conflict
        log.debug("Optimistic lock broke");
        return Future.failedFuture(new OptimisticLockingException());
    }

    return Future.succeededFuture();
}
 
Example 10
Source File: TableManagementStore.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static Future<String> extractVersionForUpdate(final ResultSet device) {
    final Optional<String> version = device.getRows(true).stream().map(o -> o.getString("version")).findAny();

    if (version.isEmpty()) {
        log.debug("No version or no row found -> entity not found");
        return Future.failedFuture(new EntityNotFoundException());
    }

    return Future.succeededFuture(version.get());
}
 
Example 11
Source File: AbstractNonNamespacedResourceOperator.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a resource with the name with the given desired state
 * and completes the given future accordingly.
 */
@SuppressWarnings("unchecked")
protected Future<ReconcileResult<T>> internalCreate(String name, T desired) {
    try {
        ReconcileResult<T> result = ReconcileResult.created(operation().withName(name).create(desired));
        log.debug("{} {} has been created", resourceKind, name);
        return Future.succeededFuture(result);
    } catch (Exception e) {
        log.debug("Caught exception while creating {} {}", resourceKind, name, e);
        return Future.failedFuture(e);
    }
}
 
Example 12
Source File: JmsBasedRegistrationClient.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Sends a request for an operation.
 *
 * @param operation The name of the operation to invoke or {@code null} if the message
 *                  should not have a subject.
 * @param applicationProperties Application properties to set on the request message or
 *                              {@code null} if no properties should be set.
 * @param payload Payload to include or {@code null} if the message should have no body.
 * @return A future indicating the outcome of the operation.
 */
public Future<JsonObject> sendRequest(
        final String operation,
        final Map<String, Object> applicationProperties,
        final Buffer payload) {

    try {
        final Message request = createMessage(payload);

        if  (operation != null) {
            request.setJMSType(operation);
        }

        if (applicationProperties != null) {
            for (Map.Entry<String, Object> entry : applicationProperties.entrySet()) {
                if (entry.getValue() instanceof String) {
                    request.setStringProperty(entry.getKey(), (String) entry.getValue());
                } else {
                    request.setObjectProperty(entry.getKey(), entry.getValue());
                }
            }
        }

        return send(request)
                .compose(registrationResult -> {
                    final Promise<JsonObject> result = Promise.promise();
                    switch (registrationResult.getStatus()) {
                    case HttpURLConnection.HTTP_OK:
                        result.complete(registrationResult.getPayload());
                        break;
                    case HttpURLConnection.HTTP_NOT_FOUND:
                        result.fail(new ClientErrorException(registrationResult.getStatus(), "no such device"));
                        break;
                    default:
                        result.fail(StatusCodeMapper.from(registrationResult));
                    }
                    return result.future();
                });
    } catch (JMSException e) {
        return Future.failedFuture(getServiceInvocationException(e));
    }
}
 
Example 13
Source File: CommandResponse.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
public static <R> CommandResponse<R> failure(Throwable cause) {
  return new CommandResponse<>(Future.failedFuture(cause));
}
 
Example 14
Source File: AbstractVertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Uploads a command response message.
 *
 * @param ctx The context in which the MQTT message has been published.
 * @param targetAddress The address that the response should be forwarded to.
 * @return A future indicating the outcome of the operation.
 *         <p>
 *         The future will succeed if the message has been uploaded successfully.
 *         Otherwise, the future will fail with a {@link ServiceInvocationException}.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
public final Future<Void> uploadCommandResponseMessage(
        final MqttContext ctx,
        final ResourceIdentifier targetAddress) {

    Objects.requireNonNull(ctx);
    Objects.requireNonNull(targetAddress);

    final String[] addressPath = targetAddress.getResourcePath();
    Integer status = null;
    String reqId = null;

    final Future<CommandResponse> commandResponseTracker;
    if (addressPath.length <= CommandConstants.TOPIC_POSITION_RESPONSE_STATUS) {
        commandResponseTracker = Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                "command response topic has too few segments"));
    } else {
        try {
            status = Integer.parseInt(addressPath[CommandConstants.TOPIC_POSITION_RESPONSE_STATUS]);
        } catch (final NumberFormatException e) {
            log.trace("got invalid status code [{}] [tenant-id: {}, device-id: {}]",
                    addressPath[CommandConstants.TOPIC_POSITION_RESPONSE_STATUS], targetAddress.getTenantId(), targetAddress.getResourceId());
        }
        if (status != null) {
            reqId = addressPath[CommandConstants.TOPIC_POSITION_RESPONSE_REQ_ID];
            final CommandResponse commandResponse = CommandResponse.from(reqId, targetAddress.getTenantId(),
                    targetAddress.getResourceId(), ctx.message().payload(), ctx.contentType(), status);

            commandResponseTracker = commandResponse != null ? Future.succeededFuture(commandResponse)
                    : Future.failedFuture(new ClientErrorException(
                            HttpURLConnection.HTTP_BAD_REQUEST, "command response topic contains invalid data"));
        } else {
            // status code could not be parsed
            commandResponseTracker = Future.failedFuture(
                    new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "invalid status code"));
        }
    }

    final Span currentSpan = TracingHelper
            .buildChildSpan(tracer, ctx.getTracingContext(), "upload Command response", getTypeName())
            .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
            .withTag(TracingHelper.TAG_TENANT_ID, targetAddress.getTenantId())
            .withTag(TracingHelper.TAG_DEVICE_ID, targetAddress.getResourceId())
            .withTag(Constants.HEADER_COMMAND_RESPONSE_STATUS, status)
            .withTag(Constants.HEADER_COMMAND_REQUEST_ID, reqId)
            .withTag(TracingHelper.TAG_AUTHENTICATED.getKey(), ctx.authenticatedDevice() != null)
            .start();

        final int payloadSize = Optional.ofNullable(ctx.message().payload()).map(Buffer::length).orElse(0);
        final Future<JsonObject> tokenTracker = getRegistrationAssertion(targetAddress.getTenantId(),
                targetAddress.getResourceId(), ctx.authenticatedDevice(), currentSpan.context());
        final Future<TenantObject> tenantTracker = getTenantConfiguration(targetAddress.getTenantId(), ctx.getTracingContext());
        final Future<TenantObject> tenantValidationTracker = CompositeFuture.all(
                                isAdapterEnabled(tenantTracker.result()),
                                checkMessageLimit(tenantTracker.result(), payloadSize, currentSpan.context()))
                                .map(success -> tenantTracker.result());

    return CompositeFuture.all(tenantTracker, commandResponseTracker)
            .compose(success -> CompositeFuture.all(tokenTracker, tenantValidationTracker))
            .compose(ok -> sendCommandResponse(targetAddress.getTenantId(), commandResponseTracker.result(),
                    currentSpan.context()))
            .compose(delivery -> {
                log.trace("successfully forwarded command response from device [tenant-id: {}, device-id: {}]",
                        targetAddress.getTenantId(), targetAddress.getResourceId());
                metrics.reportCommand(
                        Direction.RESPONSE,
                        targetAddress.getTenantId(),
                        tenantTracker.result(),
                        ProcessingOutcome.FORWARDED,
                        payloadSize,
                        ctx.getTimer());
                // check that the remote MQTT client is still connected before sending PUBACK
                if (ctx.deviceEndpoint().isConnected() && ctx.message().qosLevel() == MqttQoS.AT_LEAST_ONCE) {
                    ctx.deviceEndpoint().publishAcknowledge(ctx.message().messageId());
                }
                currentSpan.finish();
                return Future.<Void> succeededFuture();
            })
            .recover(t -> {
                TracingHelper.logError(currentSpan, t);
                currentSpan.finish();
                metrics.reportCommand(
                        Direction.RESPONSE,
                        targetAddress.getTenantId(),
                        tenantTracker.result(),
                        ProcessingOutcome.from(t),
                        payloadSize,
                        ctx.getTimer());
                return Future.failedFuture(t);
            });
}
 
Example 15
Source File: AbstractVertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private Future<Void> uploadMessage(
        final MqttContext ctx,
        final TenantObject tenantObject,
        final String deviceId,
        final Buffer payload,
        final Future<DownstreamSender> senderTracker,
        final MetricsTags.EndpointType endpoint) {

    if (!isPayloadOfIndicatedType(payload, ctx.contentType())) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                String.format("Content-Type %s does not match payload", ctx.contentType())));
    }

    final Span currentSpan = TracingHelper.buildChildSpan(tracer, ctx.getTracingContext(),
            "upload " + endpoint, getTypeName())
            .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
            .withTag(TracingHelper.TAG_TENANT_ID, tenantObject.getTenantId())
            .withTag(TracingHelper.TAG_DEVICE_ID, deviceId)
            .withTag(TracingHelper.TAG_AUTHENTICATED.getKey(), ctx.authenticatedDevice() != null)
            .start();

    final Future<JsonObject> tokenTracker = getRegistrationAssertion(tenantObject.getTenantId(), deviceId,
            ctx.authenticatedDevice(), currentSpan.context());
    final Future<?> tenantValidationTracker = CompositeFuture.all(
            isAdapterEnabled(tenantObject),
            checkMessageLimit(tenantObject, payload.length(), currentSpan.context()));

    return CompositeFuture.all(tokenTracker, tenantValidationTracker, senderTracker).compose(ok -> {

        final DownstreamSender sender = senderTracker.result();
        final Message downstreamMessage = newMessage(
                ResourceIdentifier.from(endpoint.getCanonicalName(), tenantObject.getTenantId(), deviceId),
                ctx.message().topicName(),
                ctx.contentType(),
                payload,
                tenantObject,
                tokenTracker.result(),
                null,
                EndpointType.EVENT.equals(endpoint) ? getTimeToLive(ctx.propertyBag()) : null);

        addRetainAnnotation(ctx, downstreamMessage, currentSpan);
        customizeDownstreamMessage(downstreamMessage, ctx);

        if (ctx.isAtLeastOnce()) {
            return sender.sendAndWaitForOutcome(downstreamMessage, currentSpan.context());
        } else {
            return sender.send(downstreamMessage, currentSpan.context());
        }
    }).compose(delivery -> {

        log.trace("successfully processed message [topic: {}, QoS: {}] from device [tenantId: {}, deviceId: {}]",
                ctx.message().topicName(), ctx.message().qosLevel(), tenantObject.getTenantId(), deviceId);
        // check that the remote MQTT client is still connected before sending PUBACK
        if (ctx.isAtLeastOnce() && ctx.deviceEndpoint().isConnected()) {
            currentSpan.log("sending PUBACK");
            ctx.acknowledge();
        }
        currentSpan.finish();
        return Future.<Void> succeededFuture();

    }).recover(t -> {

        if (ClientErrorException.class.isInstance(t)) {
            final ClientErrorException e = (ClientErrorException) t;
            log.debug("cannot process message [endpoint: {}] from device [tenantId: {}, deviceId: {}]: {} - {}",
                    endpoint, tenantObject.getTenantId(), deviceId, e.getErrorCode(), e.getMessage());
        } else {
            log.debug("cannot process message [endpoint: {}] from device [tenantId: {}, deviceId: {}]",
                    endpoint, tenantObject.getTenantId(), deviceId, t);
        }
        TracingHelper.logError(currentSpan, t);
        currentSpan.finish();
        return Future.failedFuture(t);
    });
}
 
Example 16
Source File: DelegatingTenantAmqpEndpoint.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private Future<Message> processGetRequest(final Message request, final SpanContext spanContext) {

        final String tenantId = MessageHelper.getTenantId(request);

        final Span span = TracingHelper.buildServerChildSpan(tracer,
                spanContext,
                SPAN_NAME_GET_TENANT,
                getClass().getSimpleName())
                .start();

        final JsonObject payload;
        try {
            payload = MessageHelper.getJsonPayload(request);
        } catch (final DecodeException e) {
            logger.debug("failed to decode AMQP request message", e);
            return finishSpanOnFutureCompletion(span, Future.failedFuture(
                    new ClientErrorException(
                            HttpURLConnection.HTTP_BAD_REQUEST,
                            "request message body contains malformed JSON")));
        }

        final Future<Message> resultFuture;
        if (tenantId == null && payload == null) {
            TracingHelper.logError(span, "request does not contain any query parameters");
            log.debug("request does not contain any query parameters");
            resultFuture = Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));

        } else if (tenantId != null) {

            // deprecated API
            log.debug("retrieving tenant [{}] using deprecated variant of get tenant request", tenantId);
            TracingHelper.TAG_TENANT_ID.set(span, tenantId);
            span.log("using deprecated variant of get tenant request");
            // span will be finished in processGetByIdRequest
            resultFuture = processGetByIdRequest(request, tenantId, span);

        } else {

            final String tenantIdFromPayload = getTypesafeValueForField(String.class, payload,
                    TenantConstants.FIELD_PAYLOAD_TENANT_ID);
            final String subjectDn = getTypesafeValueForField(String.class, payload,
                    TenantConstants.FIELD_PAYLOAD_SUBJECT_DN);

            if (tenantIdFromPayload == null && subjectDn == null) {
                TracingHelper.logError(span, "request does not contain any query parameters");
                log.debug("payload does not contain any query parameters");
                resultFuture = Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
            } else if (tenantIdFromPayload != null) {
                log.debug("retrieving tenant [id: {}]", tenantIdFromPayload);
                TracingHelper.TAG_TENANT_ID.set(span, tenantIdFromPayload);
                resultFuture = processGetByIdRequest(request, tenantIdFromPayload, span);
            } else {
                span.setTag(TAG_SUBJECT_DN_NAME, subjectDn);
                resultFuture = processGetByCaRequest(request, subjectDn, span);
            }
        }

        return finishSpanOnFutureCompletion(span, resultFuture);
    }
 
Example 17
Source File: DelegatingDeviceConnectionAmqpEndpoint.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Processes a <em>get command handling protocol adapter instance</em> request message.
 *
 * @param request The request message.
 * @param targetAddress The address the message is sent to.
 * @param spanContext The span context representing the request to be processed.
 * @return The response to send to the client via the event bus.
 */
protected Future<Message> processGetCmdHandlingAdapterInstances(final Message request,
        final ResourceIdentifier targetAddress, final SpanContext spanContext) {
    final String tenantId = targetAddress.getTenantId();
    final String deviceId = MessageHelper.getDeviceId(request);

    final Span span = TracingHelper.buildServerChildSpan(
            tracer,
            spanContext,
            SPAN_NAME_GET_CMD_HANDLING_ADAPTER_INSTANCES,
            getClass().getSimpleName()
    ).start();

    final JsonObject payload;
    try {
        payload = MessageHelper.getJsonPayload(request);
    } catch (DecodeException e) {
        logger.debug("failed to decode AMQP request message", e);
        return finishSpanOnFutureCompletion(span, Future.failedFuture(
                new ClientErrorException(
                        HttpURLConnection.HTTP_BAD_REQUEST,
                        "request message body contains malformed JSON")));
    }

    final Future<Message> resultFuture;
    if (tenantId == null || deviceId == null || payload == null) {
        TracingHelper.logError(span, "missing tenant, device and/or payload");
        resultFuture = Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
    } else {
        TracingHelper.TAG_TENANT_ID.set(span, tenantId);
        TracingHelper.TAG_DEVICE_ID.set(span, deviceId);

        final Object gatewaysValue = payload.getValue(DeviceConnectionConstants.FIELD_GATEWAY_IDS);
        if (!(gatewaysValue instanceof JsonArray)) {
            TracingHelper.logError(span, "payload JSON is missing valid '" + DeviceConnectionConstants.FIELD_GATEWAY_IDS + "' field value");
            resultFuture = Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
        } else {
            log.debug("getting command handling adapter instances for tenant [{}], device [{}]", tenantId, deviceId);

            @SuppressWarnings("unchecked")
            final List<String> list = ((JsonArray) gatewaysValue).getList();
            resultFuture = getService().getCommandHandlingAdapterInstances(tenantId, deviceId, list, span)
                    .map(res -> DeviceConnectionConstants.getAmqpReply(
                            DeviceConnectionConstants.DEVICE_CONNECTION_ENDPOINT,
                            tenantId,
                            request,
                            res)
                    );
        }
    }
    return finishSpanOnFutureCompletion(span, resultFuture);
}
 
Example 18
Source File: ApiException.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
public static <T> AsyncResult<T> fail(Throwable throwable) {
    return Future.failedFuture(new ApiException(throwable));
}
 
Example 19
Source File: MongoDbDeviceRegistryUtils.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Checks whether a registry component supports modification of persistent data.
 *
 * @param config The configuration properties of the affected registry component.
 * @return A future indicating the outcome of the operation.
 *         <p>
 *         The future will be succeeded if modification is supported.
 *         Otherwise the future will be failed with a {@link ClientErrorException} with
 *         error code {@value HttpURLConnection#HTTP_FORBIDDEN}.
 * @throws NullPointerException if any of the parameters is {@code null}.
 */
public static Future<Void> isModificationEnabled(final AbstractMongoDbBasedRegistryConfigProperties config) {
    Objects.requireNonNull(config);

    if (config.isModificationEnabled()) {
        return Future.succeededFuture();
    } else {
        return Future.failedFuture(
                new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN, "modification is disabled"));
    }
}
 
Example 20
Source File: DelegatingRegistrationAmqpEndpoint.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Processes a request for a non-standard operation.
 * <p>
 * Subclasses should override this method in order to support additional, custom
 * operations that are not defined by Hono's Device Registration API.
 * <p>
 * This default implementation simply returns a future that is failed with a
 * {@link ClientErrorException} with an error code <em>400 Bad Request</em>.
 *
 * @param request The request to process.
 * @param spanContext The span context representing the request to be processed.
 * @return A future indicating the outcome of the service invocation.
 */
protected Future<Message> processCustomRegistrationMessage(final Message request, final SpanContext spanContext) {
    log.debug("invalid operation in request message [{}]", request.getSubject());
    return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
}