Example usage for com.google.gson JsonArray JsonArray

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

Introduction

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

Prototype

public JsonArray() 

Source Link

Document

Creates an empty JsonArray.

Usage

From source file:com.gmail.tracebachi.DeltaSkins.Shared.Storage.PlayerProfileStorage.java

License:Open Source License

@Override
public JsonArray serialize() {
    JsonArray array = new JsonArray();

    synchronized (profileMap) {
        for (PlayerProfile profile : profileMap.values()) {
            array.add(profile.serialize());
        }//from w  ww.  j  a va  2 s.  c o  m
    }

    return array;
}

From source file:com.gmail.tracebachi.DeltaSkins.Shared.Storage.SkinDataStorage.java

License:Open Source License

@Override
public JsonArray serialize() {
    JsonArray array = new JsonArray();

    synchronized (skinDataMap) {
        for (SkinData skinData : skinDataMap.values()) {
            if ((System.currentTimeMillis() - skinData.getCreatedAt()) < removeOlderThanMinutes * 60 * 1000) {
                array.add(skinData.serialize());
            }/*w ww . j av  a 2s . com*/
        }
    }

    return array;
}

From source file:com.gmail.tracebachi.DeltaSkins.Spigot.DeltaSkins.java

License:Open Source License

public void onEnable() {
    if (SpigotConfig.bungee) {
        skinApplier = new SkinApplier(this);
        bungeeListener = new BungeeListener(skinApplier);

        getServer().getMessenger().registerIncomingPluginChannel(this, "DeltaSkins", bungeeListener);

        info("DeltaSkins enabled in BungeeCord mode.");
        return;/*from   www . j  a  v  a2s  .  c  o  m*/
    }

    reloadConfig();

    debugLevel = getConfig().getInt("DebugLevel", 2);
    long batchRequestIntervalSeconds = getConfig().getLong("BatchRequestIntervalSeconds", 90);
    long skinCacheDurationMinutes = getConfig().getLong("SkinCacheDurationMinutes", 180);
    long fileSaveInterval = getConfig().getLong("FileSaveInterval", 1800);
    loadFormats(getConfig());

    mojangApi = new MojangApi(this);
    skinApplier = new SkinApplier(this);
    playerProfileStorage = new PlayerProfileStorage();
    skinDataStorage = new SkinDataStorage(skinCacheDurationMinutes);

    // Read player profiles
    File profileFile = new File(getDataFolder(), PROFILES_FILENAME);
    JsonArray playerProfilesArray = readJsonElementFromFile(profileFile, new JsonArray()).getAsJsonArray();
    playerProfileStorage.deserialize(playerProfilesArray);

    // Read skin data
    File skinDataFile = new File(getDataFolder(), SKIN_DATA_FILENAME);
    JsonArray skinDataArray = readJsonElementFromFile(skinDataFile, new JsonArray()).getAsJsonArray();
    skinDataStorage.deserialize(skinDataArray);

    // Schedule repeating tasks
    BukkitScheduler scheduler = getServer().getScheduler();
    BatchUuidRunnable uuidRunnable = new BatchUuidRunnable(batchRequestIntervalSeconds, this);
    SaveFilesRunnable fileSaveRunnable = new SaveFilesRunnable(profileFile, skinDataFile, this);
    scheduler.runTaskTimerAsynchronously(this, uuidRunnable, 20, 20);
    scheduler.runTaskTimer(this, fileSaveRunnable, fileSaveInterval, fileSaveInterval);

    loginListener = new LoginListener(skinApplier, this);
    getServer().getPluginManager().registerEvents(loginListener, this);

    commands = new MainCommands(skinApplier, this);
    getCommand("deltaskins").setExecutor(commands);
}

From source file:com.goodow.realtime.server.model.DeltaSerializer.java

License:Apache License

public static JsonElement dataToClientJson(Delta<String> data, long resultingRevision) {
    Preconditions.checkArgument(resultingRevision <= MAX_DOUBLE_INTEGER, "Resulting revision %s is too large",
            resultingRevision);// w  w w  .  j a v  a 2s. c o  m

    // Assume payload is JSON, and parse it to avoid nested json.
    // TODO: Consider using Delta<JSONObject> instead.
    // The reason I haven't done it yet is because it's not immutable,
    // and also for reasons described in Delta.
    JsonElement payloadJson;
    try {
        payloadJson = new JsonParser().parse(data.getPayload());
    } catch (JsonParseException e) {
        throw new IllegalArgumentException("Invalid payload for " + data, e);
    }

    JsonArray json = new JsonArray();
    try {
        Preconditions.checkArgument(resultingRevision >= 0, "invalid rev %s", resultingRevision);
        json.add(new JsonPrimitive(resultingRevision));
        long sanityCheck = json.get(0).getAsLong();
        if (sanityCheck != resultingRevision) {
            throw new AssertionError("resultingRevision " + resultingRevision
                    + " not losslessly represented in JSON, got back " + sanityCheck);
        }
        json.add(new JsonPrimitive(data.getSession().userId));
        json.add(new JsonPrimitive(data.getSession().sessionId));
        json.add(payloadJson);
        return json;
    } catch (JsonParseException e) {
        throw new Error(e);
    }
}

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

License:Apache License

private static JsonArray serializeDeltas(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++;/*  w  w  w. j av a  2  s  .c  o m*/
    }
    return history;
}

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  ava 2 s  .  co 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 a v a 2s . c  om
    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  w w  .j a v  a 2 s  .  com*/
    }
    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 .  ja v  a  2 s  .  c o  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  a  v a 2s .c om
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;
}