Example usage for com.google.gson JsonObject getAsJsonArray

List of usage examples for com.google.gson JsonObject getAsJsonArray

Introduction

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

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

From source file:net.doubledoordev.backend.web.socket.FileManagerSocketApplication.java

License:Open Source License

@Override
public void onMessage(WebSocket socket, String text) {
    FileManager fileManager = (FileManager) ((DefaultWebSocket) socket).getUpgradeRequest()
            .getAttribute(FILE_MANAGER);
    if (!fileManager.getServer()
            .isCoOwner((User) ((DefaultWebSocket) socket).getUpgradeRequest().getAttribute(USER))) {
        WebSocketHelper.sendError(socket, "You have no rights to this server.");
        socket.close();/*from  www . j  a  va2  s .c  o m*/
        return;
    }
    try {
        JsonObject object = JSONPARSER.parse(text).getAsJsonObject();
        String name = object.get("method").getAsString();
        ArrayList<String> args = new ArrayList<>();
        if (object.has("args"))
            for (JsonElement arg : object.getAsJsonArray("args"))
                args.add(arg.getAsString());
        if (!Helper.invokeWithRefectionMagic(socket, fileManager, name, args)) {
            WebSocketHelper.sendOk(socket);
            socket.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        WebSocketHelper.sendError(socket, e);
    }
}

From source file:net.doubledoordev.backend.web.socket.ServerControlSocketApplication.java

License:Open Source License

@Override
public void onMessage(WebSocket socket, String text) {
    Server server = (Server) ((DefaultWebSocket) socket).getUpgradeRequest().getAttribute(SERVER);
    if (!server.canUserControl((User) ((DefaultWebSocket) socket).getUpgradeRequest().getAttribute(USER))) {
        WebSocketHelper.sendError(socket, "You have no rights to this server.");
        socket.close();/*  ww  w .  j ava  2s. c  om*/
        return;
    }
    try {
        JsonObject object = JSONPARSER.parse(text).getAsJsonObject();
        String name = object.get("method").getAsString();
        ArrayList<String> args = new ArrayList<>();
        if (object.has("args"))
            for (JsonElement arg : object.getAsJsonArray("args"))
                args.add(arg.getAsString());
        if (!Helper.invokeWithRefectionMagic(socket, server, name, args)) {
            WebSocketHelper.sendOk(socket);
            socket.close();
        }
    } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        WebSocketHelper.sendError(socket, e);
        socket.close();
    }
}

From source file:net.doubledoordev.backend.web.socket.UsersSocketApplication.java

License:Open Source License

@Override
public void onMessage(WebSocket socket, String text) {
    User user = (User) ((DefaultWebSocket) socket).getUpgradeRequest().getAttribute(USER);
    try {//from w  ww.j a v a  2s  .c  om
        JsonObject object = JSONPARSER.parse(text).getAsJsonObject();
        String name = object.get("method").getAsString();
        ArrayList<String> args = new ArrayList<>();
        if (object.has("args"))
            for (JsonElement arg : object.getAsJsonArray("args"))
                args.add(arg.getAsString());
        if (!Helper.invokeWithRefectionMagic(socket, user, name, args)) {
            WebSocketHelper.sendOk(socket);
            socket.close();
        }
    } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        WebSocketHelper.sendError(socket, e);
        socket.close();
    }
}

From source file:net.fabricmc.installer.installer.ServerInstaller.java

License:Apache License

public static void install(File mcDir, String version, IInstallerProgress progress, File fabricJar)
        throws IOException {
    progress.updateProgress(Translator.getString("gui.installing") + ": " + version, 0);
    String[] split = version.split("-");
    String mcVer = split[0];/*from   ww  w. j  a v a2 s . c  om*/
    String fabricVer = split[1];

    File mcJar = new File(mcDir, "minecraft_server." + mcVer + ".jar");

    if (!mcJar.exists()) {
        progress.updateProgress(Translator.getString("install.server.downloadVersionList"), 10);
        JsonObject versionList = Utils
                .loadRemoteJSON(new URL("https://launchermeta.mojang.com/mc/game/version_manifest.json"));
        String url = null;

        for (JsonElement element : versionList.getAsJsonArray("versions")) {
            JsonObject object = element.getAsJsonObject();
            if (object.get("id").getAsString().equals(mcVer)) {
                url = object.get("url").getAsString();
                break;
            }
        }

        if (url == null) {
            throw new RuntimeException(Translator.getString("install.server.error.noVersion"));
        }

        progress.updateProgress(Translator.getString("install.server.downloadServerInfo"), 12);
        JsonObject serverInfo = Utils.loadRemoteJSON(new URL(url));
        url = serverInfo.getAsJsonObject("downloads").getAsJsonObject("server").get("url").getAsString();

        progress.updateProgress(Translator.getString("install.server.downloadServer"), 15);
        FileUtils.copyURLToFile(new URL(url), mcJar);
    }

    File libs = new File(mcDir, "libs");

    ZipFile fabricZip = new ZipFile(fabricJar);
    InstallerMetadata metadata;
    try (InputStream inputStream = fabricZip
            .getInputStream(fabricZip.getEntry(Reference.INSTALLER_METADATA_FILENAME))) {
        metadata = new InstallerMetadata(inputStream);
    }

    List<InstallerMetadata.LibraryEntry> fabricDeps = metadata.getLibraries("server", "common");
    for (int i = 0; i < fabricDeps.size(); i++) {
        InstallerMetadata.LibraryEntry dep = fabricDeps.get(i);
        File depFile = new File(libs, dep.getFilename());
        if (depFile.exists()) {
            depFile.delete();
        }
        progress.updateProgress("Downloading " + dep.getFilename(), 20 + (i * 70 / fabricDeps.size()));
        FileUtils.copyURLToFile(new URL(dep.getFullURL()), depFile);
    }

    progress.updateProgress(Translator.getString("install.success"), 100);
}

