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:org.matrixlab.pisces.metastore.core.CustomMessageCodec.java

@Override
public void encodeToWire(Buffer buffer, CustomMessage customMessage) {
    // Easiest ways is using JSON object
    JsonObject jsonToEncode = new JsonObject();
    jsonToEncode.put("statusCode", customMessage.getStatusCode());
    jsonToEncode.put("resultCode", customMessage.getResultCode());
    jsonToEncode.put("summary", customMessage.getSummary());

    // 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);// w ww.j  ava2  s.  c o m
    buffer.appendString(jsonToStr);
}

From source file:org.mycontroller.standalone.eventbus.MessageStatusCodec.java

License:Apache License

@Override
public void encodeToWire(Buffer buffer, MessageStatus messageStatus) {
    // Easiest ways is using JSON object
    JsonObject jsonToEncode = new JsonObject();
    jsonToEncode.put("status", messageStatus.getStatus().name());
    jsonToEncode.put("message", messageStatus.getMessage());

    // 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);/*from  w ww. j  a v a 2 s .  c  o  m*/
    buffer.appendString(jsonToStr);
}

From source file:org.sfs.auth.SimpleAuthProvider.java

License:Apache License

@Override
public void handleOpenstackKeystoneAuth(SfsRequest httpServerRequest) {
    httpServerRequest.pause();//from w w w  .j a v a2 s. c  o  m
    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();

    aVoid().flatMap(aVoid -> {
        final BufferWriteEndableWriteStream bufferWriteStream = new BufferWriteEndableWriteStream();
        LimitedWriteEndableWriteStream limitedWriteStream = new LimitedWriteEndableWriteStream(
                bufferWriteStream, MAX_AUTH_REQUEST_SIZE);
        return pump(httpServerRequest, limitedWriteStream).map(aVoid1 -> bufferWriteStream.toBuffer());
    }).map(new HttpBodyLogger()).map(new BufferToJsonObject()).map(jsonObject -> {
        JsonObject authJsonObject = jsonObject.getJsonObject("auth");
        JsonObject passwordCredentialsJson = authJsonObject.getJsonObject("passwordCredentials");
        String username = passwordCredentialsJson.getString("username");
        String password = passwordCredentialsJson.getString("password");
        String tenantName = authJsonObject.getString("tenantName");
        if (tenantName == null) {
            tenantName = "default";
        }

        Set<String> selectedRoles = new HashSet<>();

        for (Map.Entry<Role, Collection<User>> entry : roles.asMap().entrySet()) {
            Role role = entry.getKey();
            Collection<User> users = entry.getValue();
            for (User user : users) {
                if (equal(user.getUsername(), username) && equal(user.getPassword(), password)) {
                    selectedRoles.add(role.value());
                }
            }
        }

        if (selectedRoles.isEmpty()) {
            JsonObject errorJson = new JsonObject().put("message", "Invalid Credentials");
            throw new HttpRequestValidationException(HTTP_FORBIDDEN, errorJson);
        }

        Escaper escaper = urlPathSegmentEscaper();

        String serviceUrl = getRemoteServiceUrl(httpServerRequest);
        serviceUrl = format("%s/openstackswift001/%s", serviceUrl, escaper.escape(tenantName));

        JsonObject endpointJsonObject = new JsonObject().put("region", "ORD").put("tenantId", tenantName)
                .put("publicURL", serviceUrl).put("internalURL", serviceUrl);

        JsonArray endpointsJsonArray = new JsonArray().add(endpointJsonObject);

        JsonObject serviceCatalogJsonObject = new JsonObject().put("type", "object-store")
                .put("name", "openstackswift001").put("endpoints", endpointsJsonArray);

        JsonArray serviceCatalogJsonArray = new JsonArray().add(serviceCatalogJsonObject);

        JsonObject userJsonObject = new JsonObject().put("username", username)
                .put("roles_links", new JsonArray()).put("id", username);

        JsonArray roles = new JsonArray();
        for (String selectedRole : selectedRoles) {
            roles.add(selectedRole);
        }

        userJsonObject = userJsonObject.put("roles", roles);

        Calendar expiresDt = getInstance();
        expiresDt.setTimeInMillis(currentTimeMillis() + 86400000);

        JsonObject tokenJsonObject = new JsonObject().put("audit_ids", new JsonArray())
                .put("expires", toDateTimeString(expiresDt)).put("issued_at", toDateTimeString(getInstance()))
                .put("id", base64().encode((username + ":" + password).getBytes(UTF_8)));

        JsonObject metadataJsonObject = new JsonObject().put("is_admin", 0).put("roles", new JsonArray());

        return new JsonObject().put("access", new JsonObject().put("serviceCatalog", serviceCatalogJsonArray)
                .put("token", tokenJsonObject).put("user", userJsonObject).put("metadata", metadataJsonObject));
    }).single().subscribe(new ConnectionCloseTerminus<JsonObject>(httpServerRequest) {
        @Override
        public void onNext(JsonObject authenticationResponse) {
            Buffer buffer = buffer(authenticationResponse.encode(), UTF_8.toString());
            httpServerRequest.response().setStatusCode(HTTP_OK)
                    .putHeader(CONTENT_LENGTH, valueOf(buffer.length())).write(buffer);
        }
    });
}

