Example usage for com.google.gson JsonParser JsonParser

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

Introduction

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

Prototype

@Deprecated
public JsonParser() 

Source Link

Usage

From source file:catalog.CloudantUtil.java

License:Apache License

/**
 * Read bulk documents from the cloudant database
 *
 * @throws UnsupportedEncodingException// w ww .  j a va2  s.c o m
 */
public static JsonArray bulkDocuments(Credential credential, JsonArray bulkDocs)
        throws UnsupportedEncodingException {
    JsonObject docs = new JsonObject();
    docs.add("docs", bulkDocs);
    // use GET to get the document
    String dbname = credential.dbname;
    Response response = given().port(443).baseUri(cloudantAccount(credential.user)).auth()
            .basic(credential.user, credential.password).contentType("application/json").body(docs)
            .post("/" + credential.dbname + "/_bulk_docs?include_docs=true");
    String responseStr = response.asString();
    if (responseStr.length() > 500)
        responseStr = responseStr.substring(0, 500);
    System.out.format("Response of get document from database %s: %s\n", dbname, responseStr);
    return (JsonArray) new JsonParser().parse(response.asString());
}

From source file:catalog.CloudantUtil.java

License:Apache License

/**
 * Create an index in the cloudant database
 *
 * @throws UnsupportedEncodingException//from ww  w.  j  a v a 2  s.  com
 */
public static JsonObject createIndex(Credential credential, String jsonObj)
        throws UnsupportedEncodingException {
    Response response = given().port(443).baseUri(cloudantAccount(credential.user)).auth()
            .basic(credential.user, credential.password).contentType("application/json").body(jsonObj).when()
            .post("/" + credential.dbname + "/_index");
    System.out.format("Response of create document in database %s: %s\n", credential.dbname,
            response.asString());
    assertTrue("failed to create index in database " + credential.dbname, response.statusCode() == 200);
    return (JsonObject) new JsonParser().parse(response.asString());
}

From source file:cc.metapro.openct.data.source.local.StoreHelper.java

License:Apache License

public static <T> List<T> fromJsonList(String jsonList, Class<T> classType) {
    JsonArray array = new JsonParser().parse(jsonList).getAsJsonArray();
    List<T> result = new ArrayList<>();
    for (JsonElement element : array) {
        result.add(gson.fromJson(element, classType));
    }//from  w w w. ja  va 2s . c  o m
    return result;
}

From source file:cf.adriantodt.David.loader.entities.ModuleResourceManager.java

License:LGPL

default JsonElement getAsJson(String path) {
    return new JsonParser().parse(get(path));
}

From source file:cf.adriantodt.David.Loader.java

License:LGPL

public static void main(String[] args) throws Exception {
    Loader.args = args;/*from  w  ww.ja va2  s . c  o  m*/
    JsonElement src = new JsonParser().parse(resource("/assets/loader/main.json"));

    if (!src.isJsonArray()) {
        LOGGER.error("\"/assets/loader/main.json\" is in a incorrect form. Expected \"" + JsonArray.class
                + "\", got \"" + src.getClass() + "\"");
        return;
    }

    src.getAsJsonArray().forEach(element -> {
        try {
            ModuleManager.add(Class.forName(element.getAsString()));
        } catch (Exception e) {
            LOGGER.error("Failed to load Module " + element, e);
        }
    });

    ModuleManager.firePreReadyEvents();

    new JDABuilder(AccountType.BOT).setToken(DBModule.getConfig().get("token").getAsString())
            .setEventManager(new AnnotatedEventManager()).addListener(ModuleManager.jdaListeners())
            .buildBlocking();

    ModuleManager.firePostReadyEvents();
}

From source file:cf.adriantodt.David.modules.db.I18nModule.java

License:LGPL

@PostReady
private static void load() {
    localizeLocal("botname", jda.getSelfUser().getName());
    localizeLocal("mention", jda.getSelfUser().getAsMention());

    JsonObject mainFile = new JsonParser().parse(i18nMain).getAsJsonObject();
    mainFile.entrySet().forEach(entry -> {
        //Before Load, Parse Contents
        JsonObject def = entry.getValue().getAsJsonObject();
        if (def.has("parent"))
            setParent(entry.getKey(), def.get("parent").getAsString());

        String resource = manager.get(entry.getKey() + ".json");
        if (resource == null)
            return;

        loadFile(entry.getKey(), new JsonParser().parse(resource));
    });/*w ww.  ja v  a2 s  .  c  o  m*/
}

