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.sfs.nodes.compute.account.GetAccount.java

License:Apache License

@Override
public void handle(final SfsRequest httpServerRequest) {

    aVoid().flatMap(new Authenticate(httpServerRequest))
            .flatMap(new ValidateActionAuthenticated(httpServerRequest))
            .map(aVoid -> fromSfsRequest(httpServerRequest)).map(new ValidateAccountPath())
            .map(objectPath -> objectPath.accountPath().get())
            .flatMap(new LoadAccount(httpServerRequest.vertxContext()))
            .map(new ValidatePersistentAccountExists()).flatMap(new ListContainers(httpServerRequest))
            .flatMap(containerList -> {
                HttpServerResponse httpServerResponse = httpServerRequest.response();
                MultiMap headerParams = httpServerRequest.headers();
                MultiMap queryParams = httpServerRequest.params();
                String format = queryParams.get(FORMAT);

                String accept = headerParams.get(ACCEPT);

                Account account = containerList.getAccount();

                Metadata metadata = account.getMetadata();

                for (String key : metadata.keySet()) {
                    SortedSet<String> values = metadata.get(key);
                    if (values != null && !values.isEmpty()) {
                        httpServerResponse.putHeader(format("%s%s", X_ADD_ACCOUNT_META_PREFIX, key), values);
                    }//  w  w  w.  j av  a2s.co m
                }

                httpServerResponse.putHeader(X_ACCOUNT_OBJECT_COUNT, valueOf(containerList.getObjectCount()));
                httpServerResponse.putHeader(X_ACCOUNT_CONTAINER_COUNT,
                        valueOf(containerList.getContainerCount()));
                httpServerResponse.putHeader(X_ACCOUNT_BYTES_USED,
                        BigDecimal.valueOf(containerList.getBytesUsed()).setScale(0, ROUND_HALF_UP).toString());

                MediaType parsedAccept = null;
                if (!isNullOrEmpty(accept)) {
                    parsedAccept = parse(accept);
                }

                if (equalsIgnoreCase("xml", format)) {
                    parsedAccept = APPLICATION_XML_UTF_8;
                } else if (equalsIgnoreCase("json", format)) {
                    parsedAccept = JSON_UTF_8;
                }

                httpServerResponse.setStatusCode(HTTP_OK);

                if (parsedAccept != null && JSON_UTF_8.is(parsedAccept)) {
                    String charset = UTF_8.toString();

                    JsonArray array = new JsonArray();

                    for (SparseContainer container : ordered(containerList.getContainers())) {

                        array.add(new JsonObject().put("name", container.getContainerName())
                                .put("count", container.getObjectCount())
                                .put("bytes", BigDecimal.valueOf(container.getByteCount())
                                        .setScale(0, ROUND_HALF_UP).longValue()));

                    }

                    Buffer buffer = buffer(array.encode(), charset);
                    httpServerResponse = httpServerResponse.putHeader(CONTENT_TYPE, JSON_UTF_8.toString());
                    httpServerResponse = httpServerResponse.putHeader(CONTENT_LENGTH, valueOf(buffer.length()));
                    return AsyncIO.append(buffer, httpServerResponse);

                } else if (parsedAccept != null && APPLICATION_XML_UTF_8.is(parsedAccept)) {

                    BufferOutputStream bufferOutputStream = new BufferOutputStream();
                    String charset = UTF_8.toString();
                    XMLStreamWriter writer = null;
                    try {
                        writer = newFactory().createXMLStreamWriter(bufferOutputStream, charset);

                        writer.writeStartDocument(charset, "1.0");

                        writer.writeStartElement("account");

                        writer.writeAttribute("name", fromPaths(account.getId()).accountName().get());

                        for (SparseContainer container : ordered(containerList.getContainers())) {

                            writer.writeStartElement("container");

                            writer.writeStartElement("name");
                            writer.writeCharacters(container.getContainerName());
                            writer.writeEndElement();

                            writer.writeStartElement("count");
                            writer.writeCharacters(valueOf(container.getObjectCount()));
                            writer.writeEndElement();

                            writer.writeStartElement("bytes");
                            writer.writeCharacters(BigDecimal.valueOf(container.getByteCount())
                                    .setScale(0, ROUND_HALF_UP).toString());
                            writer.writeEndElement();

                            writer.writeEndElement();
                        }

                        writer.writeEndElement();

                        writer.writeEndDocument();

                    } catch (XMLStreamException e) {
                        throw new RuntimeException(e);
                    } finally {
                        try {
                            if (writer != null) {
                                writer.close();
                            }
                        } catch (XMLStreamException e) {
                            LOGGER.warn(e.getLocalizedMessage(), e);
                        }
                    }

                    Buffer buffer = bufferOutputStream.toBuffer();
                    httpServerResponse = httpServerResponse.putHeader(CONTENT_TYPE,
                            APPLICATION_XML_UTF_8.toString());
                    httpServerResponse = httpServerResponse.putHeader(CONTENT_LENGTH, valueOf(buffer.length()));
                    return AsyncIO.append(buffer, httpServerResponse);

                } else {
                    String charset = UTF_8.toString();
                    Buffer buffer = buffer();
                    for (SparseContainer container : ordered(containerList.getContainers())) {
                        buffer.appendString(container.getContainerName(), charset);
                        buffer.appendString("\n", charset);
                    }
                    httpServerResponse = httpServerResponse.putHeader(CONTENT_TYPE,
                            PLAIN_TEXT_UTF_8.toString());
                    httpServerResponse = httpServerResponse.putHeader(CONTENT_LENGTH, valueOf(buffer.length()));
                    return AsyncIO.append(buffer, httpServerResponse);
                }
            }).single().subscribe(new ConnectionCloseTerminus<Void>(httpServerRequest) {

                @Override
                public void onNext(Void aVoid) {

                }

            });

}

