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

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

Introduction

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

Prototype

public int size() 

Source Link

Document

Get the number of entries in the JSON object

Usage

From source file:com.cyngn.vertx.opentsdb.service.OpenTsDbService.java

License:Apache License

private boolean hasInvalidTags(JsonObject tags) {
    return tags != null && options.getDefaultTagCount() + tags.size() > options.getMaxTags();
}

From source file:com.cyngn.vertx.opentsdb.Util.java

License:Apache License

/**
 * Take config specified tags and make a OpenTsDb tag string
 *
 * @param tags the map of tags to convert to their string form
 * @return list of tags in opentsdb format ie 'name1=value1 name2=value2'
 *///from  w ww  .j a  v a  2 s .  c  o m
public static String createTagsFromJson(JsonObject tags) {
    String tagsString = "";
    if (tags != null && tags.size() > 0) {
        StringBuilder builder = new StringBuilder();
        for (String key : tags.fieldNames()) {
            builder.append(key).append("=").append(tags.getString(key)).append(" ");
        }
        // if necessary, grab all but the last character, since it's always a space
        if (builder.length() > 0) {
            tagsString = builder.substring(0, builder.length() - 1);
        } else {
            tagsString = builder.toString();
        }
    }

    return tagsString;
}

From source file:com.cyngn.vertx.opentsdb.Util.java

License:Apache License

/**
 * Create a metric object for sending to the OpenTsDb lib
 *
 * @param name the metric name/*from w ww. j a va2s .  co m*/
 * @param value the metric value
 * @param tags the tags to associate to this metric
 * @return the properly constructed metric object
 */
public static JsonObject createMetric(String name, String value, JsonObject tags) {
    JsonObject obj = new JsonObject().put(OpenTsDbService.ACTION_FIELD, OpenTsDbService.ADD_COMMAND)
            .put(MetricsParser.NAME_FIELD, name).put(MetricsParser.VALUE_FIELD, value);
    if (tags != null && tags.size() > 0) {
        obj.put(MetricsParser.TAGS_FIELD, tags);
    }
    return obj;
}

From source file:com.cyngn.vertx.opentsdb.Util.java

License:Apache License

/**
 * Create a metric object for sending to the OpenTsDb lib but with no implicit command
 *
 * @param name the metric name//from   ww  w  .ja  v  a2  s.  c  o m
 * @param value the metric value
 * @param tags the tags to associate to this metric
 * @return the properly constructed metric object
 */
public static JsonObject createRawMetric(String name, String value, JsonObject tags) {
    JsonObject obj = new JsonObject().put(MetricsParser.NAME_FIELD, name).put(MetricsParser.VALUE_FIELD, value);
    if (tags != null && tags.size() > 0) {
        obj.put(MetricsParser.TAGS_FIELD, tags);
    }
    return obj;
}

From source file:com.groupon.vertx.memcache.MemcacheClusterConfig.java

License:Apache License

public MemcacheClusterConfig(JsonObject jsonConfig) {
    if (jsonConfig == null) {
        log.error("initialize", "exception", "noConfigFound");
        throw new MemcacheException("No Memcache cluster config found");
    }/*from  w w  w .  j a  va 2  s .c  o  m*/

    this.eventBusAddressPrefix = jsonConfig.getString(EVENT_BUS_ADDRESS_PREFIX_KEY);
    this.retryInterval = jsonConfig.getLong(RETRY_INTERVAL, MemcacheConfig.DEFAULT_RETRY_INTERVAL);
    JsonObject clusters = jsonConfig.getJsonObject(CLUSTERS_KEY, new JsonObject());

    if (eventBusAddressPrefix != null && !eventBusAddressPrefix.isEmpty() && clusters.size() > 0) {
        for (String clusterKey : clusters.fieldNames()) {
            JsonObject clusterConfig = clusters.getJsonObject(clusterKey, new JsonObject()).copy();
            clusterConfig.put(EVENT_BUS_ADDRESS_KEY, eventBusAddressPrefix);
            clusterConfig.put(RETRY_INTERVAL, retryInterval);
            clusterMap.put(clusterKey, new MemcacheConfig(clusterConfig));
        }
    } else {
        log.error("initialize", "exception", "invalidConfigFound", new String[] { "config" },
                jsonConfig.encode());
        throw new MemcacheException("Invalid Memcache config defined");
    }

    log.info("initialize", "success", new String[] { "eventBusAddressPrefix", "clusters" },
            eventBusAddressPrefix, clusterMap.size());
}

