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

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

Introduction

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

Prototype

public String encode() 

Source Link

Document

Encode this JSON object as a string.

Usage

From source file:io.flowly.engine.data.manager.FlowInstanceReadWriteManager.java

License:Open Source License

private void updateFlowObjectProperties(Vertex vertex, FlowInstance instance, String status,
        boolean saveMetadata) {
    vertex.property(Schema.P_STATUS, status);

    if (instance == null) {
        return;//from ww  w .  ja  va  2  s . c om
    }

    if (saveMetadata) {
        vertex.property(Schema.V_P_META_DATA, instance.getMetadata().encode());
        vertex.property(Schema.V_P_INSTANCE_ID, instance.getMetadata().getInstanceId());
    }

    JsonObject data = instance.getData();
    if (data != null && data.getMap().size() > 0) {
        vertex.property(Schema.V_P_DATA, data.encode());
    }

    JsonObject inputData = instance.getInputData();
    if (inputData != null && inputData.getMap().size() > 0) {
        vertex.property(Schema.V_P_INPUT_DATA, inputData.encode());
    }

    JsonObject outputData = instance.getOutputData();
    if (outputData != null && outputData.getMap().size() > 0) {
        vertex.property(Schema.V_P_OUTPUT_DATA, outputData.encode());
    }
}

From source file:io.flowly.webapp.FlowApiRouter.java

License:Open Source License

private void prepareGetInboxRoute(Router api, Vertx vertx) {
    Route getInboxRoute = api.route(HttpMethod.GET, "/inbox/:subjectId").produces(JSON_CONTENT_TYPE);
    getInboxRoute.handler(routingContext -> {
        String subjectId = routingContext.request().getParam(ObjectKeys.SUBJECT_ID);
        logger.info("Get inbox request received: " + subjectId);

        JsonObject args = new JsonObject();
        args.put(ObjectKeys.SUBJECT_ID, subjectId);

        String pageNumber = routingContext.request().getParam(ObjectKeys.PAGE_NUMBER);
        if (pageNumber != null) {
            args.put(ObjectKeys.PAGE_NUMBER, Integer.parseInt(pageNumber));
        }//from w  ww .ja v a 2s  .co m

        String pageSize = routingContext.request().getParam(ObjectKeys.PAGE_SIZE);
        if (pageSize != null) {
            args.put(ObjectKeys.PAGE_SIZE, Integer.parseInt(pageSize));
        }

        vertx.eventBus().send(ClusterAddresses.GET_USER_INBOX, args, reply -> {
            JsonObject inbox = (JsonObject) reply.result().body();
            writeResponse(routingContext, inbox.encode());
        });
    });
}

From source file:io.openshift.booster.RestApplication.java

License:Apache License

@Override
public void start(Future done) {
    // Create a router object.
    Router router = Router.router(vertx);
    router.get("/health").handler(rc -> rc.response().end("OK"));

    JsonObject config = new JsonObject().put("realm", System.getenv("REALM"))
            .put("public-key", System.getenv("REALM_PUBLIC_KEY"))
            .put("auth-server-url", System.getenv("SSO_AUTH_SERVER_URL")).put("ssl-required", "external")
            .put("resource", System.getenv("CLIENT_ID"))
            .put("credentials", new JsonObject().put("secret", System.getenv("CREDENTIALS")))
            // since we're consuming keycloak JWTs we need to locate the permission claims in the token
            .put("permissionsClaimKey", "realm_access/roles");

    // Configure the AuthHandler to process JWT's
    router.route("/greeting").handler(JWTAuthHandler.create(JWTAuth.create(vertx, config)));

    // This is how one can do RBAC, e.g.: only admin is allowed
    router.get("/greeting").handler(ctx -> {
        ctx.user().isAuthorised("vertx-admin", authz -> {
            if (authz.succeeded() && authz.result()) {
                ctx.next();/* w w  w. j a  v a  2 s .co  m*/
            } else {
                log.error("AuthZ failed!");
                ctx.fail(403);
            }
        });
    });

    router.get("/greeting").handler(ctx -> {
        String name = ctx.request().getParam("name");
        if (name == null) {
            name = "World";
        }
        ctx.response().putHeader(CONTENT_TYPE, "application/json; charset=utf-8")
                .end(new Greeting(++counter, name).encode());
    });

    // serve the dynamic config so the web client
    // can also connect to the SSO server
    router.get("/keycloak.json").handler(ctx -> {
        ctx.response().putHeader(CONTENT_TYPE, "application/json; charset=utf-8").end(config.encode());
    });

    // serve static files (web client)
    router.get().handler(StaticHandler.create());

    // Create the HTTP server and pass the "accept" method to the request handler.
    vertx.createHttpServer().requestHandler(router::accept).listen(
            // Retrieve the port from the configuration,
            // default to 8080.
            config().getInteger("http.port", 8080), done.completer());
}

