Example usage for io.vertx.core.json JsonObject mapFrom

List of usage examples for io.vertx.core.json JsonObject mapFrom

Introduction

In this page you can find the example usage for io.vertx.core.json JsonObject mapFrom.

Prototype

@SuppressWarnings("unchecked")
public static JsonObject mapFrom(Object obj) 

Source Link

Document

Create a JsonObject from the fields of a Java object.

Usage

From source file:docoverride.json.Examples.java

License:Open Source License

public void mapFromPojo(HttpServerRequest request) {
    User user = new User("Dale", "Cooper");
    JsonObject jsonObject = JsonObject.mapFrom(user);
}

From source file:io.gravitee.am.gateway.handler.vertx.auth.user.User.java

License:Apache License

public User(io.gravitee.am.model.User user) {
    this.user = user;
    this.principal = JsonObject.mapFrom(user);
}

From source file:io.gravitee.reporter.kafka.KafkaReporter.java

License:Apache License

@Override
public void report(Reportable reportable) {
    if (kafkaProducer != null) {
        KafkaProducerRecord<String, JsonObject> record = KafkaProducerRecord
                .create(kafkaConfiguration.getKafkaTopic(), JsonObject.mapFrom(reportable));
        kafkaProducer.write(record, done -> {
            String message;/*from  w w w .ja v  a  2 s  .  com*/
            if (done.succeeded()) {
                RecordMetadata recordMetadata = done.result();
                message = String.format("Topic=%s partition=%s offset=%s message %s", record.value(),
                        recordMetadata.getTopic(), recordMetadata.getPartition(), recordMetadata.getOffset());
            } else {
                message = String.format("Message %s not written on topic=%s", record.value(),
                        kafkaConfiguration.getKafkaTopic());
            }
            LOGGER.info(message);
        });
    }
}

From source file:io.nitor.api.backend.lambda.LambdaHandler.java

License:Apache License

