Search in sources :

Example 91 with AsyncResult

use of io.vertx.core.AsyncResult in project hono by eclipse.

the class ForwardingDownstreamAdapter method onClientAttach.

@Override
public final void onClientAttach(final UpstreamReceiver client, final Handler<AsyncResult<Void>> resultHandler) {
    if (!running) {
        throw new IllegalStateException("adapter must be started first");
    }
    Objects.requireNonNull(client);
    Objects.requireNonNull(resultHandler);
    ProtonSender sender = activeSenders.get(client);
    if (sender != null && sender.isOpen()) {
        logger.info("reusing existing downstream sender [con: {}, link: {}]", client.getConnectionId(), client.getLinkId());
        resultHandler.handle(Future.succeededFuture());
    } else {
        removeSender(client);
        // register the result handler to be failed if the connection to the downstream container fails during
        // the attempt to create a downstream sender
        clientAttachHandlers.add(resultHandler);
        Future<Void> tracker = Future.future();
        tracker.setHandler(attempt -> {
            if (attempt.succeeded()) {
                logger.info("created downstream sender [con: {}, link: {}]", client.getConnectionId(), client.getLinkId());
            } else {
                logger.warn("can't create downstream sender [con: {}, link: {}]: {}", client.getConnectionId(), client.getLinkId(), attempt.cause().getMessage());
            }
            clientAttachHandlers.remove(resultHandler);
            resultHandler.handle(attempt);
        });
        final ResourceIdentifier targetAddress = ResourceIdentifier.fromString(client.getTargetAddress());
        createSender(targetAddress, replenishedSender -> handleFlow(replenishedSender, client), closeHook -> {
            removeSender(client);
            closeReceiver(client);
        }).compose(createdSender -> {
            addSender(client, createdSender);
            tracker.complete();
        }, tracker);
    }
}
Also used : ProtonConnection(io.vertx.proton.ProtonConnection) ProtonDelivery(io.vertx.proton.ProtonDelivery) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) Constants(org.eclipse.hono.util.Constants) ArrayList(java.util.ArrayList) ConnectionFactory(org.eclipse.hono.connection.ConnectionFactory) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Map(java.util.Map) Qualifier(org.springframework.beans.factory.annotation.Qualifier) Message(org.apache.qpid.proton.message.Message) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) AsyncResult(io.vertx.core.AsyncResult) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Vertx(io.vertx.core.Vertx) ProtonHelper(io.vertx.proton.ProtonHelper) ProtonQoS(io.vertx.proton.ProtonQoS) Future(io.vertx.core.Future) Objects(java.util.Objects) List(java.util.List) Component(org.springframework.stereotype.Component) ProtonSender(io.vertx.proton.ProtonSender) Handler(io.vertx.core.Handler) ProtonSender(io.vertx.proton.ProtonSender) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier)

Example 92 with AsyncResult

use of io.vertx.core.AsyncResult in project hono by eclipse.

the class CredentialsApiAuthProvider method authenticate.

@Override
public final void authenticate(final DeviceCredentials deviceCredentials, final Handler<AsyncResult<Device>> resultHandler) {
    Objects.requireNonNull(deviceCredentials);
    Objects.requireNonNull(resultHandler);
    Future<Device> validationResult = Future.future();
    validationResult.setHandler(resultHandler);
    getCredentialsForDevice(deviceCredentials).recover(t -> {
        final ServiceInvocationException e = (ServiceInvocationException) t;
        if (e.getErrorCode() == HttpURLConnection.HTTP_NOT_FOUND) {
            return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "bad credentials"));
        } else {
            return Future.failedFuture(t);
        }
    }).map(credentialsOnRecord -> {
        if (deviceCredentials.validate(credentialsOnRecord)) {
            return new Device(deviceCredentials.getTenantId(), credentialsOnRecord.getDeviceId());
        } else {
            throw new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "invalid credentials");
        }
    }).setHandler(resultHandler);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ProtonConnection(io.vertx.proton.ProtonConnection) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) Vertx(io.vertx.core.Vertx) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Autowired(org.springframework.beans.factory.annotation.Autowired) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Constants(org.eclipse.hono.util.Constants) Future(io.vertx.core.Future) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) Objects(java.util.Objects) Status(io.vertx.ext.healthchecks.Status) CredentialsClient(org.eclipse.hono.client.CredentialsClient) User(io.vertx.ext.auth.User) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) Qualifier(org.springframework.beans.factory.annotation.Qualifier) Optional(java.util.Optional) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) HonoClient(org.eclipse.hono.client.HonoClient) CredentialsObject(org.eclipse.hono.util.CredentialsObject) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException)

Example 93 with AsyncResult

use of io.vertx.core.AsyncResult in project vertx-web by vert-x3.

the class OpenAPI3ParametersUnitTest method testPathLabelExplodeArray.