From source file:org.sfs.elasticsearch.AbstractBulkUpdateEndableWriteStream.java

License:Apache License

protected Observable<Void> write0(SearchHit data) {
    count++;//w  w w. ja v a  2  s  . c om
    return Defer.aVoid().flatMap(aVoid -> {
        String index = data.getIndex();
        String type = data.getType();
        String id = data.getId();
        long version = data.getVersion();
        JsonObject jsonObject = new JsonObject(data.getSourceAsString());
        return transform(jsonObject, id, version).map(oUpdatedJsonObject -> {
            if (oUpdatedJsonObject.isPresent()) {
                JsonObject updatedJsonObject = oUpdatedJsonObject.get();

                if (!equal(updatedJsonObject, jsonObject)) {

                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(format("Index Request {%s,%s,%s,%d} = %s, original was %s", index, type,
                                id, data.getVersion(), updatedJsonObject.encodePrettily(),
                                jsonObject.encodePrettily()));
                    }

                    IndexRequestBuilder request = elasticsearch.get().prepareIndex(index, type, id)
                            .setSource(updatedJsonObject.encode())
                            .setTimeout(timeValueMillis(elasticsearch.getDefaultIndexTimeout() - 10));
                    if (version >= 0) {
                        request = request.setVersion(version);
                    }

                    if (bulkRequest == null) {
                        bulkRequest = elasticsearch.get().prepareBulk().setTimeout(timeValueMillis(
                                (elasticsearch.getDefaultIndexTimeout() * writeQueueMaxSize) - 10));
                    }
                    bulkRequest.add(request);

                }
            } else {
                DeleteRequestBuilder request = elasticsearch.get().prepareDelete(index, type, id)
                        .setTimeout(timeValueMillis(elasticsearch.getDefaultDeleteTimeout() - 10));
                if (version >= 0) {
                    request = request.setVersion(version);
                }

                if (bulkRequest == null) {
                    bulkRequest = elasticsearch.get().prepareBulk().setTimeout(
                            timeValueMillis((elasticsearch.getDefaultIndexTimeout() * writeQueueMaxSize) - 10));
                }
                bulkRequest.add(request);
            }
            return (Void) null;
        }).onErrorResumeNext(throwable -> {
            LOGGER.warn("Handling Error", throwable);
            return just(null);
        }).singleOrDefault(null);
    });
}

From source file:org.sfs.elasticsearch.account.PersistAccount.java

License:Apache License

