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.sfs.nodes.compute.masterkey.VerifyRepairMasterKeys.java

License:Apache License

@Override
public void handle(final SfsRequest httpServerRequest) {

    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();

    Defer.aVoid().flatMap(new Authenticate(httpServerRequest))
            .flatMap(new ValidateActionAdminOrSystem(httpServerRequest)).map(aVoid -> httpServerRequest)
            .map(new ValidateHeaderBetweenLong(Jobs.Parameters.TIMEOUT, 100, Long.MAX_VALUE))
            .map(new ToVoid<>()).flatMap(aVoid -> {
                ClusterInfo clusterInfo = vertxContext.verticle().getClusterInfo();
                Nodes nodes = vertxContext.verticle().nodes();
                MultiMap headers = httpServerRequest.headers();

                long timeout = headers.contains(Jobs.Parameters.TIMEOUT)
                        ? Long.parseLong(headers.get(Jobs.Parameters.TIMEOUT))
                        : 100;//from www  . j  av  a  2 s.c o  m

                MultiMap params = MultiMap.caseInsensitiveMultiMap();

                TransientServiceDef transientServiceDef = clusterInfo.getCurrentMasterNode();
                MasterNode masterNode = nodes.remoteMasterNode(vertxContext, transientServiceDef);

                httpServerRequest.startProxyKeepAlive();

                return masterNode.executeJob(Jobs.ID.REPAIR_MASTER_KEYS, params, timeout,
                        TimeUnit.MILLISECONDS);
            }).single().subscribe(new ConnectionCloseTerminus<Void>(httpServerRequest) {
                @Override
                public void onNext(Void aVoid) {
                    JsonObject responseJson = new JsonObject().put("code", HTTP_OK).put("message", "Success");
                    httpServerRequest.response().write(responseJson.encode(), StandardCharsets.UTF_8.toString())
                            .write(DELIMITER_BUFFER);
                }
            });
}

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

License:Apache License

@Override
public void handle(final SfsRequest httpServerRequest) {

    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();

    Defer.aVoid().flatMap(new Authenticate(httpServerRequest))
            .flatMap(new ValidateActionAdminOrSystem(httpServerRequest)).map(aVoid -> httpServerRequest)
            .map(new ValidateHeaderBetweenLong(Jobs.Parameters.TIMEOUT, 100, Long.MAX_VALUE))
            .map(new ToVoid<>()).map(aVoid -> ObjectPath.fromSfsRequest(httpServerRequest))
            .map(new ValidateObjectPath()).flatMap(objectPath -> {
                ClusterInfo clusterInfo = vertxContext.verticle().getClusterInfo();
                Nodes nodes = vertxContext.verticle().nodes();
                MultiMap headers = httpServerRequest.headers();

                long timeout = headers.contains(Jobs.Parameters.TIMEOUT)
                        ? Long.parseLong(headers.get(Jobs.Parameters.TIMEOUT))
                        : 100;//from  ww  w. jav a  2  s.  com

                String unparsedForceRemoveVolumes = headers.contains(Jobs.Parameters.FORCE_REMOVE_VOLUMES)
                        ? headers.get(Jobs.Parameters.FORCE_REMOVE_VOLUMES)
                        : null;

                MultiMap params = MultiMap.caseInsensitiveMultiMap();
                if (unparsedForceRemoveVolumes != null) {
                    params.add(Jobs.Parameters.FORCE_REMOVE_VOLUMES, unparsedForceRemoveVolumes);
                }
                params.set(Jobs.Parameters.OBJECT_ID, objectPath.objectPath().get());

                TransientServiceDef transientServiceDef = clusterInfo.getCurrentMasterNode();
                MasterNode masterNode = nodes.remoteMasterNode(vertxContext, transientServiceDef);

                httpServerRequest.startProxyKeepAlive();

                return masterNode.executeJob(Jobs.ID.VERIFY_REPAIR_OBJECT, params, timeout,
                        TimeUnit.MILLISECONDS);
            }).single().subscribe(new ConnectionCloseTerminus<Void>(httpServerRequest) {
                @Override
                public void onNext(Void aVoid) {
                    JsonObject responseJson = new JsonObject().put("code", HTTP_OK).put("message", "Success");
                    httpServerRequest.response().write(responseJson.encode(), StandardCharsets.UTF_8.toString())
                            .write(DELIMITER_BUFFER);
                }
            });
}

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

License:Apache License