/**
 * Test: path_label_explode_array
 * Expected parameters sent:
 * color: .blue.black.brown
 * Expected response: {"color":["blue","black","brown"]}
 * @throws Exception
 */
@Test
public void testPathLabelExplodeArray() throws Exception {
    routerFactory.addHandlerByOperationId("path_label_explode_array", routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        JsonObject res = new JsonObject();
        RequestParameter color_path = params.pathParameter("color");
        assertNotNull(color_path);
        assertTrue(color_path.isArray());
        res.put("color", new JsonArray(color_path.getArray().stream().map(param -> param.getString()).collect(Collectors.toList())));
        routingContext.response().setStatusCode(200).setStatusMessage("OK").putHeader("content-type", "application/json; charset=utf-8").end(res.encode());
    });
    CountDownLatch latch = new CountDownLatch(1);
    List<Object> color_path;
    color_path = new ArrayList<>();
    color_path.add("blue");
    color_path.add("black");
    color_path.add("brown");
    startServer();
    apiClient.pathLabelExplodeArray(color_path, (AsyncResult<HttpResponse> ar) -> {
        if (ar.succeeded()) {
            assertEquals(200, ar.result().statusCode());
            assertTrue("Expected: " + new JsonObject("{\"color\":[\"blue\",\"black\",\"brown\"]}").encode() + " Actual: " + ar.result().bodyAsJsonObject().encode(), new JsonObject("{\"color\":[\"blue\",\"black\",\"brown\"]}").equals(ar.result().bodyAsJsonObject()));
        } else {
            assertTrue(ar.cause().getMessage(), false);
        }
        latch.countDown();
    });
    awaitLatch(latch);
}
Also used : JsonArray(io.vertx.core.json.JsonArray) HttpResponse(io.vertx.ext.web.client.HttpResponse) HashMap(java.util.HashMap) RoutingContext(io.vertx.ext.web.RoutingContext) OpenAPI3RouterFactoryImpl(io.vertx.ext.web.api.contract.openapi3.impl.OpenAPI3RouterFactoryImpl) ArrayList(java.util.ArrayList) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) RequestParameters(io.vertx.ext.web.api.RequestParameters) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Files(java.nio.file.Files) RequestParameter(io.vertx.ext.web.api.RequestParameter) Test(org.junit.Test) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) RouterFactoryOptions(io.vertx.ext.web.api.contract.RouterFactoryOptions) WebTestValidationBase(io.vertx.ext.web.api.validation.WebTestValidationBase) ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) JsonArray(io.vertx.core.json.JsonArray) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Rule(org.junit.Rule) ExternalResource(org.junit.rules.ExternalResource) Paths(java.nio.file.Paths) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Handler(io.vertx.core.Handler) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) RequestParameter(io.vertx.ext.web.api.RequestParameter) JsonObject(io.vertx.core.json.JsonObject) JsonObject(io.vertx.core.json.JsonObject) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncResult(io.vertx.core.AsyncResult) RequestParameters(io.vertx.ext.web.api.RequestParameters) Test(org.junit.Test)

Example 94 with AsyncResult

use of io.vertx.core.AsyncResult in project vertx-web by vert-x3.

the class OpenAPI3ParametersUnitTest method testPathSimpleNoexplodeArray.

/**
 * Test: path_simple_noexplode_array
 * Expected parameters sent:
 * color: blue,black,brown
 * Expected response: {"color":["blue","black","brown"]}
 * @throws Exception
 */
@Test
public void testPathSimpleNoexplodeArray() throws Exception {
    routerFactory.addHandlerByOperationId("path_simple_noexplode_array", routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        JsonObject res = new JsonObject();
        RequestParameter color_path = params.pathParameter("color");
        assertNotNull(color_path);
        assertTrue(color_path.isArray());
        res.put("color", new JsonArray(color_path.getArray().stream().map(param -> param.getString()).collect(Collectors.toList())));
        routingContext.response().setStatusCode(200).setStatusMessage("OK").putHeader("content-type", "application/json; charset=utf-8").end(res.encode());
    });
    CountDownLatch latch = new CountDownLatch(1);
    List<Object> color_path;
    color_path = new ArrayList<>();
    color_path.add("blue");
    color_path.add("black");
    color_path.add("brown");
    startServer();
    apiClient.pathSimpleNoexplodeArray(color_path, (AsyncResult<HttpResponse> ar) -> {
        if (ar.succeeded()) {
            assertEquals(200, ar.result().statusCode());
            assertTrue("Expected: " + new JsonObject("{\"color\":[\"blue\",\"black\",\"brown\"]}").encode() + " Actual: " + ar.result().bodyAsJsonObject().encode(), new JsonObject("{\"color\":[\"blue\",\"black\",\"brown\"]}").equals(ar.result().bodyAsJsonObject()));
        } else {
            assertTrue(ar.cause().getMessage(), false);
        }
        latch.countDown();
    });
    awaitLatch(latch);
}
Also used : JsonArray(io.vertx.core.json.JsonArray) HttpResponse(io.vertx.ext.web.client.HttpResponse) HashMap(java.util.HashMap) RoutingContext(io.vertx.ext.web.RoutingContext) OpenAPI3RouterFactoryImpl(io.vertx.ext.web.api.contract.openapi3.impl.OpenAPI3RouterFactoryImpl) ArrayList(java.util.ArrayList) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) RequestParameters(io.vertx.ext.web.api.RequestParameters) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Files(java.nio.file.Files) RequestParameter(io.vertx.ext.web.api.RequestParameter) Test(org.junit.Test) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) RouterFactoryOptions(io.vertx.ext.web.api.contract.RouterFactoryOptions) WebTestValidationBase(io.vertx.ext.web.api.validation.WebTestValidationBase) ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) JsonArray(io.vertx.core.json.JsonArray) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Rule(org.junit.Rule) ExternalResource(org.junit.rules.ExternalResource) Paths(java.nio.file.Paths) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Handler(io.vertx.core.Handler) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) RequestParameter(io.vertx.ext.web.api.RequestParameter) JsonObject(io.vertx.core.json.JsonObject) JsonObject(io.vertx.core.json.JsonObject) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncResult(io.vertx.core.AsyncResult) RequestParameters(io.vertx.ext.web.api.RequestParameters) Test(org.junit.Test)