From source file:net.fabricmc.installer.util.InstallerMetadata.java

License:Apache License

private Stream<JsonElement> getObjectsSubKeyed(JsonObject baseObj, String key, String... subKeys) {
    if (!baseObj.has(key)) {
        return Stream.empty();
    }/*w ww.  j  a va 2  s  .  co m*/

    List<JsonElement> list = new ArrayList<>();
    JsonObject keyObj = baseObj.getAsJsonObject(key);

    for (String s : subKeys) {
        if (keyObj.has(s)) {
            JsonArray array = keyObj.getAsJsonArray(s);
            for (JsonElement element : array) {
                list.add(element);
            }
        }
    }

    return list.stream();
}

From source file:net.kleditzsch.shcCore.Json.LoginResponseSerializer.java

License:Open Source License

@Override
public LoginResponse deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {

    JsonObject jo = jsonElement.getAsJsonObject();
    LoginResponse loginResponse = new LoginResponse();
    loginResponse.setSuccess(jo.get("success").getAsBoolean());
    loginResponse.setMessage(jo.get("message").getAsString());
    loginResponse.setErrorCode(jo.get("errorCode").getAsInt());
    loginResponse.setSessionId(jo.get("sessionId").getAsString());
    loginResponse.setProtocolVersion(jo.get("protocolVersion").getAsInt());
    loginResponse.setFritzBoxActive(jo.get("fritzBoxActive").getAsBoolean());

    //Berechtigungen
    JsonArray permissions = jo.getAsJsonArray("permissions");
    for (int i = 0; i < permissions.size(); i++) {

        loginResponse.getPermissions().add(permissions.get(i).getAsString());
    }//from w  ww.ja  va  2 s .c  o m

    //Icons
    JsonArray icons = jo.getAsJsonArray("icons");
    for (int i = 0; i < icons.size(); i++) {

        Icon icon = new Icon();
        JsonObject iconJson = icons.get(i).getAsJsonObject();
        icon.setName(iconJson.get("name").getAsString());

        JsonArray sizeArray = iconJson.getAsJsonArray("size");
        for (int j = 0; j < sizeArray.size(); j++) {

            icon.getAvailableSize().add(sizeArray.get(j).getAsInt());
        }
        loginResponse.getIcons().add(icon);
    }

    return loginResponse;
}

From source file:net.kyori.text.serializer.gson.GsonComponentSerializer.java

License:MIT License