From source file:microservicerx.rx.DistributedObservableCodec.java

@Override
public void encodeToWire(Buffer buffer, DistributedObservable customMessage) {
    // Easiest ways is using JSON object
    JsonObject jsonToEncode = new JsonObject();
    jsonToEncode.put("address", customMessage.address);

    // Encode object to string
    String jsonToStr = jsonToEncode.encode();

    // Length of JSON: is NOT characters count
    int length = jsonToStr.getBytes().length;

    // Write data into given buffer
    buffer.appendInt(length);/* ww  w.  j av  a2  s .c om*/
    buffer.appendString(jsonToStr);
}

From source file:org.eclipse.hono.client.impl.AbstractRequestResponseClient.java

License:Open Source License

protected final void createAndSendRequest(final String action, final Map<String, Object> properties,
        final JsonObject payload, final Handler<AsyncResult<R>> resultHandler) {

    final Message request = createMessage(action, properties);
    if (payload != null) {
        request.setContentType("application/json; charset=utf-8");
        request.setBody(new AmqpValue(payload.encode()));
    }/*  w ww . j  av a2  s.c o m*/
    sendMessage(request, resultHandler);
}

From source file:org.eclipse.hono.devices.HonoHttpDevice.java

License:Open Source License

/**
 * Send a message to Hono HTTP adapter. Delay any successful response by 1000 milliseconds.
 *
 * @param payload JSON object that will be sent as UTF-8 encoded String.
 * @param headersToAdd A map that contains all headers to add to the http request.
 * @param asEvent If {@code true}, an event message is sent, otherwise a telemetry message.
 * @return CompletableFuture&lt;MultiMap&gt; A completable future that contains the HTTP response in a MultiMap.
 *//*from w w  w .  ja  va 2 s  .com*/
private CompletableFuture<MultiMap> sendMessage(final JsonObject payload, final MultiMap headersToAdd,
        final boolean asEvent) {
    final CompletableFuture<MultiMap> result = new CompletableFuture<>();

    final Predicate<Integer> successfulStatus = statusCode -> statusCode == HttpURLConnection.HTTP_ACCEPTED;
    final HttpClientRequest req = vertx.createHttpClient()
            .post(HONO_HTTP_ADAPTER_PORT, HONO_HTTP_ADAPTER_HOST, asEvent ? "/event" : "/telemetry")
            .handler(response -> {
                if (successfulStatus.test(response.statusCode())) {
                    vertx.setTimer(1000, l -> result.complete(response.headers()));
                } else {
                    result.completeExceptionally(new ServiceInvocationException(response.statusCode()));
                }
            }).exceptionHandler(t -> result.completeExceptionally(t));

    req.headers().addAll(headersToAdd);
    req.headers()
            .addAll(MultiMap.caseInsensitiveMultiMap()
                    .add(HttpHeaders.AUTHORIZATION, getBasicAuth(TENANT_ID, DEVICE_AUTH_ID, DEVICE_PASSWORD))
                    .add(HttpHeaders.ORIGIN, ORIGIN_URI));

    if (payload == null) {
        req.end();
    } else {
        req.end(payload.encode());
    }
    return result;
}