@Override
public void handle(RoutingContext ctx) {
    HttpServerRequest sreq = ctx.request();
    final String path = normalizePath(sreq.path(), routeLength);
    if (path == null) {
        ctx.response().setStatusCode(NOT_FOUND.code()).end();
        return;/*from  ww  w  . j  a v  a 2s  .com*/
    }
    HttpServerResponse sres = ctx.response();
    PathMatchResult<Entry<String, String>> matchRes = pathTemplateMatcher.match(path);
    final String lambdaFunction, qualifier;
    if (matchRes == null) {
        logger.error("No matching path template");
        sres.setStatusCode(BAD_GATEWAY.code());
        return;
    } else {
        lambdaFunction = matchRes.getValue().getKey();
        qualifier = matchRes.getValue().getValue();
    }
    sreq.bodyHandler(new Handler<Buffer>() {
        @Override
        public void handle(Buffer event) {
            byte[] body = event.getBytes();
            APIGatewayProxyRequestEvent reqObj = new APIGatewayProxyRequestEvent();
            /*
            * Handle body
            */
            String bodyObjStr = null;
            boolean isBase64Encoded = true;
            if (body != null && body.length > 0) {
                String ct = sreq.getHeader("content-type").toLowerCase();
                if (ct.startsWith("text/") || ct.startsWith("application/json")
                        || (ct.indexOf("charset=") > 0)) {
                    String charset = "utf-8";
                    if (ct.indexOf("charset=") > 0) {
                        charset = getCharsetFromContentType(ct);
                    }
                    try {
                        bodyObjStr = Charset.forName(charset).newDecoder()
                                .onMalformedInput(CodingErrorAction.REPORT)
                                .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(body))
                                .toString();
                        isBase64Encoded = false;
                    } catch (CharacterCodingException e) {
                        logger.error("Decoding body failed", e);
                    }
                }
                if (bodyObjStr == null) {
                    bodyObjStr = Base64.getEncoder().encodeToString(body);
                }
                reqObj = reqObj.withBody(bodyObjStr).withIsBase64Encoded(isBase64Encoded);
            }
            Map<String, List<String>> headerMultivalue = sreq.headers().entries().stream()
                    .collect(toMap(Entry::getKey, x -> sreq.headers().getAll(x.getKey())));
            Map<String, String> headerValue = sreq.headers().entries().stream()
                    .collect(toMap(Entry::getKey, Entry::getValue));

            /*
            * Handle request context
            */
            RequestIdentity reqId = new RequestIdentity().withSourceIp(getRemoteAddress(ctx))
                    .withUserAgent(sreq.getHeader(USER_AGENT));
            if (ctx.user() != null) {
                reqId.withUser(ctx.user().principal().toString());
            }
            ProxyRequestContext reqCtx = new ProxyRequestContext()
                    .withPath(sreq.path().substring(0, routeLength)).withHttpMethod(sreq.method().toString())
                    .withIdentity(reqId);
            reqObj = reqObj.withMultiValueHeaders(headerMultivalue).withHeaders(headerValue)
                    .withHttpMethod(sreq.method().toString()).withPath(sreq.path()).withResource(path)
                    .withQueryStringParameters(splitQuery(sreq.query()))
                    .withMultiValueQueryStringParameters(splitMultiValueQuery(sreq.query()))
                    .withPathParameters(matchRes.getParameters()).withRequestContext(reqCtx);
            String reqStr = JsonObject.mapFrom(reqObj).toString();
            byte[] sendBody = reqStr.getBytes(UTF_8);
            InvokeRequest req = InvokeRequest.builder().invocationType(InvocationType.REQUEST_RESPONSE)
                    .functionName(lambdaFunction).qualifier(qualifier).payload(SdkBytes.fromByteArray(sendBody))
                    .build();
            logger.info("Calling lambda " + lambdaFunction + ":" + qualifier);
            logger.debug("Payload: " + reqStr);
            CompletableFuture<InvokeResponse> respFuture = lambdaCl.invoke(req);
            respFuture.whenComplete((iresp, err) -> {
                if (iresp != null) {
                    try {
                        String payload = iresp.payload().asString(UTF_8);
                        JsonObject resp = new JsonObject(payload);
                        int statusCode = resp.getInteger("statusCode");
                        sres.setStatusCode(statusCode);
                        for (Entry<String, Object> next : resp.getJsonObject("headers").getMap().entrySet()) {
                            sres.putHeader(next.getKey(), next.getValue().toString());
                        }
                        String respBody = resp.getString("body");
                        byte[] bodyArr = new byte[0];
                        if (body != null && !respBody.isEmpty()) {
                            if (TRUE.equals(resp.getBoolean("isBase64Encoded"))) {
                                bodyArr = Base64.getDecoder().decode(body);
                            } else {
                                bodyArr = respBody.getBytes(UTF_8);
                            }
                        }
                        sres.putHeader(CONTENT_LENGTH, String.valueOf(bodyArr.length));
                        Buffer buffer = Buffer.buffer(bodyArr);
                        tryToCacheContent(ctx, buffer);
                        sres.write(buffer);
                    } catch (Throwable t) {
                        logger.error("Error processing lambda request", t);
                        if (!sres.headWritten()) {
                            sres.setStatusCode(BAD_GATEWAY.code());
                            sres.putHeader(CONTENT_TYPE, "application/json");
                            Buffer response = Buffer.buffer(new LambdaErrorResponse(t).toString());
                            sres.putHeader(CONTENT_LENGTH, String.valueOf(response.length()));
                            sres.write(response);
                        }
                    } finally {
                        sres.end();
                    }
                } else {
                    logger.error("Error processing lambda request", err);
                    sres.setStatusCode(BAD_GATEWAY.code());
                    sres.putHeader(CONTENT_TYPE, "application/json");
                    Buffer response = Buffer.buffer(new LambdaErrorResponse(err).toString());
                    sres.putHeader(CONTENT_LENGTH, String.valueOf(response.length()));
                    sres.end(response);
                }
            });
        }
    });
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

License:Open Source License