@Override
public void handle(final SfsRequest httpServerRequest) {

    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();

    Defer.aVoid().flatMap(new Authenticate(httpServerRequest))
            .flatMap(new ValidateActionAdminOrSystem(httpServerRequest)).map(aVoid -> httpServerRequest)
            .map(new ValidateHeaderExists(Jobs.Parameters.TIMEOUT))
            .map(new ValidateHeaderBetweenLong(Jobs.Parameters.TIMEOUT, 100, Long.MAX_VALUE))
            .map(new ToVoid<>()).map(aVoid -> ObjectPath.fromSfsRequest(httpServerRequest))
            .map(new ValidateObjectPath()).flatMap(objectPath -> {
                ClusterInfo clusterInfo = vertxContext.verticle().getClusterInfo();
                Nodes nodes = vertxContext.verticle().nodes();
                MultiMap headers = httpServerRequest.headers();

                long timeout = headers.contains(Jobs.Parameters.TIMEOUT)
                        ? Long.parseLong(headers.get(Jobs.Parameters.TIMEOUT))
                        : -1;//ww w  .ja  v a2s . co m

                TransientServiceDef transientServiceDef = clusterInfo.getCurrentMasterNode();
                MasterNode masterNode = nodes.remoteMasterNode(vertxContext, transientServiceDef);

                httpServerRequest.startProxyKeepAlive();

                return masterNode.stopJob(Jobs.ID.VERIFY_REPAIR_OBJECT, timeout, TimeUnit.MILLISECONDS);
            }).single().subscribe(new ConnectionCloseTerminus<Void>(httpServerRequest) {
                @Override
                public void onNext(Void aVoid) {
                    JsonObject responseJson = new JsonObject().put("code", HTTP_OK).put("message", "Success");
                    httpServerRequest.response().write(responseJson.encode(), StandardCharsets.UTF_8.toString())
                            .write(DELIMITER_BUFFER);
                }
            });
}

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

License:Apache License

@Override
public void handle(final SfsRequest httpServerRequest) {

    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();

    Defer.aVoid().flatMap(new Authenticate(httpServerRequest))
            .flatMap(new ValidateActionAdminOrSystem(httpServerRequest)).map(aVoid -> httpServerRequest)
            .map(new ValidateHeaderExists(Jobs.Parameters.TIMEOUT))
            .map(new ValidateHeaderBetweenLong(Jobs.Parameters.TIMEOUT, 100, Long.MAX_VALUE))
            .map(new ToVoid<>()).map(aVoid -> ObjectPath.fromSfsRequest(httpServerRequest))
            .map(new ValidateObjectPath()).flatMap(objectPath -> {
                ClusterInfo clusterInfo = vertxContext.verticle().getClusterInfo();
                Nodes nodes = vertxContext.verticle().nodes();
                MultiMap headers = httpServerRequest.headers();

                long timeout = headers.contains(Jobs.Parameters.TIMEOUT)
                        ? Long.parseLong(headers.get(Jobs.Parameters.TIMEOUT))
                        : -1;//  w  w  w  .j  a  v  a 2 s . c  o  m

                TransientServiceDef transientServiceDef = clusterInfo.getCurrentMasterNode();
                MasterNode masterNode = nodes.remoteMasterNode(vertxContext, transientServiceDef);

                httpServerRequest.startProxyKeepAlive();

                return masterNode.waitForJob(Jobs.ID.VERIFY_REPAIR_OBJECT, timeout, TimeUnit.MILLISECONDS);
            }).single().subscribe(new ConnectionCloseTerminus<Void>(httpServerRequest) {
                @Override
                public void onNext(Void aVoid) {
                    JsonObject responseJson = new JsonObject().put("code", HTTP_OK).put("message", "Success");
                    httpServerRequest.response().write(responseJson.encode(), StandardCharsets.UTF_8.toString())
                            .write(DELIMITER_BUFFER);
                }
            });
}

From source file:org.sfs.nodes.data.ChecksumBlob.java

License:Apache License