From source file:com.groupon.vertx.redis.RedisCommand.java

License:Apache License

/**
 * If the command represented by the JsonObject doesn't come in the form:
 * <br>/*from  w  w w.j  a va 2 s .  c o m*/
 * <code>
 * {
 *   'command': 'GET',
 *   'arguments': [ 'somekey' ]
 * }
 * </code>
 * <br>
 * Then an exception will be thrown.
 *
 * @param commandJson - The command to be created.
 */
public RedisCommand(JsonObject commandJson) {
    if (commandJson == null || commandJson.size() != 2) {
        log.warn("initRedisCommand", "failure", new String[] { "reason" }, "Invalid command format");
        throw new IllegalArgumentException("Invalid command format");
    }

    try {
        type = RedisCommandType.valueOf(commandJson.getString("command"));
    } catch (Exception ex) {
        log.warn("initRedisCommand", "failure", new String[] { "reason" }, "Invalid command");
        throw new IllegalArgumentException("Invalid or unsupported command provided");
    }

    Object objectArguments = commandJson.getValue("arguments");
    if (objectArguments != null) {
        if (objectArguments instanceof JsonArray) {
            for (Object arg : (JsonArray) objectArguments) {
                if (arg instanceof String) {
                    arguments.add((String) arg);
                } else {
                    arguments.add(arg.toString());
                }
            }
        } else {
            arguments.add(objectArguments.toString());
        }
    }
}

From source file:fr.wseduc.rack.controllers.RackController.java

License:Open Source License

/**
 * Post a new document to other people's rack folder.
 * @param request Client request containing a list of user ids belonging to the receivers and the file.
 *//*from   w  w w .j  a  v a  2s.c o  m*/