Future<Void> saveToFile() {

    if (!getConfig().isSaveToFile()) {
        return Future.succeededFuture();
    } else if (dirty) {
        return checkFileExists(true).compose(s -> {

            final JsonArray tenantsJson = new JsonArray();
            tenants.values().stream().forEach(tenant -> {
                tenantsJson.add(JsonObject.mapFrom(tenant));
            });//  ww  w. j a va  2s  .  co m

            final Future<Void> writeHandler = Future.future();
            vertx.fileSystem().writeFile(getConfig().getFilename(),
                    Buffer.factory.buffer(tenantsJson.encodePrettily()), writeHandler.completer());
            return writeHandler.map(ok -> {
                dirty = false;
                log.trace("successfully wrote {} tenants to file {}", tenantsJson.size(),
                        getConfig().getFilename());
                return (Void) null;
            }).otherwise(t -> {
                log.warn("could not write tenants to file {}", getConfig().getFilename(), t);
                return (Void) null;
            });
        });
    } else {
        log.trace("tenants registry does not need to be persisted");
        return Future.succeededFuture();
    }
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

License:Open Source License

TenantResult<JsonObject> getTenantResult(final String tenantId) {

    final TenantObject tenant = tenants.get(tenantId);

    if (tenant == null) {
        return TenantResult.from(HttpURLConnection.HTTP_NOT_FOUND);
    } else {/*w  w w. j  ava2  s .c om*/
        return TenantResult.from(HttpURLConnection.HTTP_OK, JsonObject.mapFrom(tenant),
                CacheDirective.maxAgeDirective(MAX_AGE_GET_TENANT));
    }
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

License:Open Source License

private TenantResult<JsonObject> getForCertificateAuthority(final X500Principal subjectDn) {

    if (subjectDn == null) {
        return TenantResult.from(HttpURLConnection.HTTP_BAD_REQUEST);
    } else {/*from w  w w .  j a  v  a 2  s. c om*/
        final TenantObject tenant = getByCa(subjectDn);

        if (tenant == null) {
            return TenantResult.from(HttpURLConnection.HTTP_NOT_FOUND);
        } else {
            return TenantResult.from(HttpURLConnection.HTTP_OK, JsonObject.mapFrom(tenant),
                    CacheDirective.maxAgeDirective(MAX_AGE_GET_TENANT));
        }
    }
}

From source file:org.eclipse.hono.tests.DeviceRegistryHttpClient.java

License:Open Source License

/**
 * Creates a tenant and adds a device to it with a given password.
 * <p>//  w ww.j  a v  a  2 s  . c o m
 * The password will be added as a <em>sha-512</em> hashed password
 * using the device identifier as the authentication identifier.
 * 
 * @param tenant The tenant to create.
 * @param deviceId The identifier of the device to add to the tenant.
 * @param password The password to use for the device's credentials.
 * @return A future indicating the outcome of the operation.
 */
public Future<Void> addDeviceForTenant(final TenantObject tenant, final String deviceId,
        final String password) {

    return addTenant(JsonObject.mapFrom(tenant)).compose(ok -> registerDevice(tenant.getTenantId(), deviceId))
            .compose(ok -> {
                final CredentialsObject credentialsSpec = CredentialsObject.fromHashedPassword(deviceId,
                        deviceId, password, "sha-512", null, null, null);
                return addCredentials(tenant.getTenantId(), JsonObject.mapFrom(credentialsSpec));
            });
}

From source file:org.eclipse.hono.tests.DeviceRegistryHttpClient.java

License:Open Source License

/**
 * Creates a tenant and adds a device to it with a given client certificate.
 * <p>/*from   ww  w .  ja  v  a  2  s .c o m*/
 * The device will be registered with a set of <em>x509-cert</em> credentials
 * using the client certificate's subject DN as authentication identifier.
 * 
 * @param tenant The tenant to create.
 * @param deviceId The identifier of the device to add to the tenant.
 * @param deviceCert The device's client certificate.
 * @return A future indicating the outcome of the operation.
 */
public Future<Void> addDeviceForTenant(final TenantObject tenant, final String deviceId,
        final X509Certificate deviceCert) {

    return addTenant(JsonObject.mapFrom(tenant)).compose(ok -> registerDevice(tenant.getTenantId(), deviceId))
            .compose(ok -> {
                final CredentialsObject credentialsSpec = CredentialsObject.fromClientCertificate(deviceId,
                        deviceCert, null, null);
                return addCredentials(tenant.getTenantId(), JsonObject.mapFrom(credentialsSpec));
            }).map(ok -> {
                LOG.debug(
                        "registered device with client certificate [tenant-id: {}, device-id: {}, auth-id: {}]",
                        tenant.getTenantId(), deviceId,
                        deviceCert.getSubjectX500Principal().getName(X500Principal.RFC2253));
                return null;
            });
}

From source file:org.jberet.vertx.rest.JBeretRouterConfig.java

License:Open Source License

private static void getJobs(final RoutingContext routingContext) {
    final JobEntity[] jobEntities = JobService.getInstance().getJobs();
    final JsonArray jsonArray = new JsonArray();
    for (JobEntity jobEntity : jobEntities) {
        jsonArray.add(JsonObject.mapFrom(jobEntity));
    }//from ww  w  .j a v  a2 s.  c om
    sendJsonResponse(routingContext, jsonArray.encodePrettily());
}