Search in sources :

Example 1 with Json

use of io.vertx.core.json.Json in project mod-inventory-storage by folio-org.

the class LocationsTest method send.

// /////////////////////////// helpers
private static void send(URL url, HttpMethod method, String content, String contentType, Handler<HttpClientResponse> handler) {
    HttpClient client = StorageTestSuite.getVertx().createHttpClient();
    HttpClientRequest request;
    if (content == null) {
        content = "";
    }
    Buffer buffer = Buffer.buffer(content);
    if (method == HttpMethod.POST) {
        request = client.postAbs(url.toString());
    } else if (method == HttpMethod.DELETE) {
        request = client.deleteAbs(url.toString());
    } else if (method == HttpMethod.GET) {
        request = client.getAbs(url.toString());
    } else {
        request = client.putAbs(url.toString());
    }
    request.exceptionHandler(error -> {
        Assert.fail(error.getLocalizedMessage());
    }).handler(handler);
    request.putHeader("Authorization", "test_tenant");
    request.putHeader("x-okapi-tenant", "test_tenant");
    request.putHeader("Accept", "application/json,text/plain");
    request.putHeader("Content-type", contentType);
    request.end(buffer);
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ResponseHandler(org.folio.rest.support.ResponseHandler) HttpURLConnection(java.net.HttpURLConnection) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Json(io.vertx.core.json.Json) Response(org.folio.rest.support.Response) URL(java.net.URL) MaterialTypesClient(org.folio.rest.support.client.MaterialTypesClient) TimeoutException(java.util.concurrent.TimeoutException) AdditionalHttpStatusCodes(org.folio.rest.support.AdditionalHttpStatusCodes) CompletableFuture(java.util.concurrent.CompletableFuture) HttpResponseMatchers.statusCodeIs(org.folio.rest.support.HttpResponseMatchers.statusCodeIs) LoggerFactory(io.vertx.core.logging.LoggerFactory) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) Assert.assertThat(org.junit.Assert.assertThat) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) JsonObject(io.vertx.core.json.JsonObject) Logger(io.vertx.core.logging.Logger) Before(org.junit.Before) InterfaceUrls(org.folio.rest.support.http.InterfaceUrls) MalformedURLException(java.net.MalformedURLException) Test(org.junit.Test) UUID(java.util.UUID) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Buffer(io.vertx.core.buffer.Buffer) HttpMethod(io.vertx.core.http.HttpMethod) Handler(io.vertx.core.Handler) Assert(org.junit.Assert) HttpClient(io.vertx.core.http.HttpClient) LoanTypesClient(org.folio.rest.support.client.LoanTypesClient) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClient(io.vertx.core.http.HttpClient)

Example 2 with Json

use of io.vertx.core.json.Json in project raml-module-builder by folio-org.

the class DemoRamlRestTest method testStream.