@Override
public void handle(final SfsRequest httpServerRequest) {

    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();

    aVoid().flatMap(new Authenticate(httpServerRequest))
            .flatMap(new ValidateActionAdminOrSystem(httpServerRequest))
            .map(new ValidateNodeIsDataNode<>(vertxContext)).map(aVoid -> httpServerRequest)
            .map(new ValidateParamExists(VOLUME)).map(new ValidateParamExists(POSITION))
            .map(new ValidateParamBetweenLong(POSITION, 0, MAX_VALUE))
            .map(new ValidateParamBetweenLong(LENGTH, 0, MAX_VALUE))
            .map(new ValidateParamBetweenLong(OFFSET, 0, MAX_VALUE)).map(new ValidateParamComputedDigest())
            .flatMap(httpServerRequest1 -> {
                MultiMap params = httpServerRequest1.params();

                final Iterable<MessageDigestFactory> iterable = from(params.names())
                        .transform(new Function<String, Optional<MessageDigestFactory>>() {
                            @Override
                            public Optional<MessageDigestFactory> apply(String param) {
                                Matcher matcher = COMPUTED_DIGEST.matcher(param);
                                if (matcher.matches()) {
                                    String digestName = matcher.group(1);
                                    return fromValueIfExists(digestName);
                                }/*from   www  . j a va  2  s  .c  om*/
                                return absent();
                            }
                        }).filter(Optional::isPresent).transform(input -> input.get());

                MultiMap queryParams = httpServerRequest1.params();

                String volumeId = queryParams.get(VOLUME);
                long position = parseLong(queryParams.get(POSITION));

                Optional<Long> oOffset;
                if (queryParams.contains(OFFSET)) {
                    oOffset = of(parseLong(queryParams.get(OFFSET)));
                } else {
                    oOffset = absent();
                }

                Optional<Long> oLength;
                if (queryParams.contains(LENGTH)) {
                    oLength = of(parseLong(queryParams.get(LENGTH)));
                } else {
                    oLength = absent();
                }

                // let the client know we're alive by sending pings on the response stream
                httpServerRequest1.startProxyKeepAlive();

                LocalNode localNode = new LocalNode(vertxContext,
                        vertxContext.verticle().nodes().volumeManager());

                return localNode
                        .checksum(volumeId, position, oOffset, oLength,
                                toArray(iterable, MessageDigestFactory.class))
                        .map(digestBlobOptional -> new Holder2<>(httpServerRequest1, digestBlobOptional));
            }).flatMap(holder -> httpServerRequest.stopKeepAlive().map(aVoid -> holder))
            .onErrorResumeNext(throwable -> httpServerRequest.stopKeepAlive()
                    .flatMap(aVoid -> Observable.<Holder2<SfsRequest, Optional<DigestBlob>>>error(throwable)))
            .single().onErrorResumeNext(new HandleServerToBusy<>())
            .subscribe(new Terminus<Holder2<SfsRequest, Optional<DigestBlob>>>(httpServerRequest) {
                @Override
                public void onNext(Holder2<SfsRequest, Optional<DigestBlob>> holder) {
                    Optional<DigestBlob> oJsonDigestBlob = holder.value1();
                    JsonObject jsonResponse = new JsonObject();
                    if (oJsonDigestBlob.isPresent()) {
                        jsonResponse.put("code", HTTP_OK).put("blob", oJsonDigestBlob.get().toJsonObject());
                    } else {
                        jsonResponse.put("code", HTTP_NOT_FOUND);
                    }
                    HttpServerResponse httpResponse = holder.value0().response();
                    httpResponse.write(jsonResponse.encode(), UTF_8.toString()).write(DELIMITER_BUFFER);
                }
            });

}

From source file:org.sfs.nodes.data.PutBlob.java

License:Apache License