@Override
public Observable<Optional<PersistentAccount>> call(final TransientAccount transientAccount) {

    final Elasticsearch elasticSearch = vertxContext.verticle().elasticsearch();

    final JsonObject source = transientAccount.toJsonObject();

    String encoded;//  w  w  w  .  j  ava  2 s .c  o  m

    if (LOGGER.isDebugEnabled()) {
        encoded = source.encodePrettily();
        LOGGER.debug(format("Index Request {%s,%s,%s} = %s", elasticSearch.defaultType(),
                elasticSearch.accountIndex(), transientAccount.getId(), encoded));
    } else {
        encoded = source.encode();
    }

    IndexRequestBuilder request = elasticSearch.get()
            .prepareIndex(elasticSearch.accountIndex(), elasticSearch.defaultType(), transientAccount.getId())
            .setCreate(true).setTimeout(timeValueMillis(elasticSearch.getDefaultIndexTimeout() - 10))
            .setSource(encoded);

    return elasticSearch.execute(vertxContext, request, elasticSearch.getDefaultIndexTimeout())
            .map(indexResponse -> {
                if (indexResponse.isPresent()) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(format("Index Response {%s,%s,%s} = %s", indexResponse.get().getType(),
                                indexResponse.get().getIndex(), transientAccount.getId(),
                                Jsonify.toString(indexResponse.get())));
                    }
                    return of(fromIndexResponse(indexResponse.get(), source));
                } else {
                    LOGGER.debug(format("Index Response {%s,%s,%s} = %s", elasticSearch.defaultType(),
                            elasticSearch.accountIndex(), transientAccount.getId(), "null"));
                    return absent();
                }
            });
}

From source file:org.sfs.elasticsearch.account.UpdateAccount.java

License:Apache License

@Override
public Observable<Optional<PersistentAccount>> call(final PersistentAccount persistentAccount) {

    final Elasticsearch elasticSearch = vertxContext.verticle().elasticsearch();

    final JsonObject source = persistentAccount.toJsonObject();

    String encoded;//from  w w w .  j  a  v  a 2  s .  com

    if (LOGGER.isDebugEnabled()) {
        encoded = source.encodePrettily();
        LOGGER.debug(format("Index Request {%s,%s,%s,%d} = %s", elasticSearch.defaultType(),
                elasticSearch.accountIndex(), persistentAccount.getId(),
                persistentAccount.getPersistentVersion(), encoded));
    } else {
        encoded = source.encode();
    }

    IndexRequestBuilder request = elasticSearch.get()
            .prepareIndex(elasticSearch.accountIndex(), elasticSearch.defaultType(), persistentAccount.getId())
            .setVersion(persistentAccount.getPersistentVersion())
            .setTimeout(timeValueMillis(elasticSearch.getDefaultIndexTimeout() - 10)).setSource(encoded);

    return elasticSearch.execute(vertxContext, request, elasticSearch.getDefaultIndexTimeout())
            .map(indexResponse -> {
                if (indexResponse.isPresent()) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(format("Index Response {%s,%s,%s,%d} = %s", elasticSearch.defaultType(),
                                elasticSearch.accountIndex(), persistentAccount.getId(),
                                persistentAccount.getPersistentVersion(),
                                Jsonify.toString(indexResponse.get())));
                    }
                    return of(fromIndexResponse(indexResponse.get(), source));
                } else {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(format("Index Response {%s,%s,%s,%d} = %s", elasticSearch.defaultType(),
                                elasticSearch.accountIndex(), persistentAccount.getId(),
                                persistentAccount.getPersistentVersion(), "null"));
                    }
                    return absent();
                }
            });
}

From source file:org.sfs.elasticsearch.container.ListContainerKeys.java

License:Apache License

