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

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

Introduction

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

Prototype

public String encodePrettily() 

Source Link

Document

Encode this JSON object a a string, with whitespace to make the object easier to read by a human, or other sentient organism.

Usage

From source file:org.sfs.elasticsearch.nodes.UpdateServiceDef.java

License:Apache License

@Override
public Observable<Optional<PersistentServiceDef>> call(final PersistentServiceDef persistentServiceDef) {

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

    final String id = persistentServiceDef.getId();

    final JsonObject source = persistentServiceDef.toJsonObject();

    String encoded;//from w w  w. j a  va 2 s  .  c  o  m

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

    IndexRequestBuilder request = elasticSearch.get()
            .prepareIndex(elasticSearch.serviceDefTypeIndex(), elasticSearch.defaultType(), id)
            .setSource(encoded).setTTL(ttl).setVersion(persistentServiceDef.getVersion()).setCreate(false)
            .setTimeout(timeValueMillis(elasticSearch.getDefaultIndexTimeout() - 10));

    return elasticSearch.execute(vertxContext, request, elasticSearch.getDefaultIndexTimeout())
            .map(new Func1<Optional<IndexResponse>, Optional<PersistentServiceDef>>() {
                @Override
                public Optional<PersistentServiceDef> call(Optional<IndexResponse> oIndexResponse) {
                    if (oIndexResponse.isPresent()) {
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug(format("Response {%s,%s,%s} = %s", elasticSearch.defaultType(),
                                    elasticSearch.serviceDefTypeIndex(), id,
                                    Jsonify.toString(oIndexResponse.get())));
                        }
                        return fromNullable(fromIndexResponse(oIndexResponse.get(), source));
                    } else {
                        LOGGER.debug(format("Response {%s,%s,%s} = %s", elasticSearch.defaultType(),
                                elasticSearch.serviceDefTypeIndex(), id, "null"));
                        return absent();
                    }
                }
            });
}

From source file:org.sfs.elasticsearch.object.PersistObject.java

License:Apache License

@Override
public Observable<Optional<PersistentObject>> call(TransientObject transientObject) {

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

    PersistentContainer container = transientObject.getParent();

    String objectIndex = elasticSearch.objectIndex(container.getName());

    final JsonObject source = transientObject.toJsonObject();

    String encoded;//from w  w  w  .ja va  2  s. c o  m

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

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

    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(),
                                objectIndex, transientObject.getId(), Jsonify.toString(indexResponse.get())));
                    }
                    return of(fromIndexResponse(transientObject.getParent(), indexResponse.get(), source));
                } else {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(format("Index Response {%s,%s,%s} = %s", elasticSearch.defaultType(),
                                objectIndex, transientObject.getId(), "null"));
                    }
                    return absent();
                }
            });
}

From source file:org.sfs.elasticsearch.object.UpdateObject.java

License:Apache License

@Override
public Observable<Optional<PersistentObject>> call(final PersistentObject persistentObject) {

    final JsonObject source = persistentObject.toJsonObject();

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

    PersistentContainer persistentContainer = persistentObject.getParent();

    String objectIndex = elasticSearch.objectIndex(persistentContainer.getName());

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

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

    IndexRequestBuilder request = elasticSearch.get()
            .prepareIndex(objectIndex, elasticSearch.defaultType(), persistentObject.getId())
            .setVersion(persistentObject.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(),
                                objectIndex, persistentObject.getId(), persistentObject.getPersistentVersion(),
                                Jsonify.toString(indexResponse.get())));
                    }
                    return of(fromIndexResponse(persistentObject.getParent(), indexResponse.get(), source));
                } else {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(format("Index Response {%s,%s,%s,%d} = %s", elasticSearch.defaultType(),
                                objectIndex, persistentObject.getId(), persistentObject.getPersistentVersion(),
                                "null"));
                    }
                    return absent();
                }
            });
}

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

License:Apache License

@Override
protected Observable<Optional<JsonObject>> transform(final JsonObject data, String id, long version) {
    return toPersistentObject(data, id, version).doOnNext(persistentObject -> {
        for (TransientVersion transientVersion : persistentObject.getVersions()) {
            transientVersion.setDeleted(Boolean.TRUE);
        }/* w w  w .j av  a 2s .  c  om*/
    })
            // attempt to delete versions that need deleting
            .flatMap(this::pruneObject)
            .timeout(3, TimeUnit.MINUTES,
                    Observable.error(new RuntimeException("Timeout on pruneObject " + data.encodePrettily())),
                    scheduler)
            .map(persistentObject -> {
                if (persistentObject.getVersions().isEmpty()) {
                    return absent();
                } else {
                    JsonObject jsonObject = persistentObject.toJsonObject();
                    return of(jsonObject);
                }
            });
}

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