From source file:org.sfs.util.HttpServerRequestHeaderToJsonObject.java

License:Apache License

public static JsonObject call(HttpServerRequest httpServerRequest) {
    JsonObject jsonObject = new JsonObject();

    String query = httpServerRequest.query();
    String requestLine = String.format("%s %s%s %s", httpServerRequest.method(), httpServerRequest.path(),
            query != null ? '?' + query : "", httpServerRequest.version().toString());
    jsonObject.put("request_line", requestLine);
    MultiMap headers = httpServerRequest.headers();
    JsonArray jsonHeaders = new JsonArray();
    for (String headerName : headers.names()) {
        List<String> values = headers.getAll(headerName);
        JsonObject jsonHeader = new JsonObject();
        jsonHeader.put(headerName, values);
        jsonHeaders.add(jsonHeader);
    }/* w ww. j  a v a2  s.  co  m*/
    jsonObject.put("headers", jsonHeaders);
    return jsonObject;
}

From source file:org.sfs.vo.LargeObjectManifest.java

License:Apache License

public JsonArray toJsonObject() {
    JsonArray entryJsonArray = new JsonArray();
    for (Entry entry : entries) {
        entryJsonArray.add(entry.toJsonObject());
    }//from  ww w  .j  a  v  a 2  s  .  co m
    return entryJsonArray;
}

From source file:org.sfs.vo.Segment.java

License:Apache License

public JsonObject toJsonObject() {
    JsonObject document = new JsonObject();
    document.put("id", id);
    document.put("read_md5", readMd5);
    document.put("read_sha512", readSha512);
    document.put("read_length", readLength);
    document.put("write_sha512", writeSha512);
    document.put("write_length", writeLength);
    document.put("tiny_data", tinyData);
    document.put("is_tiny_data", TRUE.equals(isTinyData));
    document.put("is_tiny_data_deleted", TRUE.equals(isTinyDataDeleted));
    if (tinyData != null) {
        checkState(TRUE.equals(isTinyData), "isTinyData must be set to true");
        checkState(blobs == null || blobs.isEmpty(), "blobs must be empty when tinyData exists");
    }// w  w  w  .  j  av  a 2 s  .c o  m
    if (blobs != null && !blobs.isEmpty()) {
        checkState(!TRUE.equals(isTinyData), "isTinyData must be set to false");
        checkState(tinyData == null, "tinyData must be empty when blobs exist");
    }

    if (segmentCipher != null) {
        document = document.put("container_key_id", segmentCipher.containerKeyId).put("cipher_salt",
                segmentCipher.salt);
    } else {
        document.put("container_key_id", (String) null).put("cipher_salt", (byte[]) null);
    }

    JsonArray blobJsonArray = new JsonArray();
    for (TransientBlobReference transientBlobReference : blobs) {
        blobJsonArray.add(transientBlobReference.toJsonObject());
    }
    document.put("blobs", blobJsonArray);
    return document;
}

From source file:org.sfs.vo.ServiceDef.java

License:Apache License

public JsonObject toJsonObject() {
    JsonObject jsonObject = new JsonObject().put("id", id).put("update_ts", toDateTimeString(getLastUpdate()))
            .put("master_node", master).put("data_node", dataNode).put("document_count", documentCount)
            .put("available_processors", availableProcessors).put("free_memory", freeMemory)
            .put("max_memory", maxMemory).put("total_memory", totalMemory);

    if (fileSystem != null) {
        JsonObject jsonFileSystem = fileSystem.toJsonObject();
        jsonObject = jsonObject.put("file_system", jsonFileSystem);
    }//from   w  ww.  ja va2s . c  om

    JsonArray jsonListeners = new JsonArray();
    for (HostAndPort publishAddress : publishAddresses) {
        jsonListeners.add(publishAddress.toString());
    }
    jsonObject.put("publish_addresses", jsonListeners);

    JsonArray jsonVolumes = new JsonArray();
    for (XVolume<? extends XVolume> xVolume : volumes) {
        jsonVolumes.add(xVolume.toJsonObject());
    }
    jsonObject.put("volumes", jsonVolumes);
    return jsonObject;
}

From source file:org.sfs.vo.XObject.java

License:Apache License

