Example usage for io.vertx.core.json JsonArray add

List of usage examples for io.vertx.core.json JsonArray add

Introduction

In this page you can find the example usage for io.vertx.core.json JsonArray add.

Prototype

public JsonArray add(Object value) 

Source Link

Document

Add an Object to the JSON array.

Usage

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

License:Open Source License

private static void getRunningExecutions(final RoutingContext routingContext) {
    final String jobName = routingContext.request().getParam("jobName");
    final JobExecutionEntity[] runningExecutions = JobService.getInstance().getRunningExecutions(jobName);
    final JsonArray jsonArray = new JsonArray();
    for (JobExecutionEntity e : runningExecutions) {
        setJobExecutionEntityHref(routingContext, e);
        jsonArray.add(JsonObject.mapFrom(e));
    }/*from   w w w.java2 s.c  o  m*/
    sendJsonResponse(routingContext, jsonArray.encodePrettily());
}

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

License:Open Source License

private static void getJobExecutions(final RoutingContext routingContext) {
    final String jobExecutionId1String = routingContext.request().getParam("jobExecutionId1");
    final long jobExecutionId1 = jobExecutionId1String == null ? 0 : Long.parseLong(jobExecutionId1String);
    final String countString = routingContext.request().getParam("count");
    final int count = countString == null ? 0 : Integer.parseInt(countString);

    //jobExecutionId1 is used to retrieve the JobInstance, from which to get all its JobExecution's
    //jobInstanceId param is currently not used.
    final JobExecutionEntity[] jobExecutionEntities = JobService.getInstance().getJobExecutions(count, 0,
            jobExecutionId1);//from  ww w.  j  a v  a  2 s  . c o  m
    final JsonArray jsonArray = new JsonArray();
    for (JobExecutionEntity e : jobExecutionEntities) {
        setJobExecutionEntityHref(routingContext, e);
        jsonArray.add(JsonObject.mapFrom(e));
    }
    sendJsonResponse(routingContext, jsonArray.encodePrettily());
}

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

License:Open Source License

private static void getJobInstances(final RoutingContext routingContext) {
    final HttpServerRequest request = routingContext.request();

    final String jobName = request.getParam("jobName");

    final String startString = request.getParam("start");
    final int start = startString == null ? 0 : Integer.parseInt(startString);

    final String countString = request.getParam("count");
    final int count = countString == null ? 0 : Integer.parseInt(countString);

    final String jobExecutionIdString = request.getParam("jobExecutionId");
    final long jobExecutionId = jobExecutionIdString == null ? 0 : Long.parseLong(jobExecutionIdString);

    if (jobExecutionId > 0) {
        final JobInstanceEntity jobInstanceData = JobService.getInstance().getJobInstance(jobExecutionId);
        final JsonObject jsonObject = JsonObject.mapFrom(jobInstanceData);
        sendJsonResponse(routingContext, jsonObject.encodePrettily());
    } else {//from   w ww.  j  ava2 s. c  o m
        final JobInstanceEntity[] jobInstanceData = JobService.getInstance().getJobInstances(
                jobName == null ? "*" : jobName, start, count == 0 ? Integer.MAX_VALUE : count);
        final JsonArray jsonArray = new JsonArray();
        for (JobInstanceEntity e : jobInstanceData) {
            jsonArray.add(JsonObject.mapFrom(e));
        }
        sendJsonResponse(routingContext, jsonArray.encodePrettily());
    }
}

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

License:Open Source License

private static void getJobSchedules(final RoutingContext routingContext) {
    final LocalMap<String, JobSchedule> timerLocalMap = getTimerLocalMap(routingContext.vertx());
    final JsonArray jsonArray = new JsonArray();
    for (JobSchedule jobSchedule : timerLocalMap.values()) {
        jsonArray.add(JsonObject.mapFrom(jobSchedule));
    }/*ww  w  .j a  va 2s . c o m*/
    sendJsonResponse(routingContext, jsonArray.encodePrettily());
}

From source file:org.jboss.weld.vertx.examples.translator.Translator.java

License:Apache License

public void translate(@Observes @VertxConsumer(TRANSLATE) VertxEvent event) {
    String sentence = event.getMessageBody().toString();
    LOGGER.info("Going to translate: " + sentence);

    JsonArray results = new JsonArray();
    for (String word : parser.parse(sentence)) {

        JsonObject result = new JsonObject();
        result.put("word", word);

        List<String> translations = cache.getTranslations(word);
        if (translations != null) {
            result.put("translations", new JsonArray(translations));
        }//  w  w  w. j a  v  a2s .  c o m
        results.add(result);
    }
    event.setReply(results);
}

From source file:org.mustertech.webapp.vertxutils.VerticleDeployer.java

License:Open Source License