License:Apache License

@Override
protected Observable<Optional<JsonObject>> transform(final JsonObject data, String id, long version) {
    return toPersistentObject(data, id, version).map(this::forceRemoveVolumes)
            // delete versions that are to old to attempt verification,ack and rebalance
            .flatMap(this::deleteOldUnAckdVersions)
            .timeout(3, TimeUnit.MINUTES,
                    Observable.error(new RuntimeException(
                            "Timeout on deleteOldUnAckdVersions " + data.encodePrettily())),
                    scheduler)/*from   w w  w  .j av  a2 s . co  m*/
            // attempt to delete versions that need deleting
            .flatMap(this::pruneObject)
            .timeout(3, TimeUnit.MINUTES,
                    Observable.error(new RuntimeException("Timeout on pruneObject " + data.encodePrettily())),
                    scheduler)
            // verifyAck before rebalance
            // so that in cases where the verify/ack
            // failed to persist to the index
            // we're able to recreate the state
            // needed for rebalancing
            .flatMap(this::verifyAck)
            .timeout(3, TimeUnit.MINUTES,
                    Observable.error(new RuntimeException("Timeout on verifyAck " + data.encodePrettily())),
                    scheduler)
            // rebalance the objects, including the ones that were just re-verified
            // disable rebalance because more testing is needed
            .flatMap(this::reBalance)
            .timeout(3, TimeUnit.MINUTES,
                    Observable.error(new RuntimeException("Timeout on reBalance " + data.encodePrettily())),
                    scheduler)
            .map(persistentObject -> {
                if (persistentObject.getVersions().isEmpty()) {
                    return absent();
                } else {
                    JsonObject jsonObject = persistentObject.toJsonObject();
                    return of(jsonObject);
                }
            });
}

From source file:org.sfs.nodes.compute.account.GetAccountMeta.java

License:Apache License

@Override
public void handle(SfsRequest httpServerRequest) {
    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();

    aVoid().flatMap(new Authenticate(httpServerRequest)).flatMap(new ValidateActionAdmin(httpServerRequest))
            .map(aVoid -> fromSfsRequest(httpServerRequest)).map(new ValidateAccountPath())
            .map(ObjectPath::accountPath).map(Optional::get).flatMap(new LoadAccount(vertxContext))
            .map(new ValidatePersistentAccountExists()).map(PersistentAccount::toJsonObject)
            .subscribe(new ConnectionCloseTerminus<JsonObject>(httpServerRequest) {
                @Override/*from  w  ww .j av  a2s. co  m*/
                public void onNext(JsonObject input) {
                    Buffer buffer = buffer(input.encodePrettily(), UTF_8.toString());
                    httpServerRequest.response().setStatusCode(HTTP_OK)
                            .putHeader(CONTENT_LENGTH, valueOf(buffer.length()))
                            .putHeader(CONTENT_TYPE, JSON_UTF_8.toString()).write(buffer);
                }
            });
}

From source file:org.sfs.nodes.compute.container.GetContainerMeta.java

License:Apache License

@Override
public void handle(SfsRequest httpServerRequest) {
    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();

    aVoid().flatMap(new Authenticate(httpServerRequest)).flatMap(new ValidateActionAdmin(httpServerRequest))
            .map(aVoid -> fromSfsRequest(httpServerRequest)).map(new ValidateObjectPath())
            .flatMap(new LoadAccountAndContainer(vertxContext)).map(PersistentContainer::toJsonObject)
            .subscribe(new ConnectionCloseTerminus<JsonObject>(httpServerRequest) {
                @Override//from w w  w .j  av a  2s  . co m
                public void onNext(JsonObject input) {
                    Buffer buffer = buffer(input.encodePrettily(), UTF_8.toString());
                    httpServerRequest.response().setStatusCode(HTTP_OK)
                            .putHeader(CONTENT_LENGTH, valueOf(buffer.length()))
                            .putHeader(CONTENT_TYPE, JSON_UTF_8.toString()).write(buffer);
                }
            });
}

From source file:org.sfs.nodes.compute.object.GetObjectMeta.java

License:Apache License

