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

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

Introduction

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

Prototype

public JsonObject(Buffer buf) 

Source Link

Document

Create an instance from a buffer.

Usage

From source file:docoverride.json.Examples.java

License:Open Source License

public void exampleCreateFromMap() {
    Map<String, Object> map = new HashMap<>();
    map.put("foo", "bar");
    map.put("xyz", 3);
    JsonObject object = new JsonObject(map);
}

From source file:enmasse.kafka.bridge.converter.JsonMessageConverter.java

License:Apache License

@Override
public Message toAmqpMessage(String amqpAddress, ConsumerRecord<String, byte[]> record) {

    Message message = Proton.message();/*w  w w.j  a v a 2  s  .  c o  m*/
    message.setAddress(amqpAddress);

    // get the root JSON
    JsonObject json = new JsonObject(new String(record.value()));

    // get AMQP properties from the JSON
    JsonObject jsonProperties = json.getJsonObject(JsonMessageConverter.PROPERTIES);
    if (jsonProperties != null) {

        for (Entry<String, Object> entry : jsonProperties) {

            if (entry.getValue() != null) {

                if (entry.getKey().equals(JsonMessageConverter.MESSAGE_ID)) {
                    message.setMessageId(entry.getValue());
                } else if (entry.getKey().equals(JsonMessageConverter.TO)) {
                    message.setAddress(entry.getValue().toString());
                } else if (entry.getKey().equals(JsonMessageConverter.SUBJECT)) {
                    message.setSubject(entry.getValue().toString());
                } else if (entry.getKey().equals(JsonMessageConverter.REPLY_TO)) {
                    message.setReplyTo(entry.getValue().toString());
                } else if (entry.getKey().equals(JsonMessageConverter.CORRELATION_ID)) {
                    message.setCorrelationId(entry.getValue());
                }
            }
        }
    }

    // get AMQP application properties from the JSON
    JsonObject jsonApplicationProperties = json.getJsonObject(JsonMessageConverter.APPLICATION_PROPERTIES);
    if (jsonApplicationProperties != null) {

        Map<Symbol, Object> applicationPropertiesMap = new HashMap<>();

        for (Entry<String, Object> entry : jsonApplicationProperties) {
            applicationPropertiesMap.put(Symbol.valueOf(entry.getKey()), entry.getValue());
        }

        ApplicationProperties applicationProperties = new ApplicationProperties(applicationPropertiesMap);
        message.setApplicationProperties(applicationProperties);
    }

    // put message annotations about partition, offset and key (if not null)
    Map<Symbol, Object> messageAnnotationsMap = new HashMap<>();
    messageAnnotationsMap.put(Symbol.valueOf(Bridge.AMQP_PARTITION_ANNOTATION), record.partition());
    messageAnnotationsMap.put(Symbol.valueOf(Bridge.AMQP_OFFSET_ANNOTATION), record.offset());
    if (record.key() != null)
        messageAnnotationsMap.put(Symbol.valueOf(Bridge.AMQP_KEY_ANNOTATION), record.key());
    messageAnnotationsMap.put(Symbol.valueOf(Bridge.AMQP_TOPIC_ANNOTATION), record.topic());

    // get AMQP message annotations from the JSON
    JsonObject jsonMessageAnnotations = json.getJsonObject(JsonMessageConverter.MESSAGE_ANNOTATIONS);
    if (jsonMessageAnnotations != null) {

        for (Entry<String, Object> entry : jsonMessageAnnotations) {
            messageAnnotationsMap.put(Symbol.valueOf(entry.getKey()), entry.getValue());
        }
    }

    MessageAnnotations messageAnnotations = new MessageAnnotations(messageAnnotationsMap);
    message.setMessageAnnotations(messageAnnotations);

    // get the AMQP message body from the JSON
    JsonObject jsonBody = json.getJsonObject(JsonMessageConverter.BODY);

    if (jsonBody != null) {

        // type attribtute for following sectin : AMQP value or raw data/binary
        String type = jsonBody.getString(JsonMessageConverter.SECTION_TYPE);

        if (type.equals(JsonMessageConverter.SECTION_AMQP_VALUE_TYPE)) {

            // section is an AMQP value
            Object jsonSection = jsonBody.getValue(JsonMessageConverter.SECTION);

            // encoded as String
            if (jsonSection instanceof String) {
                message.setBody(new AmqpValue(jsonSection));
                // encoded as an array/List
            } else if (jsonSection instanceof JsonArray) {
                JsonArray jsonArray = (JsonArray) jsonSection;
                message.setBody(new AmqpValue(jsonArray.getList()));
                // encoded as a Map
            } else if (jsonSection instanceof JsonObject) {
                JsonObject jsonObject = (JsonObject) jsonSection;
                message.setBody(new AmqpValue(jsonObject.getMap()));
            }

        } else if (type.equals(JsonMessageConverter.SECTION_DATA_TYPE)) {

            // section is a raw binary data

            // get the section from the JSON (it's base64 encoded)
            byte[] value = jsonBody.getBinary(JsonMessageConverter.SECTION);

            message.setBody(new Data(new Binary(Base64.getDecoder().decode(value))));
        }
    }

    return message;
}

