List of usage examples for io.vertx.core Future failedFuture
static <T> Future<T> failedFuture(String failureMessage)
From source file:org.eclipse.hono.adapter.http.X509AuthHandler.java
License:Open Source License
private Future<X509Certificate[]> getX509CertificateChain(final Certificate[] clientChain) { final List<X509Certificate> chain = new LinkedList<>(); for (Certificate cert : clientChain) { if (cert instanceof X509Certificate) { chain.add((X509Certificate) cert); } else {/* ww w . j a v a 2 s.co m*/ LOG.info("cannot authenticate device using unsupported certificate type [{}]", cert.getClass().getName()); return Future.failedFuture(UNAUTHORIZED); } } return Future.succeededFuture(chain.toArray(new X509Certificate[chain.size()])); }
From source file:org.eclipse.hono.adapter.kura.KuraProtocolAdapter.java
License:Open Source License
/** * {@inheritDoc}/*www . j av a 2s. c om*/ */ @Override protected Future<Void> onPublishedMessage(final MqttContext ctx) { return mapTopic(ctx).recover(t -> { LOG.debug("discarding message [topic: {}] from device: {}", ctx.message().topicName(), t.getMessage()); return Future.failedFuture(t); }).compose(address -> uploadMessage(ctx, address, ctx.message().payload())); }
From source file:org.eclipse.hono.adapter.mqtt.AbstractVertxBasedMqttProtocolAdapter.java
License:Open Source License
private Future<Void> bindSecureMqttServer() { if (isSecurePortEnabled()) { final MqttServerOptions options = new MqttServerOptions(); options.setHost(getConfig().getBindAddress()).setPort(determineSecurePort()) .setMaxMessageSize(getConfig().getMaxPayloadSize()); addTlsKeyCertOptions(options);//from w ww. j a va2 s . com addTlsTrustOptions(options); return bindMqttServer(options, server).map(s -> { server = s; return (Void) null; }).recover(t -> { return Future.failedFuture(t); }); } else { return Future.succeededFuture(); } }
From source file:org.eclipse.hono.adapter.mqtt.AbstractVertxBasedMqttProtocolAdapter.java
License:Open Source License
private Future<Void> bindInsecureMqttServer() { if (isInsecurePortEnabled()) { final MqttServerOptions options = new MqttServerOptions(); options.setHost(getConfig().getInsecurePortBindAddress()).setPort(determineInsecurePort()) .setMaxMessageSize(getConfig().getMaxPayloadSize()); return bindMqttServer(options, insecureServer).map(server -> { insecureServer = server;/*from w ww .jav a 2s.c om*/ return (Void) null; }).recover(t -> { return Future.failedFuture(t); }); } else { return Future.succeededFuture(); } }
From source file:org.eclipse.hono.adapter.mqtt.AbstractVertxBasedMqttProtocolAdapter.java
License:Open Source License
/** * Create a future indicating a rejected connection. * /*from w w w . j a v a 2 s . co m*/ * @param returnCode The error code to return. * @param <T> The type of the returned future. * @return A future indicating a rejected connection. */ protected static <T> Future<T> rejected(final MqttConnectReturnCode returnCode) { return Future.failedFuture(new MqttConnectionException( returnCode != null ? returnCode : MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE)); }
From source file:org.eclipse.hono.adapter.mqtt.AbstractVertxBasedMqttProtocolAdapter.java
License:Open Source License
private Future<Device> handleEndpointConnectionWithAuthentication(final MqttEndpoint endpoint) { if (endpoint.auth() == null) { LOG.debug("connection request from device [clientId: {}] rejected: {}", endpoint.clientIdentifier(), "device did not provide credentials in CONNECT packet"); return rejected(MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD); } else {// w w w. jav a 2s. c o m final DeviceCredentials credentials = getCredentials(endpoint.auth()); if (credentials == null) { LOG.debug("connection request from device [clientId: {}] rejected: {}", endpoint.clientIdentifier(), "device provided malformed credentials in CONNECT packet"); return rejected(MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD); } else { return getTenantConfiguration(credentials.getTenantId()).compose(tenantConfig -> { if (tenantConfig.isAdapterEnabled(getTypeName())) { LOG.debug("protocol adapter [{}] is enabled for tenant [{}]", getTypeName(), credentials.getTenantId()); return Future.succeededFuture(tenantConfig); } else { LOG.debug("protocol adapter [{}] is disabled for tenant [{}]", getTypeName(), credentials.getTenantId()); return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN, "adapter disabled for tenant")); } }).compose(tenantConfig -> { final Future<Device> result = Future.future(); usernamePasswordAuthProvider.authenticate(credentials, result.completer()); return result; }).compose(authenticatedDevice -> { LOG.debug("successfully authenticated device [tenant-id: {}, auth-id: {}, device-id: {}]", authenticatedDevice.getTenantId(), credentials.getAuthId(), authenticatedDevice.getDeviceId()); return triggerLinkCreation(authenticatedDevice.getTenantId()).map(done -> { onAuthenticationSuccess(endpoint, authenticatedDevice); return null; }).compose(ok -> accepted(authenticatedDevice)); }).recover(t -> { LOG.debug("cannot establish connection with device [tenant-id: {}, auth-id: {}]", credentials.getTenantId(), credentials.getAuthId(), t); if (t instanceof ServerErrorException) { // one of the services we depend on might not be available (yet) return rejected(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE); } else { // validation of credentials has failed return rejected(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED); } }); } } }
From source file:org.eclipse.hono.adapter.mqtt.AbstractVertxBasedMqttProtocolAdapter.java
License:Open Source License
/** * Uploads a message to Hono Messaging.//from w ww . j av a 2s .c om * * @param ctx The context in which the MQTT message has been published. * @param resource The resource that the message should be uploaded to. * @param payload The message payload to send. * @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 context, resource or payload is {@code null}. * @throws IllegalArgumentException if the payload is empty. */ public final Future<Void> uploadMessage(final MqttContext ctx, final ResourceIdentifier resource, final Buffer payload) { Objects.requireNonNull(ctx); Objects.requireNonNull(resource); Objects.requireNonNull(payload); switch (EndpointType.fromString(resource.getEndpoint())) { case TELEMETRY: return uploadTelemetryMessage(ctx, resource.getTenantId(), resource.getResourceId(), payload); case EVENT: return uploadEventMessage(ctx, resource.getTenantId(), resource.getResourceId(), payload); default: return Future.failedFuture( new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "unsupported endpoint")); } }
From source file:org.eclipse.hono.adapter.mqtt.AbstractVertxBasedMqttProtocolAdapter.java
License:Open Source License
private Future<Void> uploadMessage(final MqttContext ctx, final String tenant, final String deviceId, final Buffer payload, final Future<MessageSender> senderTracker, final String endpointName) { if (!isPayloadOfIndicatedType(payload, ctx.contentType())) { return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, String.format("Content-Type %s does not match with the payload", ctx.contentType()))); } else {//w ww . ja v a2 s . co m final Future<JsonObject> tokenTracker = getRegistrationAssertion(tenant, deviceId, ctx.authenticatedDevice()); final Future<TenantObject> tenantConfigTracker = getTenantConfiguration(tenant); return CompositeFuture.all(tokenTracker, tenantConfigTracker, senderTracker).compose(ok -> { if (tenantConfigTracker.result().isAdapterEnabled(getTypeName())) { final MessageSender sender = senderTracker.result(); final Message downstreamMessage = newMessage( ResourceIdentifier.from(endpointName, tenant, deviceId), sender.isRegistrationAssertionRequired(), ctx.message().topicName(), ctx.contentType(), payload, tokenTracker.result(), null); customizeDownstreamMessage(downstreamMessage, ctx); if (ctx.message().qosLevel() == MqttQoS.AT_LEAST_ONCE) { return sender.sendAndWaitForOutcome(downstreamMessage); } else { return sender.send(downstreamMessage); } } else { // this adapter is not enabled for the tenant return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN)); } }).compose(delivery -> { LOG.trace( "successfully processed message [topic: {}, QoS: {}] for device [tenantId: {}, deviceId: {}]", ctx.message().topicName(), ctx.message().qosLevel(), tenant, deviceId); metrics.incrementProcessedMqttMessages(endpointName, tenant); onMessageSent(ctx); // 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()); } return Future.<Void>succeededFuture(); }).recover(t -> { if (ClientErrorException.class.isInstance(t)) { final ClientErrorException e = (ClientErrorException) t; LOG.debug( "cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]: {} - {}", tenant, deviceId, endpointName, e.getErrorCode(), e.getMessage()); } else { LOG.debug("cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]", tenant, deviceId, endpointName, t); metrics.incrementUndeliverableMqttMessages(endpointName, tenant); onMessageUndeliverable(ctx); } return Future.failedFuture(t); }); } }
From source file:org.eclipse.hono.adapter.mqtt.impl.VertxBasedMqttProtocolAdapter.java
License:Open Source License
/** * {@inheritDoc}/*w w w. j ava 2 s .c o m*/ */ @Override protected Future<Void> onPublishedMessage(final MqttContext ctx) { return mapTopic(ctx.message()).compose(address -> checkAddress(ctx, address)) .compose(address -> uploadMessage(ctx, address, ctx.message().payload())).recover(t -> { LOG.debug("discarding message [topic: {}] from device: {}", ctx.message().topicName(), t.getMessage()); return Future.failedFuture(t); }); }
From source file:org.eclipse.hono.adapter.mqtt.impl.VertxBasedMqttProtocolAdapter.java
License:Open Source License
Future<ResourceIdentifier> mapTopic(final MqttPublishMessage message) { try {//from w w w . ja va 2s.c o m final ResourceIdentifier topic = ResourceIdentifier.fromString(message.topicName()); switch (EndpointType.fromString(topic.getEndpoint())) { case TELEMETRY: if (MqttQoS.EXACTLY_ONCE.equals(message.qosLevel())) { // client tries to send telemetry message using QoS 2 return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "QoS 2 not supported for telemetry messages")); } else { return Future.succeededFuture(topic); } case EVENT: if (!MqttQoS.AT_LEAST_ONCE.equals(message.qosLevel())) { // client tries to send event message using QoS 0 or 2 return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "Only QoS 1 supported for event messages")); } else { return Future.succeededFuture(topic); } default: // MQTT client is trying to publish on a not supported endpoint LOG.debug("no such endpoint [{}]", topic.getEndpoint()); return Future.failedFuture( new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "no such endpoint")); } } catch (final IllegalArgumentException e) { return Future.failedFuture( new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "malformed topic name")); } }