private BuildableComponent<?, ?> deserialize0(final JsonElement element,
        final JsonDeserializationContext context) throws JsonParseException {
    if (element.isJsonPrimitive()) {
        return TextComponent.of(element.getAsString());
    } else if (element.isJsonArray()) {
        ComponentBuilder<?, ?> parent = null;
        for (final JsonElement childElement : element.getAsJsonArray()) {
            final BuildableComponent<?, ?> child = this.deserialize0(childElement, context);
            if (parent == null) {
                parent = child.toBuilder();
            } else {
                parent.append(child);//from w w  w.  ja va  2 s.  co m
            }
        }
        if (parent == null) {
            throw new JsonParseException("Don't know how to turn " + element + " into a Component");
        }
        return parent.build();
    } else if (!element.isJsonObject()) {
        throw new JsonParseException("Don't know how to turn " + element + " into a Component");
    }

    final JsonObject object = element.getAsJsonObject();
    final ComponentBuilder<?, ?> component;
    if (object.has(TEXT)) {
        component = TextComponent.builder(object.get(TEXT).getAsString());
    } else if (object.has(TRANSLATE)) {
        final String key = object.get(TRANSLATE).getAsString();
        if (!object.has(TRANSLATE_WITH)) {
            component = TranslatableComponent.builder(key);
        } else {
            final JsonArray with = object.getAsJsonArray(TRANSLATE_WITH);
            final List<Component> args = new ArrayList<>(with.size());
            for (int i = 0, size = with.size(); i < size; i++) {
                final JsonElement argElement = with.get(i);
                args.add(this.deserialize0(argElement, context));
            }
            component = TranslatableComponent.builder(key).args(args);
        }
    } else if (object.has(SCORE)) {
        final JsonObject score = object.getAsJsonObject(SCORE);
        if (!score.has(SCORE_NAME) || !score.has(SCORE_OBJECTIVE)) {
            throw new JsonParseException(
                    "A score component requires a " + SCORE_NAME + " and " + SCORE_OBJECTIVE);
        }
        // score components can have a value sometimes, let's grab it
        if (score.has(SCORE_VALUE)) {
            component = ScoreComponent.builder().name(score.get(SCORE_NAME).getAsString())
                    .objective(score.get(SCORE_OBJECTIVE).getAsString())
                    .value(score.get(SCORE_VALUE).getAsString());
        } else {
            component = ScoreComponent.builder().name(score.get(SCORE_NAME).getAsString())
                    .objective(score.get(SCORE_OBJECTIVE).getAsString());
        }
    } else if (object.has(SELECTOR)) {
        component = SelectorComponent.builder().pattern(object.get(SELECTOR).getAsString());
    } else if (object.has(KEYBIND)) {
        component = KeybindComponent.builder().keybind(object.get(KEYBIND).getAsString());
    } else if (object.has(NBT)) {
        final String nbt = object.get(NBT).getAsString();
        final boolean interpret = object.has(NBT_INTERPRET)
                && object.getAsJsonPrimitive(NBT_INTERPRET).getAsBoolean();
        if (object.has(NBT_BLOCK)) {
            final BlockNbtComponent.Pos position = context.deserialize(object.get(NBT_BLOCK),
                    BlockNbtComponent.Pos.class);
            component = BlockNbtComponent.builder().nbtPath(nbt).interpret(interpret).pos(position);
        } else if (object.has(NBT_ENTITY)) {
            component = EntityNbtComponent.builder().nbtPath(nbt).interpret(interpret)
                    .selector(object.get(NBT_ENTITY).getAsString());
        } else {
            throw notSureHowToDeserialize(element);
        }
    } else {
        throw notSureHowToDeserialize(element);
    }

    if (object.has(EXTRA)) {
        final JsonArray extra = object.getAsJsonArray(EXTRA);
        for (int i = 0, size = extra.size(); i < size; i++) {
            final JsonElement extraElement = extra.get(i);
            component.append(this.deserialize0(extraElement, context));
        }
    }

    final Style style = context.deserialize(element, Style.class);
    if (!style.isEmpty()) {
        component.style(style);
    }

    return component.build();
}

From source file:net.lm.seriesfreak.database.data.properties.StringArrayProperty.java

License:Open Source License

@Override
public void deserialize(JsonObject object) {
    JsonArray values = object.getAsJsonArray("Value");

    for (int i = 0; i < values.size(); i++) {
        this.value.add(values.get(i).getAsString());
    }// w  ww  . j  a v  a 2  s  . com
}

From source file:net.lm.seriesfreak.ui.language.LanguageLoader.java

License:Open Source License

@SuppressWarnings("UseSpecificCatch")
private void getFiles() {
    try {/*from   w w w. j  a  v  a2s . c om*/
        JsonObject resourceListFile = Resources.getResources();

        JsonArray langs = resourceListFile.getAsJsonArray("lang");

        for (int i = 0; i < langs.size(); i++) {
            Language lang = new Language(langs.get(i).getAsString());

            try (InputStream resIn = this.getClass()
                    .getResourceAsStream(resourcesPath + "/" + lang.getName() + ".lang")) {
                lang.load(resIn);
            }

            languages.add(lang);
        }
    } catch (Exception ex) {
        log.fatal("Failed to get languages files: ", ex);

        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("Missing Files");
        alert.setHeaderText("Application cannot load");
        alert.setContentText("The language files for this application are missing.\n\n"
                + "You will probably need to reinstall the application to fix this.");
        alert.showAndWait();

        Application.exit(ExitCode.LANGUAGE_LOADING_FAILURE);
    }
}

From source file:net.minecraftforge.common.crafting.JsonContext.java

License:Open Source License

void loadConstants(JsonObject[] jsons) {
    for (JsonObject json : jsons) {
        if (json.has("conditions")
                && !CraftingHelper.processConditions(json.getAsJsonArray("conditions"), this))
            continue;
        if (!json.has("ingredient"))
            throw new JsonSyntaxException("Constant entry must contain 'ingredient' value");
        constants.put(JsonUtils.getString(json, "name"),
                CraftingHelper.getIngredient(json.get("ingredient"), this));
    }/*from w ww.j av  a 2s . c  om*/

}