From source file:es.upv.grycap.opengateway.core.http.BaseRestService.java

License:Apache License

private void convertSend(final HttpResponse aux, final HttpServerResponse response) {
    if (converter != null) {
        final JsonObject jsonObj = aux.fromString(r -> new JsonObject(r));
        if (jsonObj == null) {
            sendError(404, response);/*from  ww w .  j  a  va 2s. c  om*/
        } else {
            response.putHeader("content-type", "application/json")
                    .end(ofNullable(converter.apply(jsonObj)).orElse(new JsonObject()).encode());
        }
    } else {
        final Buffer buffer = buffer(aux.readByteArray());
        if (buffer.length() == 0) {
            sendError(404, response);
        } else {
            response.putHeader("content-type", "application/json").end(buffer);
        }
    }
}

From source file:es.upv.grycap.opengateway.core.OgDaemon.java

License:Apache License

/**
 * Reads configuration properties and creates the options for the deployment of the services.
 * @return Configuration options for service deployment.
 *///from w  w  w .  j a va2  s  .c om
protected DeploymentOptions createDeploymentOptions() {
    requireNonNull(config);
    // create service options from configuration
    final Map<String, Object> verticleConfig = newHashMap();
    verticleConfig.put("daemon-service.startup-timeout",
            config.getLong("opengateway.daemon-service.startup-timeout"));
    verticleConfig.put("http-server.port", config.getInt("opengateway.http-server.port"));
    verticleConfig.put("cluster.name", config.getString("opengateway.cluster.name"));
    verticleConfig.put("cluster.secret", config.getString("opengateway.cluster.secret"));
    verticleConfig.put("cluster.network", config.getString("opengateway.cluster.network"));
    verticleConfig.put("cluster.public-address", config.getString("opengateway.cluster.public-address"));
    // create deployment options
    return new DeploymentOptions().setInstances(config.getInt("opengateway.http-server.instances"))
            .setConfig(new JsonObject(verticleConfig));
}

From source file:eu.rethink.mn.component.GlobalRegistryConnector.java

License:Apache License

@Override
public void handle(PipeContext ctx) {
    final PipeMessage msg = ctx.getMessage();

    register.getEventBus().send("mn:/global-registry-connector", msg.getJson().encode(), event -> {
        final Object val = event.result().body();
        if (event.succeeded()) {
            //reply: {"123-1":{"catalogAddress":"12345678","guid":"123131241241241","lastUpdate":"2015-11-30"}}

            final PipeMessage replyMsg = new PipeMessage();
            replyMsg.setId(msg.getId());
            replyMsg.setFrom(msg.getTo());
            replyMsg.setTo(msg.getFrom());
            replyMsg.setBody(new JsonObject(val.toString()));
            ctx.reply(replyMsg);/*from  w  w  w  . j  a v a2s  . c o  m*/
        } else {
            ctx.fail(name, "Error contacting domain registry");
        }
    });
}

From source file:eu.rethink.mn.component.RegistryConnector.java

License:Apache License