@Override
public Observable<PersistentContainerKey> call(PersistentContainer persistentContainer) {

    final Elasticsearch elasticSearch = vertxContext.verticle().elasticsearch();

    final JsonObject source = persistentContainer.toJsonObject();

    String encoded;//from   w  w w.j a  v a  2 s  .c  om

    if (LOGGER.isDebugEnabled()) {
        encoded = source.encodePrettily();
        LOGGER.debug(format("Search Request {%s,%s,%s,%d} = %s", elasticSearch.defaultType(),
                elasticSearch.containerKeyIndex(), persistentContainer.getId(),
                persistentContainer.getPersistentVersion(), encoded));
    } else {
        encoded = source.encode();
    }

    SearchRequestBuilder request = elasticSearch.get().prepareSearch(elasticSearch.containerKeyIndex())
            .setTypes(elasticSearch.defaultType()).setVersion(true)
            .setQuery(termQuery("container_id", persistentContainer.getId()))
            .setTimeout(timeValueMillis(elasticSearch.getDefaultIndexTimeout() - 10)).setSource(encoded);

    return elasticSearch.execute(vertxContext, request, elasticSearch.getDefaultIndexTimeout())
            .flatMap(oSearchResponse -> {
                if (oSearchResponse.isPresent()) {
                    SearchResponse searchResponse = oSearchResponse.get();
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(format("Search Response {%s,%s,%s,%d} = %s", elasticSearch.defaultType(),
                                elasticSearch.containerIndex(), persistentContainer.getId(),
                                persistentContainer.getPersistentVersion(), Jsonify.toString(searchResponse)));
                    }
                    return from(searchResponse.getHits());
                } else {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(format("Index Response {%s,%s,%s,%d} = %s", elasticSearch.defaultType(),
                                elasticSearch.containerIndex(), persistentContainer.getId(),
                                persistentContainer.getPersistentVersion(), "null"));
                    }
                    return empty();
                }
            }).map(searchHitFields -> fromSearchHit(persistentContainer, searchHitFields));
}

From source file:org.sfs.elasticsearch.container.PersistContainer.java

License:Apache License

@Override
public Observable<Optional<PersistentContainer>> call(final TransientContainer transientContainer) {

    final Elasticsearch elasticSearch = vertxContext.verticle().elasticsearch();

    final JsonObject source = transientContainer.toJsonObject();

    String encoded;/*from w ww .ja v a 2  s  .c o  m*/

    if (LOGGER.isDebugEnabled()) {
        encoded = source.encodePrettily();
        LOGGER.debug(format("Index Request {%s,%s,%s} = %s", elasticSearch.defaultType(),
                elasticSearch.containerIndex(), transientContainer.getId(), encoded));
    } else {
        encoded = source.encode();
    }

    IndexRequestBuilder request = elasticSearch.get()
            .prepareIndex(elasticSearch.containerIndex(), elasticSearch.defaultType(),
                    transientContainer.getId())
            .setCreate(true).setTimeout(timeValueMillis(elasticSearch.getDefaultIndexTimeout() - 10))
            .setSource(encoded);

    return elasticSearch.execute(vertxContext, request, elasticSearch.getDefaultIndexTimeout())
            .map(indexResponse -> {
                if (indexResponse.isPresent()) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(format("Index Response {%s,%s,%s} = %s", elasticSearch.defaultType(),
                                elasticSearch.containerIndex(), transientContainer.getId(),
                                Jsonify.toString(indexResponse.get())));
                    }
                    return of(fromIndexResponse(transientContainer.getParent(), indexResponse.get(), source));
                } else {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(format("Index Response {%s,%s,%s} = %s", elasticSearch.defaultType(),
                                elasticSearch.containerIndex(), transientContainer.getId(), "null"));
                    }
                    return absent();
                }
            });
}

From source file:org.sfs.elasticsearch.container.UpdateContainer.java

License:Apache License