@Override
public void handle(final SfsRequest httpServerRequest) {

    httpServerRequest.pause();/* w w w .j a v  a  2  s  .  co m*/

    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();

    aVoid().flatMap(new Authenticate(httpServerRequest))
            .flatMap(new ValidateActionAdminOrSystem(httpServerRequest))
            .map(new ValidateNodeIsDataNode<>(vertxContext)).map(aVoid -> httpServerRequest)
            .map(new ValidateParamExists(VOLUME)).map(new ValidateHeaderExists(CONTENT_LENGTH))
            .map(new ValidateHeaderBetweenLong(CONTENT_LENGTH, 0, MAX_VALUE))
            .map(new ValidateParamComputedDigest()).map(new ToVoid<>()).map(aVoid -> httpServerRequest)
            .flatMap(httpServerRequest1 -> {

                MultiMap headers = httpServerRequest1.headers();
                MultiMap params = httpServerRequest1.params();

                String volumeId = params.get(VOLUME);

                final Iterable<MessageDigestFactory> iterable = from(params.names())
                        .transform(new Function<String, Optional<MessageDigestFactory>>() {
                            @Override
                            public Optional<MessageDigestFactory> apply(String param) {
                                Matcher matcher = COMPUTED_DIGEST.matcher(param);
                                if (matcher.find()) {
                                    String digestName = matcher.group(1);
                                    return fromValueIfExists(digestName);
                                }
                                return absent();
                            }
                        }).filter(Optional::isPresent).transform(input -> input.get());

                VolumeManager volumeManager = vertxContext.verticle().nodes().volumeManager();

                if (!volumeManager.isOpen()) {
                    throw new HttpStatusCodeException("VolumeManager not open", HTTP_UNAVAILABLE);
                }

                Volume volume = volumeManager.get(volumeId).orNull();

                if (volume == null) {
                    throw new HttpStatusCodeException(String.format("Volume %s not found", volumeId),
                            HTTP_UNAVAILABLE);
                }

                if (!Volume.Status.STARTED.equals(volume.status())) {
                    throw new HttpStatusCodeException(String.format("Volume %s not started", volumeId),
                            HTTP_UNAVAILABLE);
                }

                long length = parseLong(headers.get(CONTENT_LENGTH));

                httpServerRequest1.startProxyKeepAlive();

                return volume.putDataStream(httpServerRequest1.vertxContext().vertx(), length)
                        .flatMap(writeStreamBlob -> {

                            DigestReadStream digestReadStream = new DigestReadStream(httpServerRequest1,
                                    toArray(iterable, MessageDigestFactory.class));
                            CountingReadStream countingReadStream = new CountingReadStream(digestReadStream);
                            return writeStreamBlob.consume(countingReadStream).map(aVoid1 -> {
                                DigestBlob digestBlob = new DigestBlob(writeStreamBlob.getVolume(),
                                        writeStreamBlob.getPosition(), countingReadStream.count());
                                for (Holder2<MessageDigestFactory, byte[]> digest : digestReadStream
                                        .digests()) {
                                    digestBlob.withDigest(digest.value0(), digest.value1());
                                }
                                return new Holder2<>(httpServerRequest1, of(digestBlob));
                            });
                        });

            }).single().onErrorResumeNext(new HandleServerToBusy<>())
            .subscribe(new Terminus<Holder2<SfsRequest, Optional<DigestBlob>>>(httpServerRequest) {

                @Override
                public void onNext(Holder2<SfsRequest, Optional<DigestBlob>> holder) {
                    Optional<DigestBlob> oJsonDigestBlob = holder.value1();
                    JsonObject jsonResponse = new JsonObject();
                    if (oJsonDigestBlob.isPresent()) {
                        jsonResponse.put("code", HTTP_OK).put("blob", oJsonDigestBlob.get().toJsonObject());
                    } else {
                        jsonResponse.put("code", HTTP_INTERNAL_ERROR);
                    }
                    HttpServerResponse httpResponse = holder.value0().response();
                    httpResponse.write(jsonResponse.encode(), UTF_8.toString()).write(DELIMITER_BUFFER);
                }
            });

}

From source file:org.sfs.nodes.master.MasterNodeExecuteJob.java

License:Apache License

@Override
public void handle(SfsRequest httpServerRequest) {

    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();

    Defer.aVoid().flatMap(new Authenticate(httpServerRequest))
            .flatMap(new ValidateActionAdminOrSystem(httpServerRequest))
            .map(new ValidateNodeIsMasterNode<>(vertxContext)).map(aVoid -> httpServerRequest)
            .map(new ValidateHeaderExists(Jobs.Parameters.JOB_ID))
            .map(new ValidateHeaderBetweenLong(Jobs.Parameters.TIMEOUT, 100, Long.MAX_VALUE))
            .map(new ToVoid<>()).flatMap(aVoid -> {

                MultiMap headers = httpServerRequest.headers();
                String jobId = headers.get(JOB_ID);

                long timeout = headers.contains(Jobs.Parameters.TIMEOUT)
                        ? Long.parseLong(headers.get(Jobs.Parameters.TIMEOUT))
                        : -1;//from  w  ww.  ja  va  2s .  c om

                httpServerRequest.startProxyKeepAlive();

                Jobs jobs = vertxContext.verticle().jobs();
                return Defer.aVoid().doOnNext(
                        aVoid1 -> jobs.execute(vertxContext, jobId, headers).subscribe(new NullSubscriber<>()))
                        .flatMap(aVoid1 -> {
                            if (timeout >= 0) {
                                return jobs.waitStopped(vertxContext, jobId, timeout, TimeUnit.MILLISECONDS);
                            } else {
                                return Defer.aVoid();
                            }
                        });
            }).single().subscribe(new Terminus<Void>(httpServerRequest) {

                @Override
                public void onNext(Void aVoid) {
                    JsonObject responseJson = new JsonObject().put("code", HTTP_OK).put("message", "Success");
                    httpServerRequest.response().write(responseJson.encode(), StandardCharsets.UTF_8.toString())
                            .write(DELIMITER_BUFFER);
                }
            });
}

From source file:org.sfs.nodes.master.MasterNodeStopJob.java

License:Apache License