private void testStream(TestContext context, boolean chunked) {
    int chunkSize = 1024;
    int numberChunks = 50;
    Async async = context.async();
    vertx.createHttpClient().request(HttpMethod.POST, port, "localhost", "/rmbtests/testStream").onComplete(context.asyncAssertSuccess(request -> {
        request.response().onComplete(context.asyncAssertSuccess(response -> {
            assertThat(response.statusCode(), is(200));
            response.body(context.asyncAssertSuccess(body -> {
                assertThat(body.toJsonObject().getBoolean("complete"), is(true));
                async.complete();
            }));
        }));
        if (chunked) {
            request.setChunked(true);
        } else {
            request.putHeader("Content-Length", Integer.toString(chunkSize * numberChunks));
        }
        request.putHeader("Accept", "application/json,text/plain");
        request.putHeader("Content-type", "application/octet-stream");
        request.putHeader("x-okapi-tenant", TENANT);
        String chunk = "X".repeat(chunkSize);
        for (int i = 0; i < numberChunks; i++) {
            request.write(chunk);
        }
        request.end(context.asyncAssertSuccess());
    }));
}
Also used : TestContext(io.vertx.ext.unit.TestContext) CoreMatchers(org.hamcrest.CoreMatchers) Async(io.vertx.ext.unit.Async) Json(io.vertx.core.json.Json) HttpResponse(io.vertx.ext.web.client.HttpResponse) RequestSpecBuilder(io.restassured.builder.RequestSpecBuilder) RestVerticle(org.folio.rest.RestVerticle) BeforeClass(org.junit.BeforeClass) WebClient(io.vertx.ext.web.client.WebClient) Date(java.util.Date) PostgresTesterContainer(org.folio.postgres.testing.PostgresTesterContainer) RunWith(org.junit.runner.RunWith) Timeout(io.vertx.ext.unit.junit.Timeout) VertxUtils(org.folio.rest.tools.utils.VertxUtils) TenantClient(org.folio.rest.client.TenantClient) RequestSpecification(io.restassured.specification.RequestSpecification) JsonObject(io.vertx.core.json.JsonObject) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) AsyncResult(io.vertx.core.AsyncResult) Datetime(org.folio.rest.jaxrs.model.Datetime) Metadata(org.folio.rest.jaxrs.model.Metadata) NetClient(io.vertx.core.net.NetClient) AfterClass(org.junit.AfterClass) AdminLoglevelPutLevel(org.folio.rest.jaxrs.model.AdminLoglevelPutLevel) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) JsonPathParser(org.folio.rest.tools.parser.JsonPathParser) Data(org.folio.rest.jaxrs.model.Data) NetworkUtils(org.folio.rest.tools.utils.NetworkUtils) PostgresClient(org.folio.rest.persist.PostgresClient) HttpRequest(io.vertx.ext.web.client.HttpRequest) Book(org.folio.rest.jaxrs.model.Book) Logger(org.apache.logging.log4j.Logger) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) AdminClient(org.folio.rest.client.AdminClient) HttpMethod(io.vertx.core.http.HttpMethod) TenantAttributes(org.folio.rest.jaxrs.model.TenantAttributes) RestAssured.given(io.restassured.RestAssured.given) Books(org.folio.rest.jaxrs.model.Books) RestAssured(io.restassured.RestAssured) LogManager(org.apache.logging.log4j.LogManager) TenantInit(org.folio.rest.tools.utils.TenantInit) NetSocket(io.vertx.core.net.NetSocket) Async(io.vertx.ext.unit.Async)

Example 3 with Json

use of io.vertx.core.json.Json in project hono by eclipse.

the class ProtonBasedCredentialsClient method get.

@Override
public Future<CredentialsObject> get(final String tenantId, final String type, final String authId, final JsonObject clientContext, final SpanContext spanContext) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(type);
    Objects.requireNonNull(authId);
    Objects.requireNonNull(clientContext);
    final int clientContextHashCode;
    if (clientContext.isEmpty()) {
        clientContextHashCode = clientContext.hashCode();
    } else {
        // "normalize" JSON so that binary valued properties always
        // contain the value's Base64 encoding instead of the raw byte array
        // and thus always result in the same hash code
        clientContextHashCode = new JsonObject(clientContext.encode()).hashCode();
    }
    final AnnotatedCacheKey<CacheKey> responseCacheKey = new AnnotatedCacheKey<>(new CacheKey(tenantId, type, authId, clientContextHashCode));
    final Span span = newChildSpan(spanContext, "get Credentials");
    span.setTag(MessageHelper.APP_PROPERTY_TENANT_ID, tenantId);
    span.setTag(TAG_CREDENTIALS_TYPE, type);
    span.setTag(TAG_AUTH_ID, authId);
    final Future<CredentialsResult<CredentialsObject>> resultTracker = getResponseFromCache(responseCacheKey, span).recover(cacheMiss -> getOrCreateClient(tenantId).compose(client -> {
        final JsonObject specification = CredentialsConstants.getSearchCriteria(type, authId).mergeIn(clientContext);
        if (LOG.isTraceEnabled()) {
            LOG.trace("getting credentials using spec:{}{}", System.lineSeparator(), specification.encodePrettily());
        }
        return client.createAndSendRequest(CredentialsConstants.CredentialsAction.get.toString(), null, specification.toBuffer(), RequestResponseApiConstants.CONTENT_TYPE_APPLICATION_JSON, this::getRequestResponseResult, span);
    }).map(credentialsResult -> {
        addResultToCache(responseCacheKey, credentialsResult);
        return credentialsResult;
    }));
    return mapResultAndFinishSpan(resultTracker, result -> {
        switch(result.getStatus()) {
            case HttpURLConnection.HTTP_OK:
            case HttpURLConnection.HTTP_CREATED:
                return result.getPayload();
            case HttpURLConnection.HTTP_NOT_FOUND:
                throw new ClientErrorException(result.getStatus(), "no such credentials");
            default:
                throw StatusCodeMapper.from(result);
        }
    }, span);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) CacheDirective(org.eclipse.hono.util.CacheDirective) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) Json(io.vertx.core.json.Json) DecodeException(io.vertx.core.json.DecodeException) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) LoggerFactory(org.slf4j.LoggerFactory) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Cache(com.github.benmanes.caffeine.cache.Cache) Constants(org.eclipse.hono.util.Constants) StatusCodeMapper(org.eclipse.hono.client.StatusCodeMapper) CredentialsClient(org.eclipse.hono.client.registry.CredentialsClient) JsonObject(io.vertx.core.json.JsonObject) HonoConnection(org.eclipse.hono.client.HonoConnection) AbstractRequestResponseServiceClient(org.eclipse.hono.client.amqp.AbstractRequestResponseServiceClient) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) CredentialsChangeNotification(org.eclipse.hono.notification.deviceregistry.CredentialsChangeNotification) Logger(org.slf4j.Logger) CredentialsResult(org.eclipse.hono.util.CredentialsResult) RequestResponseClient(org.eclipse.hono.client.amqp.RequestResponseClient) CachingClientFactory(org.eclipse.hono.client.impl.CachingClientFactory) MessageHelper(org.eclipse.hono.util.MessageHelper) RequestResponseApiConstants(org.eclipse.hono.util.RequestResponseApiConstants) Future(io.vertx.core.Future) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) ApplicationProperties(org.apache.qpid.proton.amqp.messaging.ApplicationProperties) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) AnnotatedCacheKey(org.eclipse.hono.client.util.AnnotatedCacheKey) Buffer(io.vertx.core.buffer.Buffer) Span(io.opentracing.Span) SendMessageSampler(org.eclipse.hono.client.SendMessageSampler) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) CredentialsObject(org.eclipse.hono.util.CredentialsObject) JsonObject(io.vertx.core.json.JsonObject) CredentialsResult(org.eclipse.hono.util.CredentialsResult) ClientErrorException(org.eclipse.hono.client.ClientErrorException) AnnotatedCacheKey(org.eclipse.hono.client.util.AnnotatedCacheKey) Span(io.opentracing.Span) AnnotatedCacheKey(org.eclipse.hono.client.util.AnnotatedCacheKey)