@Override
public Observable<Optional<PersistentContainer>> call(final PersistentContainer persistentContainer) {

    final Elasticsearch elasticSearch = vertxContext.verticle().elasticsearch();

    final JsonObject source = persistentContainer.toJsonObject();

    String encoded;/* w  w w .j ava2 s  .  c o  m*/

    if (LOGGER.isDebugEnabled()) {
        encoded = source.encodePrettily();
        LOGGER.debug(format("Index Request {%s,%s,%s,%d} = %s", elasticSearch.defaultType(),
                elasticSearch.containerIndex(), persistentContainer.getId(),
                persistentContainer.getPersistentVersion(), encoded));
    } else {
        encoded = source.encode();
    }

    IndexRequestBuilder request = elasticSearch.get()
            .prepareIndex(elasticSearch.containerIndex(), elasticSearch.defaultType(),
                    persistentContainer.getId())
            .setVersion(persistentContainer.getPersistentVersion())
            .setTimeout(timeValueMillis(elasticSearch.getDefaultIndexTimeout() - 10)).setSource(encoded);

    return elasticSearch.execute(vertxContext, request, elasticSearch.getDefaultIndexTimeout())
            .map(indexResponse -> {
                if (indexResponse.isPresent()) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(format("Index Response {%s,%s,%s,%d} = %s", elasticSearch.defaultType(),
                                elasticSearch.containerIndex(), persistentContainer.getId(),
                                persistentContainer.getPersistentVersion(),
                                Jsonify.toString(indexResponse.get())));
                    }
                    return of(fromIndexResponse(persistentContainer.getParent(), indexResponse.get(), source));
                } else {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(format("Index Response {%s,%s,%s,%d} = %s", elasticSearch.defaultType(),
                                elasticSearch.containerIndex(), persistentContainer.getId(),
                                persistentContainer.getPersistentVersion(), "null"));
                    }
                    return absent();
                }
            });
}

From source file:org.sfs.elasticsearch.containerkey.PersistContainerKey.java

License:Apache License

@Override
public Observable<Holder2<TransientContainerKey, Optional<PersistentContainerKey>>> call(
        final TransientContainerKey transientContainerKey) {

    final Elasticsearch elasticSearch = vertxContext.verticle().elasticsearch();

    final JsonObject document = transientContainerKey.toJsonObject();

    String encoded;/*from   ww  w . ja v a  2 s. c  om*/

    if (LOGGER.isDebugEnabled()) {
        encoded = document.encodePrettily();
        LOGGER.debug(format("Index Request {%s,%s,%s} = %s", elasticSearch.defaultType(),
                elasticSearch.containerKeyIndex(), transientContainerKey.getId(), encoded));
    } else {
        encoded = document.encode();
    }

    IndexRequestBuilder request = elasticSearch.get()
            .prepareIndex(elasticSearch.containerKeyIndex(), elasticSearch.defaultType(),
                    transientContainerKey.getId())
            .setCreate(true) // put only if absent
            .setTimeout(timeValueMillis(elasticSearch.getDefaultIndexTimeout() - 10)).setSource(encoded);

    return elasticSearch.execute(vertxContext, request, elasticSearch.getDefaultIndexTimeout())
            .map(indexResponse -> {
                Holder2<TransientContainerKey, Optional<PersistentContainerKey>> output = new Holder2<>();
                output.value0 = transientContainerKey;
                if (indexResponse.isPresent()) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(format("Index Response {%s,%s,%s} = %s", elasticSearch.defaultType(),
                                elasticSearch.containerKeyIndex(), transientContainerKey.getId(),
                                Jsonify.toString(indexResponse.get())));
                    }
                    output.value1 = of(fromIndexResponse(transientContainerKey.getPersistentContainer(),
                            indexResponse.get(), document));
                } else {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(format("Index Response {%s,%s,%s} = %s", elasticSearch.defaultType(),
                                elasticSearch.containerKeyIndex(), transientContainerKey.getId(), "null"));
                    }
                    output.value1 = absent();
                }
                return output;
            });
}