public static void deploy(final Vertx vertx, final String cfgJson, Handler<AsyncResult<JsonObject>> handler) {
    if (null == vertx) {
        NullPointerException e = new NullPointerException("NULL vertxutils instance is passed!");
        handler.handle(makeAsyncResult(e, null));

        return;//from   www. ja v a2 s . c o m
    }

    // Store the vertx instance
    VerticleDeployer.vertx = vertx;

    try {
        InputStream schStream = VerticleDeployer.class.getResourceAsStream("/schema/deploy-schema.json");
        StringWriter strWriter = new StringWriter();

        IOUtils.copy(schStream, strWriter, "UTF-8");
        JsonValidator.validateJson(strWriter.toString(), cfgJson);
        IOUtils.closeQuietly(schStream);

        JsonObject cfgObj = new JsonObject(cfgJson);
        JsonObject globalCfg = null;
        JsonObject optObj = null, optCfg = null;
        JsonArray deployOpts = cfgObj.getJsonArray("deployOpts");

        int optsLen = deployOpts.size();
        ArrayList<Promise<JsonObject, Exception, Double>> promises = new ArrayList<Promise<JsonObject, Exception, Double>>();

        if (cfgObj.containsKey("globalConf")) {
            globalCfg = cfgObj.getJsonObject("globalConf");
        }

        for (int idx = 0; idx < optsLen; idx++) {
            optObj = (JsonObject) deployOpts.getJsonObject(idx);

            if (cfgObj.containsKey("appendGlobal") && cfgObj.getBoolean("appendGlobal")) {
                if (optObj.containsKey("config")) {
                    optCfg = optObj.getJsonObject("config");

                    if (!optCfg.containsKey("global")) {
                        optCfg.put("global", globalCfg);
                    }
                } else {
                    optCfg = new JsonObject();

                    optCfg.put("global", globalCfg);
                    optObj.put("config", optCfg);
                }
            }

            promises.add(deployWithOpts(optObj));
        }

        DeferredManager defMgr = new DefaultDeferredManager();

        defMgr.when(promises.toArray(new Promise[] {})).done(new DoneCallback<MultipleResults>() {
            public void onDone(MultipleResults results) {
                JsonArray resArr = new JsonArray();
                Iterator<OneResult> oneResIter = results.iterator();

                while (oneResIter.hasNext()) {
                    resArr.add(oneResIter.next().getResult());
                }

                JsonObject resObj = new JsonObject();
                resObj.put("deployInfo", resArr);

                handler.handle(makeAsyncResult(null, resObj));
            }
        }).fail(new FailCallback<OneReject>() {
            public void onFail(OneReject err) {
                handler.handle(makeAsyncResult((Throwable) err.getReject(), null));
            }
        });
    } catch (Exception e) {
        handler.handle(makeAsyncResult(e, null));
    }
}

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.filesystem.volume.DigestBlob.java

License:Apache License

public JsonObject toJsonObject() {
    JsonObject jsonObject = super.toJsonObject();

    JsonArray jsonDigests = new JsonArray();

    for (Map.Entry<MessageDigestFactory, byte[]> messageDigest : getDigests().entrySet()) {
        MessageDigestFactory algorithm = messageDigest.getKey();
        byte[] digest = messageDigest.getValue();
        JsonObject jsonDigest = new JsonObject().put("name", algorithm.getValue()).put("value", digest);
        jsonDigests.add(jsonDigest);
    }/*  w w w.j  a  v a2 s. co  m*/

    jsonObject.put("X-Computed-Digests", jsonDigests);

    return jsonObject;
}

From source file:org.sfs.metadata.Metadata.java

License:Apache License

public JsonArray toJsonObject() {
    JsonArray metadata = new JsonArray();
    if (!meta.isEmpty()) {
        for (String key : keySet()) {
            SortedSet<String> values = get(key);
            if (!values.isEmpty()) {
                JsonArray valueJsonArray = new JsonArray();
                for (String value : values) {
                    valueJsonArray.add(value);
                }/*w w w. j  a  v a 2  s. c o  m*/
                JsonObject metaObject = new JsonObject();
                metaObject.put("name", key);
                metaObject.put("values", valueJsonArray);

                metadata.add(metaObject);
            }
        }
    }
    return metadata;
}

From source file:org.sfs.nodes.all.stats.GetClusterStats.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(aVoid -> httpServerRequest)
            .map(new ToVoid<>()).map(aVoid -> {
                ClusterInfo clusterInfo = vertxContext.verticle().getClusterInfo();
                JsonArray jsonArray = new JsonArray();
                for (TransientServiceDef node : clusterInfo.getAllNodes()) {
                    jsonArray.add(node.toJsonObject());
                }//from  w w w  . j a v  a 2s.c o  m
                return jsonArray;
            }).single().subscribe(new Terminus<JsonArray>(httpServerRequest) {

                @Override
                public void onNext(JsonArray jsonArray) {
                    Buffer encoded = buffer(jsonArray.encode().getBytes(UTF_8));
                    httpServerRequest.response().setStatusCode(HTTP_OK)
                            .putHeader(CONTENT_LENGTH, valueOf(encoded.length())).write(encoded);
                }
            });

}