Example 95 with AsyncResult

use of io.vertx.core.AsyncResult in project vertx-web by vert-x3.

the class OpenAPI3ParametersUnitTest method testPathLabelNoexplodeObject.

/**
 * Test: path_label_noexplode_object
 * Expected parameters sent:
 * color: .R.100.G.200.B.150
 * Expected response: {"color":{"R":"100","G":"200","B":"150"}}
 * @throws Exception
 */
@Test
public void testPathLabelNoexplodeObject() throws Exception {
    routerFactory.addHandlerByOperationId("path_label_noexplode_object", routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        JsonObject res = new JsonObject();
        RequestParameter color_path = params.pathParameter("color");
        assertNotNull(color_path);
        assertTrue(color_path.isObject());
        Map<String, String> map = new HashMap<>();
        for (String key : color_path.getObjectKeys()) map.put(key, color_path.getObjectValue(key).getString());
        res.put("color", map);
        routingContext.response().setStatusCode(200).setStatusMessage("OK").putHeader("content-type", "application/json; charset=utf-8").end(res.encode());
    });
    CountDownLatch latch = new CountDownLatch(1);
    Map<String, Object> color_path;
    color_path = new HashMap<>();
    color_path.put("R", "100");
    color_path.put("G", "200");
    color_path.put("B", "150");
    startServer();
    apiClient.pathLabelNoexplodeObject(color_path, (AsyncResult<HttpResponse> ar) -> {
        if (ar.succeeded()) {
            assertEquals(200, ar.result().statusCode());
            assertTrue("Expected: " + new JsonObject("{\"color\":{\"R\":\"100\",\"G\":\"200\",\"B\":\"150\"}}").encode() + " Actual: " + ar.result().bodyAsJsonObject().encode(), new JsonObject("{\"color\":{\"R\":\"100\",\"G\":\"200\",\"B\":\"150\"}}").equals(ar.result().bodyAsJsonObject()));
        } else {
            assertTrue(ar.cause().getMessage(), false);
        }
        latch.countDown();
    });
    awaitLatch(latch);
}
Also used : HashMap(java.util.HashMap) RequestParameter(io.vertx.ext.web.api.RequestParameter) JsonObject(io.vertx.core.json.JsonObject) JsonObject(io.vertx.core.json.JsonObject) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncResult(io.vertx.core.AsyncResult) RequestParameters(io.vertx.ext.web.api.RequestParameters) Test(org.junit.Test)

Aggregations

AsyncResult (io.vertx.core.AsyncResult)162 Handler (io.vertx.core.Handler)106 Test (org.junit.Test)72 JsonObject (io.vertx.core.json.JsonObject)68 CountDownLatch (java.util.concurrent.CountDownLatch)62 Future (io.vertx.core.Future)59 List (java.util.List)49 RequestParameter (io.vertx.ext.web.api.RequestParameter)48 RequestParameters (io.vertx.ext.web.api.RequestParameters)48 HashMap (java.util.HashMap)45 Map (java.util.Map)42 IOException (java.io.IOException)41 ArrayList (java.util.ArrayList)40 Vertx (io.vertx.core.Vertx)35 Collectors (java.util.stream.Collectors)35 RoutingContext (io.vertx.ext.web.RoutingContext)28 Buffer (io.vertx.core.buffer.Buffer)24 StandardCharsets (java.nio.charset.StandardCharsets)23 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)23 Consumer (java.util.function.Consumer)23