@Override
public void handle(SfsRequest httpServerRequest) {

    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();

    Defer.aVoid().flatMap(new Authenticate(httpServerRequest))
            .flatMap(new ValidateActionAdminOrSystem(httpServerRequest))
            .map(new ValidateNodeIsMasterNode<>(vertxContext)).map(aVoid -> httpServerRequest)
            .map(new ValidateHeaderExists(Jobs.Parameters.JOB_ID))
            .map(new ValidateHeaderBetweenLong(Jobs.Parameters.TIMEOUT, 100, Long.MAX_VALUE))
            .map(new ToVoid<>()).flatMap(aVoid -> {

                MultiMap headers = httpServerRequest.headers();

                long timeout = headers.contains(Jobs.Parameters.TIMEOUT)
                        ? Long.parseLong(headers.get(Jobs.Parameters.TIMEOUT))
                        : -1;/*w  w  w.j  ava2  s.com*/

                String jobId = headers.get(Jobs.Parameters.JOB_ID);

                httpServerRequest.startProxyKeepAlive();

                Jobs jobs = vertxContext.verticle().jobs();
                return Defer.aVoid().flatMap(aVoid1 -> jobs.stop(vertxContext, jobId)).flatMap(aVoid1 -> {
                    if (timeout >= 0) {
                        return jobs.waitStopped(vertxContext, jobId, timeout, TimeUnit.MILLISECONDS);
                    } else {
                        return Defer.aVoid();
                    }
                });
            }).single().subscribe(new Terminus<Void>(httpServerRequest) {

                @Override
                public void onNext(Void aVoid) {
                    JsonObject responseJson = new JsonObject().put("code", HTTP_OK).put("message", "Success");
                    httpServerRequest.response().write(responseJson.encode(), StandardCharsets.UTF_8.toString())
                            .write(DELIMITER_BUFFER);
                }
            });
}

From source file:org.sfs.nodes.master.MasterNodeWaitForJob.java

License:Apache License

@Override
public void handle(SfsRequest httpServerRequest) {

    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();

    Defer.aVoid().flatMap(new Authenticate(httpServerRequest))
            .flatMap(new ValidateActionAdminOrSystem(httpServerRequest))
            .map(new ValidateNodeIsMasterNode<>(vertxContext)).map(aVoid -> httpServerRequest)
            .map(new ValidateHeaderExists(Jobs.Parameters.JOB_ID))
            .map(new ValidateHeaderBetweenLong(Jobs.Parameters.TIMEOUT, 100, Long.MAX_VALUE))
            .map(new ToVoid<>()).flatMap(aVoid -> {

                MultiMap headers = httpServerRequest.headers();

                long timeout = headers.contains(Jobs.Parameters.TIMEOUT)
                        ? Long.parseLong(headers.get(Jobs.Parameters.TIMEOUT))
                        : -1;/*from  ww  w.j a v a  2s .com*/

                String jobId = headers.get(Jobs.Parameters.JOB_ID);

                httpServerRequest.startProxyKeepAlive();

                Jobs jobs = vertxContext.verticle().jobs();
                return Defer.aVoid().flatMap(aVoid1 -> {
                    if (timeout >= 0) {
                        return jobs.waitStopped(vertxContext, jobId, timeout, TimeUnit.MILLISECONDS);
                    } else {
                        return Defer.aVoid();
                    }
                });
            }).single().subscribe(new Terminus<Void>(httpServerRequest) {

                @Override
                public void onNext(Void aVoid) {
                    JsonObject responseJson = new JsonObject().put("code", HTTP_OK).put("message", "Success");
                    httpServerRequest.response().write(responseJson.encode(), StandardCharsets.UTF_8.toString())
                            .write(DELIMITER_BUFFER);
                }
            });
}

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

License:Apache License

@Override
public void onError(Throwable e) {
    JsonObject document = new JsonObject();
    HttpServerResponse response = httpServerRequest.response();
    if (e instanceof HttpRequestValidationException) {
        HttpRequestValidationException cause = (HttpRequestValidationException) e;
        JsonObject entity = cause.getEntity();
        int status = cause.getStatusCode();

        LOGGER.debug("Validate Error", e);
        document.put("status", status).put("message", entity.encode());

    } else if (e instanceof HttpStatusCodeException) {
        HttpStatusCodeException cause = (HttpStatusCodeException) e;

        LOGGER.debug("HttpStatusCode Error", e);
        document.put("status", cause.getStatusCode());

    } else {/*ww  w.  j  a va 2 s  . c  o  m*/
        LOGGER.error("Unhandled Exception", e);
        document.put("status", HTTP_INTERNAL_ERROR);
    }
    response.end(document.encode(), UTF_8.toString());
}