@Post("")
@SecuredAction(send)
public void postRack(final HttpServerRequest request) {
    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override
        public void handle(final UserInfos userInfos) {

            if (userInfos == null) {
                badRequest(request);
                return;
            }

            request.setExpectMultipart(true);
            final Buffer fileBuffer = Buffer.buffer();
            final JsonObject metadata = new JsonObject();

            /* Upload file */
            request.uploadHandler(getUploadHandler(fileBuffer, metadata, request));

            /* After upload */
            request.endHandler(new Handler<Void>() {
                @Override
                public void handle(Void v) {
                    String users = request.formAttributes().get("users");
                    if (users == null) {
                        badRequest(request);
                        return;
                    }

                    String[] userIds = users.split(",");

                    final AtomicInteger countdown = new AtomicInteger(userIds.length);
                    final AtomicInteger success = new AtomicInteger(0);
                    final AtomicInteger failure = new AtomicInteger(0);

                    /* Final handler - called after each attempt */
                    final Handler<Boolean> finalHandler = new Handler<Boolean>() {
                        @Override
                        public void handle(Boolean event) {
                            if (event == null || !event)
                                failure.addAndGet(1);
                            else
                                success.addAndGet(1);
                            if (countdown.decrementAndGet() == 0) {
                                JsonObject result = new JsonObject();
                                result.put("success", success.get());
                                result.put("failure", failure.get());
                                renderJson(request, result);
                            }
                        }
                    };

                    for (final String to : userIds) {
                        /* Query user and check existence */
                        String query = "MATCH (n:User) " + "WHERE n.id = {id} "
                                + "RETURN count(n) as nb, n.displayName as username";
                        Map<String, Object> params = new HashMap<>();
                        params.put("id", to);

                        Handler<Message<JsonObject>> existenceHandler = new Handler<Message<JsonObject>>() {
                            @Override
                            public void handle(Message<JsonObject> res) {
                                JsonArray result = res.body().getJsonArray("result");

                                if (!"ok".equals(res.body().getString("status")) || 1 != result.size()
                                        || 1 != result.getJsonObject(0).getInteger("nb")) {
                                    finalHandler.handle(false);
                                    return;
                                }

                                /* Pre write rack document fields */
                                final JsonObject doc = new JsonObject();
                                doc.put("to", to);
                                doc.put("toName", result.getJsonObject(0).getString("username"));
                                doc.put("from", userInfos.getUserId());
                                doc.put("fromName", userInfos.getUsername());
                                String now = dateFormat.format(new Date());
                                doc.put("sent", now);

                                /* Rack collection saving */
                                final Handler<JsonObject> rackSaveHandler = new Handler<JsonObject>() {
                                    @Override
                                    public void handle(JsonObject uploaded) {
                                        if (uploaded == null || !"ok".equals(uploaded.getString("status"))) {
                                            finalHandler.handle(false);
                                        } else {
                                            addAfterUpload(uploaded.put("metadata", metadata), doc,
                                                    request.params().get("name"),
                                                    request.params().get("application"),
                                                    request.params().getAll("thumbnail"),
                                                    new Handler<Message<JsonObject>>() {
                                                        @Override
                                                        public void handle(Message<JsonObject> res) {
                                                            if ("ok".equals(res.body().getString("status"))) {
                                                                JsonObject params = new JsonObject()
                                                                        .put("uri",
                                                                                "/userbook/annuaire#"
                                                                                        + doc.getString("from"))
                                                                        .put("resourceUri", pathPrefix)
                                                                        .put("username",
                                                                                doc.getString("fromName"))
                                                                        .put("documentName",
                                                                                doc.getString("name"));
                                                                List<String> receivers = new ArrayList<>();
                                                                receivers.add(doc.getString("to"));

                                                                JsonObject pushNotif = new JsonObject()
                                                                        .put("title",
                                                                                "rack.push.notif.rack-post")
                                                                        .put("body",
                                                                                I18n.getInstance().translate(
                                                                                        "rack.push.notif.rack-post.body",
                                                                                        getHost(request),
                                                                                        I18n.acceptLanguage(
                                                                                                request),
                                                                                        doc.getString(
                                                                                                "fromName"),
                                                                                        doc.getString("name")));
                                                                params.put("pushNotif", pushNotif);

                                                                timelineHelper.notifyTimeline(request,
                                                                        "rack.rack-post", userInfos, receivers,
                                                                        userInfos.getUserId()
                                                                                + System.currentTimeMillis()
                                                                                + "postrack",
                                                                        null, params, true);
                                                                finalHandler.handle(true);
                                                            } else {
                                                                finalHandler.handle(false);
                                                            }
                                                        }
                                                    });
                                        }
                                    }
                                };

                                /* Get user quota & check */
                                getUserQuota(to, new Handler<JsonObject>() {
                                    @Override
                                    public void handle(JsonObject j) {
                                        if (j == null || "error".equals(j.getString("status"))) {
                                            finalHandler.handle(false);
                                            return;
                                        }

                                        long emptySize = 0l;
                                        long quota = j.getLong("quota", 0l);
                                        long storage = j.getLong("storage", 0l);
                                        emptySize = quota - storage;
                                        if (emptySize < metadata.getLong("size", 0l)) {
                                            finalHandler.handle(false);
                                            return;
                                        }
                                        //Save file
                                        RackController.this.storage.writeBuffer(fileBuffer,
                                                metadata.getString("content-type"), metadata.getString("name"),
                                                rackSaveHandler);
                                    }
                                });

                            }
                        };
                        Neo4j.getInstance().execute(query, params, existenceHandler);
                    }
                }
            });
        }
    });
}

From source file:io.silverware.microservices.providers.cdi.internal.RestInterface.java

License:Apache License