@Override
public void handle(PipeContext ctx) {
    final PipeMessage msg = ctx.getMessage();
    logger.info("[RegistryConnector.handle]" + msg);

    register.getEventBus().send("mn:/registry-connector", msg.getJson().encode(), event -> {

        if (event.succeeded()) {
            //reply: {"123-1":{"catalogAddress":"12345678","guid":"123131241241241","lastUpdate":"2015-11-30"}}
            final Object val = event.result().body();
            final JsonObject body = new JsonObject(val.toString());
            final int code = body.getInteger("code");

            final PipeMessage replyMsg = new PipeMessage();
            replyMsg.setId(msg.getId());
            replyMsg.setFrom(msg.getTo());
            replyMsg.setTo(msg.getFrom());
            replyMsg.setBody(body);// w  ww  . j  av a 2  s.c om

            switch (code) {

            case 200:
                replyMsg.setReplyCode(ReplyCode.OK);
                break;
            case 404:
                replyMsg.setReplyCode(ReplyCode.NOT_FOUND);
                break;
            case 500:
            default:
                replyMsg.setReplyCode(ReplyCode.ERROR);
                break;
            }

            ctx.reply(replyMsg);
        } else {
            ctx.fail(name, "Error contacting domain registry");
        }
    });
}

From source file:eu.rethink.mn.pipeline.message.PipeMessage.java

License:Apache License

public PipeMessage(String json) {
    this(new JsonObject(json));
}

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

License:Open Source License