From source file:cf.adriantodt.utils.data.ConfigUtils.java

License:LGPL

public static JsonObject get(String name, Map<String, Predicate<JsonElement>> validator,
        Supplier<JsonObject> defaultGenerator, boolean returnGenerated, boolean generateFileOnError) {
    Path path = path(name);/*  w ww . j  ava2s.  co m*/
    try {
        JsonElement input = new JsonParser().parse(new String(Files.readAllBytes(path), UTF8));
        JsonObject object = requireObject(input);
        validator.forEach((s, predicate) -> requireValid(object, s, predicate));
        return object;
    } catch (IOException | NullPointerException | IllegalStateException e) {
        LOGGER.error("Error while loading Config file: ", e);
        Optional<Supplier<JsonObject>> optionalGenerator = Optional.ofNullable(defaultGenerator);
        LOGGER.error("Configuration File not found or damaged." + (optionalGenerator.isPresent()
                ? (generateFileOnError ? " Generating one at " + path + "..." : "")
                        + (returnGenerated ? " The Generated Default Object will be returned." : "")
                : " No Generator found."));
        if (!optionalGenerator.isPresent()) {
            return null;
        } else {
            JsonObject defaultObj = optionalGenerator.get().get();

            if (generateFileOnError) {
                try {
                    Files.write(path, GSON.toJson(defaultObj).getBytes(Charset.forName("UTF-8")));
                    LOGGER.error("Configuration File generated.");
                } catch (Exception ex) {
                    LOGGER.error("Configuration File could not be generated. Please fix the permissions.");
                }
            }

            if (returnGenerated)
                return defaultObj;
        }
    }

    return null;
}

From source file:cf.brforgers.bot.handlers.BotIntercommns.java

License:LGPL

private static void transaction(User bot, String msg) {
    if (msg.length() < (IC_CALL.length() + 1) || !msg.startsWith(IC_CALL))
        return;// www  . j av a 2  s. c  o  m
    msg = msg.substring(IC_CALL.length());

    char opcode = msg.charAt(0);

    if (opcode == SUPPORTS_IC) {
        pm(bot, IC_CALL + SUPPORTED);
        return;
    }

    if (opcode == TRANSACTION) {
        if (msg.length() < 2)
            return;
        msg = msg.substring(1);
        opcode = msg.charAt(0);

        if (opcode == TRANSACTION_CHECK) {
            msg = msg.substring(2);
            int oldHash = Statistics.parseInt(msg, 0);
            if (oldHash != self.toString().hashCode()) {
                pm(bot, IC_CALL + TRANSACTION + TRANSACTION_UPDATE);
            }
            return;
        }

        if (opcode == TRANSACTION_GET) {
            msg = msg.substring(2);

            if (msg.equals("p")) {
                pm(bot, IC_CALL + TRANSACTION + TRANSACTION_SET + "$p=" + self.p);
            }

            if (msg.equals("cmds")) {
                boolean first = true;
                JsonArray array = new JsonArray();
                String state = array.toString();

                for (int i = 0; i < self.cmds.size(); i++) {
                    state = array.toString();
                    array.add(new JsonPrimitive(self.cmds.get(i)));

                    if (array.toString().length() > 1900) {
                        pm(bot, IC_CALL + TRANSACTION + TRANSACTION_SET + "$cmds" + (first ? "=" : "+")
                                + state);
                        first = false;
                        array = new JsonArray();
                        array.add(new JsonPrimitive(self.cmds.get(i)));
                    }
                }

                pm(bot, IC_CALL + TRANSACTION + TRANSACTION_SET + "$cmds" + (first ? "=" : "+") + state);
                return;
            }

            return;
        }

        if (opcode == TRANSACTION_SET) {
            msg = msg.substring(2);
            if (msg.startsWith("p")) {
                get(bot).p = Statistics.parseInt(msg.substring(2), 0);
                return;
            }

            if (msg.startsWith("cmds")) {
                msg = msg.substring("cmds".length());
                opcode = msg.charAt(0);
                msg = msg.substring(1);
                JsonArray array = new JsonParser().parse(msg).getAsJsonArray();

                if (opcode == '=') {
                    get(bot).cmds.clear();
                }

                if (opcode == '-') {
                    get(bot).cmds.removeIf(s -> StreamSupport.stream(array.spliterator(), false)
                            .anyMatch(j -> s.equals(j.getAsString()))); //I Know, it's lazy.
                }

                if (opcode == '=' || opcode == '+') {
                    get(bot).cmds.addAll(StreamSupport.stream(array.spliterator(), false)
                            .map(JsonElement::getAsString).collect(Collectors.toList()));
                }

                return;
            }
            return;
        }

        if (opcode == TRANSACTION_UPDATE) {
            pm(bot, IC_CALL + TRANSACTION + TRANSACTION_GET + "$p");
            pm(bot, IC_CALL + TRANSACTION + TRANSACTION_GET + "$cmds");
            return;
        }

        return;
    }

    if (msg.startsWith(SUPPORTED)) {
        if (Character.toLowerCase(msg.charAt(1)) == 'y') {
            pm(bot, IC_CALL + TRANSACTION + TRANSACTION_CHECK + TRANSACTION_VALUE
                    + get(bot).toString().hashCode());
        }
    }
}