@SuppressWarnings("checkstyle:JavadocMethod")
public void callMethod(final RoutingContext routingContext) {
    final String microserviceName = routingContext.request().getParam("microservice");
    final String methodName = routingContext.request().getParam("method");
    final Bean bean = gatewayRegistry.get(microserviceName);

    routingContext.request().bodyHandler(buffer -> {
        final JsonObject mainJsonObject = new JsonObject(buffer.toString());

        try {// ww w  .j  av a 2 s  .  c  o  m
            final Class<?> beanClass = bean.getBeanClass();
            List<Method> methods = Arrays.asList(beanClass.getDeclaredMethods()).stream()
                    .filter(method -> method.getName().equals(methodName)
                            && method.getParameterCount() == mainJsonObject.size())
                    .collect(Collectors.toList());

            if (methods.size() == 0) {
                throw new IllegalStateException(
                        String.format("No such method %s with compatible parameters.", methodName));
            }

            if (methods.size() > 1) {
                throw new IllegalStateException("Overridden methods are not supported yet.");
            }

            final Method m = methods.get(0);

            final Parameter[] methodParams = m.getParameters();
            final Object[] paramValues = new Object[methodParams.length];
            final ConvertUtilsBean convert = new ConvertUtilsBean();
            for (int i = 0; i < methodParams.length; i++) {
                final Parameter methodParameter = methodParams[i];
                final String paramName = getParamName(methodParameter, m, beanClass);
                final Object jsonObject = mainJsonObject.getValue(paramName);
                paramValues[i] = convert.convert(jsonObject, methodParameter.getType());
            }

            @SuppressWarnings("unchecked")
            Set<Object> services = context.lookupLocalMicroservice(
                    new MicroserviceMetaData(microserviceName, beanClass, bean.getQualifiers()));
            JsonObject response = new JsonObject();
            try {
                Object result = m.invoke(services.iterator().next(), paramValues);
                response.put("result", Json.encodePrettily(result));
                response.put("resultPlain", JsonWriter.objectToJson(result));
            } catch (Exception e) {
                response.put("exception", e.toString());
                response.put("stackTrace", stackTraceAsString(e));
                log.warn("Could not call method: ", e);
            }

            routingContext.response().end(response.encodePrettily());
        } catch (Exception e) {
            log.warn(String.format("Unable to call method %s#%s: ", microserviceName, methodName), e);
            routingContext.response().setStatusCode(503).end("Resource not available.");
        }
    });
}

From source file:org.entcore.auth.Auth.java

License:Open Source License