@Override
public void handle(SfsRequest httpServerRequest) {
    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();

    aVoid().flatMap(new Authenticate(httpServerRequest)).flatMap(new ValidateActionAdmin(httpServerRequest))
            .map(aVoid -> fromSfsRequest(httpServerRequest)).map(new ValidateObjectPath())
            .flatMap(new LoadAccountAndContainerAndObject(vertxContext)).map(PersistentObject::toJsonObject)
            .subscribe(new ConnectionCloseTerminus<JsonObject>(httpServerRequest) {
                @Override/*from   w  w  w  . j  a va2 s. c om*/
                public void onNext(JsonObject input) {
                    Buffer buffer = buffer(input.encodePrettily(), UTF_8.toString());
                    httpServerRequest.response().setStatusCode(HTTP_OK)
                            .putHeader(CONTENT_LENGTH, valueOf(buffer.length()))
                            .putHeader(CONTENT_TYPE, JSON_UTF_8.toString()).write(buffer);
                }
            });
}

From source file:org.sfs.nodes.HttpClientResponseException.java

License:Apache License

public HttpClientResponseException(HttpClientResponse httpClientResponse, JsonObject responseBuffer) {
    super(format("Status Code was %d. [%s]", httpClientResponse.statusCode(), responseBuffer.encodePrettily()));
}

From source file:org.sfs.rx.Terminus.java

License:Apache License

@Override
public void onError(Throwable e) {
    try {/*w w  w  . j  a  va  2 s  . c o  m*/
        HttpServerResponse response = httpServerRequest.response();
        response.setChunked(true);
        if (containsException(HttpRequestValidationException.class, e)) {
            HttpRequestValidationException cause = unwrapCause(HttpRequestValidationException.class, e).get();
            JsonObject entity = cause.getEntity();
            int status = cause.getStatusCode();

            // if credentials weren't supplied send unauthorized instead
            // of forbidden
            if (status == HTTP_FORBIDDEN && !httpServerRequest.headers().contains(AUTHORIZATION)
                    && !httpServerRequest.headers().contains(X_AUTH_TOKEN)) {
                status = HTTP_UNAUTHORIZED;
                if (!httpServerRequest.proxyKeepAliveStarted()) {
                    response.putHeader(WWW_AUTHENTICATE, "Basic realm=\"Helix\"");
                }
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Validate Error " + httpServerRequest.path(), e);
            }

            HttpMethod method = httpServerRequest.method();
            if (Objects.equals(HEAD, method)) {
                if (httpServerRequest.proxyKeepAliveStarted()) {
                    Buffer encoded = buffer(entity.encodePrettily(), UTF_8.toString())
                            .appendBuffer(DELIMITER_BUFFER);
                    response.end(encoded);
                } else {
                    Buffer encoded = buffer(entity.encodePrettily(), UTF_8.toString());
                    response.setStatusCode(status).write(encoded).end();
                }
            } else {
                if (httpServerRequest.proxyKeepAliveStarted()) {
                    Buffer encoded = buffer(entity.encodePrettily(), UTF_8.toString())
                            .appendBuffer(DELIMITER_BUFFER);
                    response.end(encoded);
                } else {
                    Buffer buffer = buffer(entity.encodePrettily(), UTF_8.toString());
                    response.setStatusCode(status).write(buffer).end(buffer);
                }
            }

        } else if (containsException(HttpStatusCodeException.class, e)) {
            HttpStatusCodeException cause = unwrapCause(HttpStatusCodeException.class, e).get();

            int status = cause.getStatusCode();

            // if credentials weren't supplied send unauthorized instead
            // of forbidden
            if (status == HTTP_FORBIDDEN && !httpServerRequest.headers().contains(AUTHORIZATION)
                    && !httpServerRequest.headers().contains(X_AUTH_TOKEN)) {
                status = HTTP_UNAUTHORIZED;
                if (!httpServerRequest.proxyKeepAliveStarted()) {
                    response.putHeader(WWW_AUTHENTICATE, "Basic realm=\"Helix\"");
                }
            }

            LOGGER.error("HttpStatusCode Error " + httpServerRequest.path(), e);

            if (httpServerRequest.proxyKeepAliveStarted()) {
                JsonObject jsonObject = new JsonObject().put("code", status);
                Buffer encoded = buffer(jsonObject.encodePrettily(), UTF_8.toString())
                        .appendBuffer(DELIMITER_BUFFER);
                response.end(encoded);
            } else {
                response.setStatusCode(status).end();
            }

        } else {
            LOGGER.error("Unhandled Exception " + httpServerRequest.path(), e);
            if (httpServerRequest.proxyKeepAliveStarted()) {
                JsonObject jsonObject = new JsonObject().put("code", HTTP_INTERNAL_ERROR);
                Buffer encoded = buffer(jsonObject.encode(), UTF_8.toString()).appendBuffer(DELIMITER_BUFFER);
                response.end(encoded);
            } else {
                response.setStatusCode(HTTP_INTERNAL_ERROR).end();
            }

        }
    } finally {
        httpServerRequest.resume();
    }
}