Example 4 with Json

use of io.vertx.core.json.Json in project gravitee-gateway by gravitee-io.

the class ApisHandler method handle.

@Override
public void handle(RoutingContext ctx) {
    HttpServerResponse response = ctx.response();
    response.setStatusCode(HttpStatusCode.OK_200);
    response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    response.setChunked(true);
    try {
        Collection<ListApiEntity> apis = apiManager.apis().stream().map(api -> {
            ListApiEntity entity = new ListApiEntity();
            entity.setId(api.getId());
            entity.setName(api.getName());
            entity.setVersion(api.getVersion());
            return entity;
        }).collect(Collectors.toList());
        Json.prettyMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        response.write(Json.prettyMapper.writeValueAsString(apis));
    } catch (JsonProcessingException jpe) {
        response.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500);
        LOGGER.error("Unable to transform data object to JSON", jpe);
    }
    response.end();
}
Also used : Json(io.vertx.core.json.Json) HttpHeaders(io.gravitee.common.http.HttpHeaders) Logger(org.slf4j.Logger) Collection(java.util.Collection) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ApiManager(io.gravitee.gateway.handlers.api.manager.ApiManager) RoutingContext(io.vertx.ext.web.RoutingContext) Collectors(java.util.stream.Collectors) HttpStatusCode(io.gravitee.common.http.HttpStatusCode) MediaType(io.gravitee.common.http.MediaType) HttpServerResponse(io.vertx.core.http.HttpServerResponse) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) Handler(io.vertx.core.Handler) HttpServerResponse(io.vertx.core.http.HttpServerResponse) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

Json (io.vertx.core.json.Json)4 Buffer (io.vertx.core.buffer.Buffer)3 JsonObject (io.vertx.core.json.JsonObject)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 Handler (io.vertx.core.Handler)2 HttpMethod (io.vertx.core.http.HttpMethod)2 HttpURLConnection (java.net.HttpURLConnection)2 Test (org.junit.Test)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 JsonInclude (com.fasterxml.jackson.annotation.JsonInclude)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Cache (com.github.benmanes.caffeine.cache.Cache)1 HttpHeaders (io.gravitee.common.http.HttpHeaders)1 HttpStatusCode (io.gravitee.common.http.HttpStatusCode)1 MediaType (io.gravitee.common.http.MediaType)1 ApiManager (io.gravitee.gateway.handlers.api.manager.ApiManager)1 Span (io.opentracing.Span)1 SpanContext (io.opentracing.SpanContext)1 RestAssured (io.restassured.RestAssured)1