@Override
public void start() throws Exception {
    final EventBus eb = getEventBus(vertx);
    super.start();
    setDefaultResourceFilter(new AuthResourcesProvider(new Neo(vertx, eb, null)));

    final UserAuthAccount userAuthAccount = new DefaultUserAuthAccount(vertx, config);
    final EventStore eventStore = EventStoreFactory.getFactory().getEventStore(Auth.class.getSimpleName());

    AuthController authController = new AuthController();
    authController.setEventStore(eventStore);
    authController.setUserAuthAccount(userAuthAccount);
    addController(authController);//  w ww  .  java 2 s  .co  m

    final ConfigurationController configurationController = new ConfigurationController();
    configurationController.setConfigurationService(new DefaultConfigurationService());
    addController(configurationController);

    final String samlMetadataFolder = config.getString("saml-metadata-folder");
    if (samlMetadataFolder != null && !samlMetadataFolder.trim().isEmpty()) {
        vertx.fileSystem().readDir(samlMetadataFolder, new Handler<AsyncResult<List<String>>>() {
            @Override
            public void handle(AsyncResult<List<String>> event) {
                if (event.succeeded() && event.result().size() > 0) {
                    try {
                        SamlController samlController = new SamlController();
                        JsonObject conf = config;

                        vertx.deployVerticle(SamlValidator.class,
                                new DeploymentOptions().setConfig(conf).setWorker(true));
                        samlController.setEventStore(eventStore);
                        samlController.setUserAuthAccount(userAuthAccount);
                        samlController.setServiceProviderFactory(new DefaultServiceProviderFactory(
                                config.getJsonObject("saml-services-providers")));
                        samlController
                                .setSignKey((String) vertx.sharedData().getLocalMap("server").get("signKey"));
                        samlController.setSamlWayfParams(config.getJsonObject("saml-wayf"));
                        samlController.setIgnoreCallBackPattern(config.getString("ignoreCallBackPattern"));
                        addController(samlController);
                        LocalMap<Object, Object> server = vertx.sharedData().getLocalMap("server");
                        if (server != null) {
                            String loginUri = config.getString("loginUri");
                            String callbackParam = config.getString("callbackParam");
                            if (loginUri != null && !loginUri.trim().isEmpty()) {
                                server.putIfAbsent("loginUri", loginUri);
                            }
                            if (callbackParam != null && !callbackParam.trim().isEmpty()) {
                                server.putIfAbsent("callbackParam", callbackParam);
                            }
                            final JsonObject authLocations = config.getJsonObject("authLocations");
                            if (authLocations != null && authLocations.size() > 0) {
                                server.putIfAbsent("authLocations", authLocations.encode());
                            }
                        }
                    } catch (ConfigurationException e) {
                        log.error("Saml loading error.", e);
                    }
                }
            }
        });
    }
    final JsonObject openidFederate = config.getJsonObject("openid-federate");
    final JsonObject openidConnect = config.getJsonObject("openid-connect");
    final OpenIdConnectController openIdConnectController;
    if (openidFederate != null || openidConnect != null) {
        openIdConnectController = new OpenIdConnectController();
        addController(openIdConnectController);
    } else {
        openIdConnectController = null;
    }
    if (openidConnect != null) {
        final String certsPath = openidConnect.getString("certs");
        if (isNotEmpty(certsPath)) {
            JWT.listCertificates(vertx, certsPath, new Handler<JsonObject>() {
                @Override
                public void handle(JsonObject certs) {
                    openIdConnectController.setCertificates(certs);
                }
            });
        }
    }
    if (openidFederate != null) {
        openIdConnectController.setEventStore(eventStore);
        openIdConnectController.setUserAuthAccount(userAuthAccount);
        openIdConnectController.setSignKey((String) vertx.sharedData().getLocalMap("server").get("signKey"));
        openIdConnectController.setOpenIdConnectServiceProviderFactory(
                new DefaultOpenIdServiceProviderFactory(vertx, openidFederate.getJsonObject("domains")));
        openIdConnectController.setSubMapping(openidFederate.getBoolean("authorizeSubMapping", false));

        final JsonArray authorizedHostsLogin = openidFederate.getJsonArray("authorizedHostsLogin");
        if (authorizedHostsLogin != null && authorizedHostsLogin.size() > 0) {
            authController.setAuthorizedHostsLogin(authorizedHostsLogin);
        }
    }
}

From source file:org.entcore.auth.controllers.SamlController.java

License:Open Source License

/**
 * End of acs method : authenticate user if not already connectd through IDP ENT
 *
 * @param request request from "/acs" method
 * @param event event from SamlServiceProvider.execute(...)
 * @param sessionIndex sessionIndex get from acs assertion
 * @param nameId nameID get from acs assertion
 *///from   w  w  w. jav a 2s .c  o m
private void endAcs(final HttpServerRequest request, Either<String, Object> event, final String sessionIndex,
        final String nameId) {
    if (event.right().getValue() != null && event.right().getValue() instanceof JsonObject) {
        final JsonObject res = (JsonObject) event.right().getValue();
        if (res.size() == 0) {
            loginResult(request, "fed.auth.error.user.not.found");
        } else {
            authenticate(res, sessionIndex, nameId, request);
        }
    } else if (event.right().getValue() != null && event.right().getValue() instanceof JsonArray
            && isNotEmpty(signKey)) {
        try {
            JsonObject params = getUsersWithSignatures((JsonArray) event.right().getValue(), sessionIndex,
                    nameId);
            renderView(request, params, "selectFederatedUser.html", null);
        } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
            log.error("Error signing federated users.", e);
            redirect(request, LOGIN_PAGE);
        }
    } else {
        redirect(request, LOGIN_PAGE);
    }
}