From source file:org.eclipse.hono.service.monitoring.AbstractMessageSenderConnectionEventProducer.java

License:Open Source License

private Future<?> sendNotificationEvent(final Device authenticatedDevice, final String protocolAdapter,
        final String remoteId, final String cause, final JsonObject data) {

    if (authenticatedDevice == null) {
        // we only handle authenticated devices
        return Future.succeededFuture();
    }/*from ww w. java2s  . c  o  m*/

    // get an assertion

    final Future<String> assertionFuture = this.deviceRegistryClient
            .getOrCreateRegistrationClient(authenticatedDevice.getTenantId()).compose(registrationClient -> {
                return registrationClient.assertRegistration(authenticatedDevice.getDeviceId())
                        .map(registration -> {
                            return registration.getString(RegistrationConstants.FIELD_ASSERTION);
                        });
            });

    // get a sender

    final Future<MessageSender> senderFuture = getOrCreateSender(authenticatedDevice);

    // send message with assertion and sender

    return CompositeFuture.all(assertionFuture, senderFuture).compose(f -> {
        final String deviceId = authenticatedDevice.getDeviceId();

        final JsonObject payload = new JsonObject();
        payload.put("cause", cause);
        payload.put("remote-id", remoteId);
        payload.put("source", protocolAdapter);

        if (data != null) {
            payload.put("data", data);
        }

        return senderFuture.result().send(deviceId, payload.encode().getBytes(StandardCharsets.UTF_8),
                EventConstants.EVENT_CONNECTION_NOTIFICATION_CONTENT_TYPE, assertionFuture.result(), v -> {
                });
    });
}

From source file:org.eclipse.hono.service.registration.BaseRegistrationService.java

License:Open Source License

/**
 * Processes a registration request message received via the Vertx event bus.
 * // w w w  .  j  av  a  2  s.c om
 * @param regMsg The message.
 */
public final void processRegistrationMessage(final Message<JsonObject> regMsg) {

    try {
        final JsonObject body = regMsg.body();
        final String tenantId = body.getString(RequestResponseApiConstants.FIELD_TENANT_ID);
        final String deviceId = body.getString(RequestResponseApiConstants.FIELD_DEVICE_ID);
        final String operation = body.getString(MessageHelper.SYS_PROPERTY_SUBJECT);

        switch (operation) {
        case ACTION_ASSERT:
            log.debug("asserting registration of device [{}] with tenant [{}]", deviceId, tenantId);
            assertRegistration(tenantId, deviceId, result -> reply(regMsg, result));
            break;
        case ACTION_GET:
            log.debug("retrieving device [{}] of tenant [{}]", deviceId, tenantId);
            getDevice(tenantId, deviceId, result -> reply(regMsg, result));
            break;
        case ACTION_REGISTER:
            JsonObject payload = getRequestPayload(body);
            log.debug("registering device [{}] of tenant [{}] with data {}", deviceId, tenantId,
                    payload != null ? payload.encode() : null);
            addDevice(tenantId, deviceId, payload, result -> reply(regMsg, result));
            break;
        case ACTION_UPDATE:
            payload = getRequestPayload(body);
            log.debug("updating registration for device [{}] of tenant [{}] with data {}", deviceId, tenantId,
                    payload != null ? payload.encode() : null);
            updateDevice(tenantId, deviceId, payload, result -> reply(regMsg, result));
            break;
        case ACTION_DEREGISTER:
            log.debug("deregistering device [{}] of tenant [{}]", deviceId, tenantId);
            removeDevice(tenantId, deviceId, result -> reply(regMsg, result));
            break;
        case ACTION_ENABLED:
            log.debug("checking if device [{}] of tenant [{}] is enabled", deviceId, tenantId);
            isEnabled(tenantId, deviceId, result -> reply(regMsg, result));
            break;
        default:
            log.info("operation [{}] not supported", operation);
            reply(regMsg, RegistrationResult.from(HTTP_BAD_REQUEST));
        }
    } catch (ClassCastException e) {
        log.debug("malformed request message");
        reply(regMsg, RegistrationResult.from(HTTP_BAD_REQUEST));
    }
}

