Example usage for com.google.gson JsonArray add

List of usage examples for com.google.gson JsonArray add

Introduction

In this page you can find the example usage for com.google.gson JsonArray add.

Prototype

public void add(JsonElement element) 

Source Link

Document

Adds the specified element to self.

Usage

From source file:com.goodow.realtime.server.rpc.PollHandler.java

License:Apache License

private JsonArray fetchDeltas(JsonArray ids, String sessionId)
        throws IOException, SlobNotFoundException, AccessDeniedException {
    JsonArray msgs = new JsonArray();
    SlobStore store = slobFacilities.getSlobStore();
    String token = null;/*from   w  ww . j  a  va2  s. c o  m*/
    for (JsonElement elem : ids) {
        JsonArray array = elem.getAsJsonArray();
        ObjectId key = new ObjectId(array.get(0).getAsString());
        long startRev = array.get(1).getAsLong();
        Long endVersion = array.size() >= 3 ? array.get(2).getAsLong() : null;

        ConnectResult r = null;
        try {
            r = store.reconnect(key, new Session(context.get().getAccountInfo().getUserId(), sessionId));
        } catch (SlobNotFoundException e) {
            if (startRev == 1) {
                continue;
            }
            throw e;
        }
        if (r.getChannelToken() != null) {
            assert token == null || token.equals(r.getChannelToken());
            token = r.getChannelToken();
        }
        JsonObject msg = new JsonObject();
        msg.addProperty(Params.ID, key.toString());
        boolean isEmpty = deltaHandler.fetchDeltas(msg, key, startRev - 1, endVersion);
        if (!isEmpty) {
            msgs.add(msg);
        }
    }
    if (token != null) {
        JsonObject tokenMsg = new JsonObject();
        tokenMsg.addProperty(Params.ID, Params.TOKEN);
        tokenMsg.addProperty(Params.TOKEN, token);
        msgs.add(tokenMsg);
    }
    return msgs;
}

From source file:com.goodow.wind.server.rpc.DeltaHandler.java

License:Apache License

private JsonObject fetchHistories(SessionId sid, JsonArray keys)
        throws IOException, SlobNotFoundException, AccessDeniedException {
    SlobStore store = slobFacilities.getSlobStore();
    JsonObject toRtn = new JsonObject();
    JsonArray msgs = new JsonArray();
    String token = null;/*from ww  w . j av  a  2  s.c  o m*/
    for (JsonElement e : keys) {
        JsonObject obj = e.getAsJsonObject();
        ObjectId key = new ObjectId(obj.get(Params.ID).getAsString());
        long version = obj.get(Params.VERSION).getAsLong();
        Long endVersion = obj.has(Params.END_VERSION) ? obj.get(Params.END_VERSION).getAsLong() : null;
        ConnectResult r = store.reconnect(key, sid);
        JsonObject msg;
        if (r.getChannelToken() != null) {
            assert token == null || token.equals(r.getChannelToken());
            token = r.getChannelToken();
        }
        HistoryResult history = store.loadHistory(key, version, endVersion);
        msg = LocalMutationProcessor.jsonBroadcastData(key.toString(),
                serializeHistory(version, history.getData()));
        msg.addProperty(Params.VERSION, r.getVersion());
        msgs.add(msg);
    }
    if (token != null) {
        toRtn.addProperty(Params.TOKEN, token);
    }
    toRtn.add(Params.DELTAS, msgs);
    return toRtn;
}

From source file:com.goodow.wind.server.rpc.DeltaHandler.java

License:Apache License

private JsonArray serializeHistory(long startVersion, List<Delta<String>> entries) {
    JsonArray history = new JsonArray();
    int index = 0;
    for (Delta<String> data : entries) {
        history.add(DeltaSerializer.dataToClientJson(data, startVersion + index + 1));
        index++;/*from   w ww . jav a2 s. c  o m*/
    }
    return history;
}

From source file:com.google.api.ads.adwords.keywordoptimizer.api.JsonUtil.java

License:Open Source License