From source file:cf.funge.aworldofplants.RequestRouter.java

License:Open Source License

/**
 * The main Lambda function handler. Receives the request as an input stream, parses the json and looks for the
 * "action" property to decide where to route the request. The "body" property of the incoming request is passed
 * to the Action implementation as a request body.
 *
 * @param request  The InputStream for the incoming event. This should contain an "action" and "body" properties. The
 *                 action property should contain the namespaced name of the class that should handle the invocation.
 *                 The class should implement the Action interface. The body property should contain the full
 *                 request body for the action class.
 * @param response An OutputStream where the response returned by the action class is written
 * @param context  The Lambda Context object
 * @throws BadRequestException    This Exception is thrown whenever parameters are missing from the request or the action
 *                                class can't be found
 * @throws InternalErrorException This Exception is thrown when an internal error occurs, for example when the database
 *                                is not accessible
 *///ww w. j a va2  s. co m
public static void lambdaHandler(InputStream request, OutputStream response, Context context)
        throws BadRequestException, InternalErrorException {
    LambdaLogger logger = context.getLogger();

    JsonParser parser = new JsonParser();
    JsonObject inputObj;
    try {
        inputObj = parser.parse(IOUtils.toString(request)).getAsJsonObject();
    } catch (IOException e) {
        logger.log("Error while reading request\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }

    if (inputObj == null || inputObj.get("action") == null
            || inputObj.get("action").getAsString().trim().equals("")) {
        logger.log("Invald inputObj, could not find action parameter");
        throw new BadRequestException("Could not find action value in request");
    }

    String actionClass = inputObj.get("action").getAsString();
    Action action;

    try {
        action = Action.class.cast(Class.forName(actionClass).newInstance());
    } catch (final InstantiationException e) {
        logger.log("Error while instantiating action class\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    } catch (final IllegalAccessException e) {
        logger.log("Illegal access while instantiating action class\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    } catch (final ClassNotFoundException e) {
        logger.log("Action class could not be found\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }

    if (action == null) {
        logger.log("Action class is null");
        throw new BadRequestException("Invalid action class");
    }

    JsonObject body = null;
    if (inputObj.get("body") != null) {
        body = inputObj.get("body").getAsJsonObject();
    }

    String output = action.handle(body, context);

    try {
        IOUtils.write(output, response);
    } catch (final IOException e) {
        logger.log("Error while writing response\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }
}

From source file:ch.cern.db.flume.JSONEvent.java

License:GNU General Public License

@Override
public void setBody(byte[] body) {
    json = new JsonParser().parse(new String(body)).getAsJsonObject();
}