private void copyFiles(final HttpServerRequest request, final JsonArray idsArray, final String folder,
        final UserInfos user, final String destinationCollection) {

    String criteria = "{ \"_id\" : { \"$in\" : " + idsArray.encode() + "}";
    criteria += ", \"to\" : \"" + user.getUserId() + "\" }";

    mongo.find(collection, new JsonObject(criteria), new Handler<Message<JsonObject>>() {

        private void persist(final JsonArray insert, int remains) {
            if (remains == 0) {
                mongo.insert(destinationCollection, insert, new Handler<Message<JsonObject>>() {
                    @Override//from  w ww.j a  v  a  2  s .  co m
                    public void handle(Message<JsonObject> inserted) {
                        if ("ok".equals(inserted.body().getString("status"))) {
                            /* Increment quota */
                            long totalSize = 0l;
                            for (Object insertion : insert) {
                                JsonObject added = (JsonObject) insertion;
                                totalSize += added.getJsonObject("metadata", new JsonObject()).getLong("size",
                                        0l);
                            }
                            updateUserQuota(user.getUserId(), totalSize);
                            renderJson(request, inserted.body());
                        } else {
                            renderError(request, inserted.body());
                        }
                    }
                });
            }
        }

        @Override
        public void handle(Message<JsonObject> r) {
            JsonObject src = r.body();
            if ("ok".equals(src.getString("status")) && src.getJsonArray("results") != null) {
                final JsonArray origs = src.getJsonArray("results");
                final JsonArray insert = new JsonArray();
                final AtomicInteger number = new AtomicInteger(origs.size());

                emptySize(user, new Handler<Long>() {

                    @Override
                    public void handle(Long emptySize) {
                        long size = 0;

                        /* Get total file size */
                        for (Object o : origs) {
                            if (!(o instanceof JsonObject))
                                continue;
                            JsonObject metadata = ((JsonObject) o).getJsonObject("metadata");
                            if (metadata != null) {
                                size += metadata.getLong("size", 0l);
                            }
                        }
                        /* If total file size is too big (> quota left) */
                        if (size > emptySize) {
                            badRequest(request, "files.too.large");
                            return;
                        }

                        /* Process */
                        for (Object o : origs) {
                            JsonObject orig = (JsonObject) o;
                            final JsonObject dest = orig.copy();
                            String now = MongoDb.formatDate(new Date());
                            dest.remove("_id");
                            dest.remove("protected");
                            dest.remove("comments");
                            dest.put("application", WORKSPACE_NAME);

                            dest.put("owner", user.getUserId());
                            dest.put("ownerName", dest.getString("toName"));
                            dest.remove("to");
                            dest.remove("from");
                            dest.remove("toName");
                            dest.remove("fromName");

                            dest.put("created", now);
                            dest.put("modified", now);
                            if (folder != null && !folder.trim().isEmpty()) {
                                dest.put("folder", folder);
                            } else {
                                dest.remove("folder");
                            }
                            insert.add(dest);
                            final String filePath = orig.getString("file");

                            if (folder != null && !folder.trim().isEmpty()) {

                                //If the document has a new parent folder, replicate sharing rights
                                String parentName, parentFolder;
                                if (folder.lastIndexOf('_') < 0) {
                                    parentName = folder;
                                    parentFolder = folder;
                                } else if (filePath != null) {
                                    String[] splittedPath = folder.split("_");
                                    parentName = splittedPath[splittedPath.length - 1];
                                    parentFolder = folder;
                                } else {
                                    String[] splittedPath = folder.split("_");
                                    parentName = splittedPath[splittedPath.length - 2];
                                    parentFolder = folder.substring(0, folder.lastIndexOf("_"));
                                }

                                QueryBuilder parentFolderQuery = QueryBuilder.start("owner")
                                        .is(user.getUserId()).and("folder").is(parentFolder).and("name")
                                        .is(parentName);

                                mongo.findOne(collection, MongoQueryBuilder.build(parentFolderQuery),
                                        new Handler<Message<JsonObject>>() {
                                            @Override
                                            public void handle(Message<JsonObject> event) {
                                                if ("ok".equals(event.body().getString("status"))) {
                                                    JsonObject parent = event.body().getJsonObject("result");
                                                    if (parent != null && parent.getJsonArray("shared") != null
                                                            && parent.getJsonArray("shared").size() > 0)
                                                        dest.put("shared", parent.getJsonArray("shared"));

                                                    if (filePath != null) {
                                                        storage.copyFile(filePath, new Handler<JsonObject>() {
                                                            @Override
                                                            public void handle(JsonObject event) {
                                                                if (event != null && "ok"
                                                                        .equals(event.getString("status"))) {
                                                                    dest.put("file", event.getString("_id"));
                                                                    persist(insert, number.decrementAndGet());
                                                                }
                                                            }
                                                        });
                                                    } else {
                                                        persist(insert, number.decrementAndGet());
                                                    }
                                                } else {
                                                    renderJson(request, event.body(), 404);
                                                }
                                            }
                                        });

                            } else if (filePath != null) {
                                storage.copyFile(filePath, new Handler<JsonObject>() {

                                    @Override
                                    public void handle(JsonObject event) {
                                        if (event != null && "ok".equals(event.getString("status"))) {
                                            dest.put("file", event.getString("_id"));
                                            persist(insert, number.decrementAndGet());
                                        }
                                    }
                                });
                            } else {
                                persist(insert, number.decrementAndGet());
                            }
                        }
                    }
                });
            } else {
                notFound(request, src.toString());
            }
        }
    });

}

From source file:fr.wseduc.rack.security.RackResourcesProvider.java

License:Open Source License

private void authorizeOwner(HttpServerRequest request, UserInfos user, final Handler<Boolean> handler) {
    String id = request.params().get("id");
    String matcher = "{ \"_id\": \"" + id + "\", \"to\": \"" + user.getUserId() + "\" }";

    mongo.count(Rack.RACK_COLLECTION, new JsonObject(matcher), new Handler<Message<JsonObject>>() {
        public void handle(Message<JsonObject> result) {
            JsonObject res = result.body();
            handler.handle(res != null && "ok".equals(res.getString("status")) && res.getLong("count") == 1);
        }/*from  w w  w.ja  va 2 s  . c  o  m*/
    });
}

From source file:fr.wseduc.rack.services.RackServiceMongoImpl.java

License:Open Source License

public void recoverRack(String id, Handler<Either<String, JsonObject>> handler) {
    JsonObject modifier = new JsonObject("{ \"$unset\": { \"folder\" : \"\"} }");
    mongo.update(collection, new JsonObject("{ \"_id\": \"" + id + "\" }"), modifier,
            validActionResultHandler(handler));
}