/**
 * Initializes Gson to convert objects to and from JSON. This method customizes a "plain" Gson by
 * adding appropriate exclusions strategies / adapters as needed in this project for a "pretty"
 * output. /*www .jav  a  2 s  .co m*/
 */
private static Gson initGson(boolean prettyPrint) {
    GsonBuilder builder = new GsonBuilder();

    // Exclude superclasses.
    ExclusionStrategy superclassExclusionStrategy = new SuperclassExclusionStrategy();
    builder.addDeserializationExclusionStrategy(superclassExclusionStrategy);
    builder.addSerializationExclusionStrategy(superclassExclusionStrategy);

    // Exclude underscore fields in client lib objects.
    ExclusionStrategy underscoreExclusionStrategy = new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes field) {
            if (field.getName().startsWith("_")) {
                return true;
            }

            return false;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    };
    builder.addDeserializationExclusionStrategy(underscoreExclusionStrategy);
    builder.addSerializationExclusionStrategy(underscoreExclusionStrategy);

    // Render KeywordCollection as an array of KeywordInfos.
    builder.registerTypeAdapter(KeywordCollection.class, new JsonSerializer<KeywordCollection>() {
        @Override
        public JsonElement serialize(KeywordCollection src, java.lang.reflect.Type typeOfSrc,
                JsonSerializationContext context) {
            JsonArray out = new JsonArray();
            for (KeywordInfo info : src.getListSortedByScore()) {
                out.add(context.serialize(info));
            }
            return out;
        }
    });
    // Render Money as a primitive.
    builder.registerTypeAdapter(Money.class, new JsonSerializer<Money>() {
        @Override
        public JsonElement serialize(Money src, java.lang.reflect.Type typeOfSrc,
                JsonSerializationContext context) {
            JsonElement out = new JsonPrimitive(src.getMicroAmount() / 1000000);
            return out;
        }
    });
    // Render Keyword in a simple way.
    builder.registerTypeAdapter(Keyword.class, new JsonSerializer<Keyword>() {
        @Override
        public JsonElement serialize(Keyword src, java.lang.reflect.Type typeOfSrc,
                JsonSerializationContext context) {
            JsonObject out = new JsonObject();
            out.addProperty("text", src.getText());
            out.addProperty("matchtype", src.getMatchType().toString());
            return out;
        }
    });
    // Render Throwable in a simple way (for all subclasses).
    builder.registerTypeHierarchyAdapter(Throwable.class, new JsonSerializer<Throwable>() {
        @Override
        public JsonElement serialize(Throwable src, java.lang.reflect.Type typeOfSrc,
                JsonSerializationContext context) {
            JsonObject out = new JsonObject();
            out.addProperty("message", src.getMessage());
            out.addProperty("type", src.getClass().getName());

            JsonArray stack = new JsonArray();
            for (StackTraceElement stackTraceElement : src.getStackTrace()) {
                JsonObject stackElem = new JsonObject();
                stackElem.addProperty("file", stackTraceElement.getFileName());
                stackElem.addProperty("line", stackTraceElement.getLineNumber());
                stackElem.addProperty("method", stackTraceElement.getMethodName());
                stackElem.addProperty("class", stackTraceElement.getClassName());
                stack.add(stackElem);
            }
            out.add("stack", stack);

            if (src.getCause() != null) {
                out.add("cause", context.serialize(src.getCause()));
            }
            return out;
        }
    });

    if (prettyPrint) {
        builder.setPrettyPrinting();
    }

    return builder.create();
}

From source file:com.google.cloud.solutions.sampleapps.orchestration.orchestrator.server.GceInstanceCreator.java

License:Open Source License

/**
 * Makes the payload for creating an instance.
 *
 * @param instanceName the name of the instance.
 * @return the payload for the POST request to create a new instance.
 *//*w  ww.  j ava2  s  .c o  m*/