From source file:org.eclipse.hono.util.CredentialsConstants.java

License:Open Source License

public static Message getAmqpReply(final String status, final Object correlationId, final String tenantId,
        final String deviceId, final boolean isApplCorrelationId, final JsonObject payload) {

    final ResourceIdentifier address = ResourceIdentifier.from(CredentialsConstants.CREDENTIALS_ENDPOINT,
            tenantId, deviceId);/*from   ww  w  . j av a  2  s  .  com*/
    final Message message = ProtonHelper.message();
    message.setMessageId(UUID.randomUUID().toString());
    message.setCorrelationId(correlationId);
    message.setAddress(address.toString());

    final Map<String, Object> map = new HashMap<>();
    map.put(MessageHelper.APP_PROPERTY_DEVICE_ID, deviceId);
    map.put(MessageHelper.APP_PROPERTY_TENANT_ID, tenantId);
    map.put(MessageHelper.APP_PROPERTY_STATUS, status);
    message.setApplicationProperties(new ApplicationProperties(map));

    if (isApplCorrelationId) {
        Map<Symbol, Object> annotations = new HashMap<>();
        annotations.put(Symbol.valueOf(MessageHelper.ANNOTATION_X_OPT_APP_CORRELATION_ID), isApplCorrelationId);
        message.setMessageAnnotations(new MessageAnnotations(annotations));
    }

    if (payload != null) {
        message.setContentType("application/json; charset=utf-8");
        message.setBody(new AmqpValue(payload.encode()));
    }
    return message;
}

From source file:org.eclipse.hono.util.RequestResponseApiConstants.java

License:Open Source License

/**
 * Build a Proton message containing the reply to a request for the provided endpoint.
 *
 * @param endpoint The endpoint the reply message will be built for.
 * @param status The status from the service that processed the message.
 * @param correlationId The UUID to correlate the reply with the originally sent message.
 * @param tenantId The tenant for which the message was processed.
 * @param deviceId The device that the message relates to.
 * @param isApplCorrelationId Flag to inidicate if the correlationId has to be available as application property
 *        {@link MessageHelper#ANNOTATION_X_OPT_APP_CORRELATION_ID}.
 * @param payload The payload of the message reply as json object.
 * @return Message The built Proton message. Maybe null. In that case, the message reply will not contain a body.
 *//*from  w  ww. j  ava 2  s . c o  m*/
public static final Message getAmqpReply(final String endpoint, final String status, final Object correlationId,
        final String tenantId, final String deviceId, final boolean isApplCorrelationId,
        final JsonObject payload) {

    final ResourceIdentifier address = ResourceIdentifier.from(endpoint, tenantId, deviceId);
    final Message message = ProtonHelper.message();
    message.setMessageId(UUID.randomUUID().toString());
    message.setCorrelationId(correlationId);
    message.setAddress(address.toString());

    final Map<String, Object> map = new HashMap<>();
    map.put(MessageHelper.APP_PROPERTY_DEVICE_ID, deviceId);
    map.put(MessageHelper.APP_PROPERTY_TENANT_ID, tenantId);
    map.put(MessageHelper.APP_PROPERTY_STATUS, status);
    message.setApplicationProperties(new ApplicationProperties(map));

    if (isApplCorrelationId) {
        Map<Symbol, Object> annotations = new HashMap<>();
        annotations.put(Symbol.valueOf(MessageHelper.ANNOTATION_X_OPT_APP_CORRELATION_ID), true);
        message.setMessageAnnotations(new MessageAnnotations(annotations));
    }

    if (payload != null) {
        message.setContentType("application/json; charset=utf-8");
        message.setBody(new AmqpValue(payload.encode()));
    }
    return message;
}