public JsonObject toJsonObject() {
    JsonObject document = new JsonObject();

    checkState(parent != null, "container cannot be null");
    checkState(parent.getParent() != null, "account cannot be null");

    document.put("account_id", parent.getParent().getId());
    document.put("container_id", parent.getId());
    document.put("node_id", nodeId);
    document.put("owner_guid", ownerGuid);

    JsonArray versionsJsonArray = new JsonArray();
    for (TransientVersion transientVersion : versions) {
        versionsJsonArray.add(transientVersion.toJsonObject());
    }// www .  j a  v a 2  s  . c  o  m
    document.put("versions", versionsJsonArray);
    document.put("version_count", versions.size());
    Optional<TransientVersion> oOldestVersion = getOldestVersion();
    if (oOldestVersion.isPresent()) {
        document.put("oldest_version_ts", toDateTimeString(oOldestVersion.get().getCreateTs()));
    } else {
        document.put("oldest_version_ts", (String) null);
    }

    document.put("create_ts", toDateTimeString(getCreateTs()));
    document.put("update_ts", toDateTimeString(getUpdateTs()));

    return document;
}

From source file:org.sfs.vo.XVersion.java

License:Apache License

public JsonObject toJsonObject() {
    JsonObject document = new JsonObject();
    document.put("id", id);
    document.put("deleted", deleted);
    document.put("verified", size(readableSegments()) == segments.size());
    document.put("delete_marker", deleteMarker);

    document.put("etag", etag);
    document.put("content_md5", contentMd5);
    document.put("content_sha512", contentSha512);
    document.put("content_type", contentType);
    document.put("content_encoding", contentEncoding);
    document.put("content_disposition", contentDisposition);
    document.put("content_length", contentLength);
    document.put("server_side_encryption", useServerSideEncryption());
    document.put("object_manifest", objectManifest);
    document.put("static_large_object", staticLargeObject);
    document.put("delete_at", deleteAt);

    JsonArray jsonSegments = new JsonArray();
    for (TransientSegment segment : segments) {
        JsonObject segmentDocument = segment.toJsonObject();
        jsonSegments.add(segmentDocument);
    }/*from   w  ww. java  2s.c  o  m*/
    document.put("segments", jsonSegments);

    document.put("metadata", getMetadata().toJsonObject());

    document.put("create_ts", toDateTimeString(getCreateTs()));

    document.put("update_ts", toDateTimeString(getUpdateTs()));

    return document;
}

From source file:org.sub.bug.entity.BugConverter.java

License:Apache License

public static void toJson(Bug obj, JsonObject json) {
    if (obj.getBugDateClosed() != null) {
        json.put("bugDateClosed", obj.getBugDateClosed());
    }/*from ww w .j  a  v a  2  s .  co  m*/
    if (obj.getBugDateReported() != null) {
        json.put("bugDateReported", obj.getBugDateReported());
    }
    if (obj.getBugDescription() != null) {
        json.put("bugDescription", obj.getBugDescription());
    }
    if (obj.getBugDeveloper() != null) {
        json.put("bugDeveloper", obj.getBugDeveloper().toJson());
    }
    if (obj.getBugId() != null) {
        json.put("bugId", obj.getBugId());
    }
    if (obj.getBugReporter() != null) {
        json.put("bugReporter", obj.getBugReporter());
    }
    if (obj.getModule() != null) {
        json.put("module", obj.getModule());
    }
    if (obj.getModuleName() != null) {
        json.put("moduleName", obj.getModuleName());
    }
    if (obj.getProblemLogs() != null) {
        JsonArray array = new JsonArray();
        obj.getProblemLogs().forEach(item -> array.add(item.toJson()));
        json.put("problemLogs", array);
    }
}

From source file:se.liquidbytes.jel.owfs.OwfsAdapter.java

License:Apache License

/**
 * Returns a list of all supported devices by this adapter.
 *
 * @param message eventbus message./* ww  w  . ja  v a  2s.  co m*/
 */
private void getSupportedDevices(Message message) {

    JsonArray result = new JsonArray();

    for (JsonObject device : DeviceDatabase.getSuportedDeviceTypes()) {
        result.add(new JsonObject().put("typeId", device.getString("typeId"))
                .put("name", device.getString("name")).put("description", device.getString("description"))
                .put("manufacturer", device.getJsonObject("manufacturer")));
    }

    message.reply(constructReply(result));
}

From source file:se.liquidbytes.jel.owfs.OwfsAdapter.java

License:Apache License

/**
 * Returns a list of all available devices on 1-wire bus.
 *
 * @return list of devices./*  www. ja  v  a2  s. com*/
 */
private JsonArray getAvailableDevices() {
    JsonArray result = new JsonArray();

    List<JsonObject> deviceList = deviceLookup.values().stream()
            .sorted(comparing((JsonObject d) -> d.getString("type"))
                    .thenComparing((JsonObject d) -> d.getString("name")))
            .collect(Collectors.toList());
    for (JsonObject device : deviceList) {
        result.add(new JsonObject().put("hwId", device.getString("hwId")).put("type", device.getString("type"))
                .put("name", device.getString("name")));
    }

    return result;
}