String createPayload_instance(String instanceName, String bootDiskName, Map<String, String> configProperties) {
    JsonObject json = new JsonObject();
    json.addProperty("kind", "compute#instance");
    json.addProperty("name", instanceName);
    json.addProperty("machineType", ConfigProperties.urlPrefixWithProjectAndZone + "/machineTypes/"
            + configProperties.get("machineType"));

    JsonObject disksElem = new JsonObject();
    disksElem.addProperty("kind", "compute#attachedDisk");
    disksElem.addProperty("boot", true);
    disksElem.addProperty("type", "PERSISTENT");
    disksElem.addProperty("mode", "READ_WRITE");
    disksElem.addProperty("deviceName", bootDiskName);
    disksElem.addProperty("zone", ConfigProperties.urlPrefixWithProjectAndZone);
    disksElem.addProperty("source", ConfigProperties.urlPrefixWithProjectAndZone + "/disks/" + bootDiskName);

    JsonArray jsonAr = new JsonArray();
    jsonAr.add(disksElem);
    json.add("disks", jsonAr);

    JsonObject networkInterfacesObj = new JsonObject();
    networkInterfacesObj.addProperty("kind", "compute#instanceNetworkInterface");
    networkInterfacesObj.addProperty("network",
            ConfigProperties.urlPrefixWithProject + "/global/networks/default");

    JsonObject accessConfigsObj = new JsonObject();
    accessConfigsObj.addProperty("name", "External NAT");
    accessConfigsObj.addProperty("type", "ONE_TO_ONE_NAT");
    JsonArray accessConfigsAr = new JsonArray();
    accessConfigsAr.add(accessConfigsObj);
    networkInterfacesObj.add("accessConfigs", accessConfigsAr);

    JsonArray networkInterfacesAr = new JsonArray();
    networkInterfacesAr.add(networkInterfacesObj);
    json.add("networkInterfaces", networkInterfacesAr);

    JsonObject serviceAccountsObj = new JsonObject();
    serviceAccountsObj.addProperty("kind", "compute#serviceAccount");
    serviceAccountsObj.addProperty("email", "default");
    JsonArray scopesAr = new JsonArray();
    scopesAr.add(new JsonPrimitive("https://www.googleapis.com/auth/userinfo.email"));
    scopesAr.add(new JsonPrimitive("https://www.googleapis.com/auth/compute"));
    scopesAr.add(new JsonPrimitive("https://www.googleapis.com/auth/devstorage.full_control"));
    serviceAccountsObj.add("scopes", scopesAr);
    JsonArray serviceAccountsAr = new JsonArray();
    serviceAccountsAr.add(serviceAccountsObj);
    json.add("serviceAccounts", serviceAccountsAr);

    JsonObject metadataObj = new JsonObject();

    JsonArray mdItemsAr = new JsonArray();
    JsonObject mdItemsObj = new JsonObject();
    mdItemsObj.addProperty("key", "startup-script-url");
    mdItemsObj.addProperty("value", configProperties.get("startupScript"));
    mdItemsAr.add(mdItemsObj);
    metadataObj.add("items", mdItemsAr);
    json.add("metadata", metadataObj);
    String payload = json.toString();
    return payload;
}

From source file:com.google.cloud.solutions.sampleapps.orchestration.orchestrator.server.InstanceStatusServlet.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    JsonArray jsonAr = new JsonArray();
    Map<String, String> gceIpsAndInstanceNames = orchestrator.getGceIpsAndInstanceNames();
    resp.setContentType("application/json");
    resp.setHeader("Cache-Control", "no-cache");
    for (String gceIp : gceIpsAndInstanceNames.keySet()) {
        try {/*from www . ja va 2 s.c om*/
            // Query each instance for its status/load.
            URL url = new URL("http://" + gceIp + ":8080/StatusPublisher/status");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            GceStats gceStats = gson.fromJson(reader, GceStats.class);
            reader.close();
            JsonObject instanceElem = new JsonObject();
            instanceElem.addProperty("instanceName", gceIpsAndInstanceNames.get(gceIp));
            instanceElem.addProperty("status", gson.toJson(gceStats));
            jsonAr.add(instanceElem);
        } catch (MalformedURLException e) {
            logger.warning("Malformed URL: " + e);
        } catch (IOException e) {
            logger.warning("Can't open stream: " + e);
        }
    }
    PrintWriter writer = resp.getWriter();
    writer.println(gson.toJson(jsonAr));
}

From source file:com.google.dart.server.generated.types.AnalysisErrorFixes.java

License:Open Source License

public JsonObject toJson() {
    JsonObject jsonObject = new JsonObject();
    jsonObject.add("error", error.toJson());
    JsonArray jsonArrayFixes = new JsonArray();
    for (SourceChange elt : fixes) {
        jsonArrayFixes.add(elt.toJson());
    }/*  www.ja  v  a  2 s.c  om*/
    jsonObject.add("fixes", jsonArrayFixes);
    return jsonObject;
}

From source file:com.google.dart.server.generated.types.ChangeContentOverlay.java

License:Open Source License

public JsonObject toJson() {
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("type", type);
    JsonArray jsonArrayEdits = new JsonArray();
    for (SourceEdit elt : edits) {
        jsonArrayEdits.add(elt.toJson());
    }/*from w ww . ja  va 2 s .c  o  m*/
    jsonObject.add("edits", jsonArrayEdits);
    return jsonObject;
}

From source file:com.google.dart.server.generated.types.CompletionSuggestion.java

License:Open Source License

public JsonObject toJson() {
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("kind", kind);
    jsonObject.addProperty("relevance", relevance);
    jsonObject.addProperty("completion", completion);
    jsonObject.addProperty("selectionOffset", selectionOffset);
    jsonObject.addProperty("selectionLength", selectionLength);
    jsonObject.addProperty("isDeprecated", isDeprecated);
    jsonObject.addProperty("isPotential", isPotential);
    if (docSummary != null) {
        jsonObject.addProperty("docSummary", docSummary);
    }/*from w  ww.  java  2s  . c  o  m*/
    if (docComplete != null) {
        jsonObject.addProperty("docComplete", docComplete);
    }
    if (declaringType != null) {
        jsonObject.addProperty("declaringType", declaringType);
    }
    if (element != null) {
        jsonObject.add("element", element.toJson());
    }
    if (returnType != null) {
        jsonObject.addProperty("returnType", returnType);
    }
    if (parameterNames != null) {
        JsonArray jsonArrayParameterNames = new JsonArray();
        for (String elt : parameterNames) {
            jsonArrayParameterNames.add(new JsonPrimitive(elt));
        }
        jsonObject.add("parameterNames", jsonArrayParameterNames);
    }
    if (parameterTypes != null) {
        JsonArray jsonArrayParameterTypes = new JsonArray();
        for (String elt : parameterTypes) {
            jsonArrayParameterTypes.add(new JsonPrimitive(elt));
        }
        jsonObject.add("parameterTypes", jsonArrayParameterTypes);
    }
    if (requiredParameterCount != null) {
        jsonObject.addProperty("requiredParameterCount", requiredParameterCount);
    }
    if (hasNamedParameters != null) {
        jsonObject.addProperty("hasNamedParameters", hasNamedParameters);
    }
    if (parameterName != null) {
        jsonObject.addProperty("parameterName", parameterName);
    }
    if (parameterType != null) {
        jsonObject.addProperty("parameterType", parameterType);
    }
    if (importUri != null) {
        jsonObject.addProperty("importUri", importUri);
    }
    return jsonObject;
}

From source file:com.google.dart.server.generated.types.ExtractLocalVariableFeedback.java

License:Open Source License

public JsonObject toJson() {
    JsonObject jsonObject = new JsonObject();
    JsonArray jsonArrayNames = new JsonArray();
    for (String elt : names) {
        jsonArrayNames.add(new JsonPrimitive(elt));
    }// w w w. j  a  v  a  2  s . c o m
    jsonObject.add("names", jsonArrayNames);
    JsonArray jsonArrayOffsets = new JsonArray();
    for (int elt : offsets) {
        jsonArrayOffsets.add(new JsonPrimitive(elt));
    }
    jsonObject.add("offsets", jsonArrayOffsets);
    JsonArray jsonArrayLengths = new JsonArray();
    for (int elt : lengths) {
        jsonArrayLengths.add(new JsonPrimitive(elt));
    }
    jsonObject.add("lengths", jsonArrayLengths);
    return jsonObject;
}