Example usage for com.google.gson JsonElement getAsJsonObject

List of usage examples for com.google.gson JsonElement getAsJsonObject

Introduction

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

Prototype

public JsonObject getAsJsonObject() 

Source Link

Document

convenience method to get this element as a JsonObject .

Usage

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

License:LGPL

private static Data unpack(JsonElement element) {
    JsonObject object = element.getAsJsonObject();
    Data data = all.stream().filter(dataPredicate -> object.get("id").getAsString().equals(dataPredicate.id))
            .findFirst().orElseGet(Data::new);
    data.id = object.get("id").getAsString();
    data.lang = ConfigUtils.isJsonString(object.get("lang")) ? object.get("lang").getAsString() : null;
    userMap.put(data.getUser(jda), data);
    if (data.getUser(jda) == null) {
        timeoutUntilDbRemoval.put(data, 5);
    }//from w  ww .j  a va2 s .  com
    return data;
}

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

License:LGPL

public static JsonObject requireObject(JsonElement element) {
    if (element == null || !element.isJsonObject())
        throw new NullPointerException("the provided " + JsonElement.class + " is not an " + JsonObject.class);

    return element.getAsJsonObject();
}

From source file:ch.cyberduck.core.dropbox.DropboxExceptionMappingService.java

License:Open Source License

private void parse(final StringBuilder buffer, final String message) {
    final JsonParser parser = new JsonParser();
    try {//  w w w .  j  ava2 s  .  co m
        final JsonElement element = parser.parse(new StringReader(message));
        if (element.isJsonObject()) {
            final JsonObject json = element.getAsJsonObject();
            final JsonObject error = json.getAsJsonObject("error");
            if (null == error) {
                this.append(buffer, message);
            } else {
                final JsonPrimitive tag = error.getAsJsonPrimitive(".tag");
                if (null == tag) {
                    this.append(buffer, message);
                } else {
                    this.append(buffer, StringUtils.replace(tag.getAsString(), "_", " "));
                }
            }
        }
        if (element.isJsonPrimitive()) {
            this.append(buffer, element.getAsString());
        }
    } catch (JsonParseException e) {
        // Ignore
    }
}

From source file:ch.ethz.inf.vs.hypermedia.corehal.block.CoREHalResourceFuture.java

License:Open Source License

public CoapRequestFuture getFormRequest(String key, String name, Object payload) {
    MediaType mediaType = null;//from   ww  w  .  java  2 s.  c  o  m
    if (payload != null) {
        mediaType = Utils.getMediaTypeAnnotation(payload.getClass());
    }
    int ct = MediaTypeRegistry.UNDEFINED;
    String mt = null;
    if (mediaType != null) {
        mt = mediaType.mediaType();
        ct = mediaType.contentType();
    }
    int payloadContentType = ct;
    String payloadMediaType = mt;
    CoapRequestFuture request = new CoapRequestFuture();
    request.addParent(this);
    request.setPreProcess(() -> {
        V item = get();
        Form form;
        if (item instanceof CoREHalBase) {
            form = ((CoREHalBase) item).getForm(key, name);
        } else {
            throw new RuntimeException("Not implemented");
        }
        if (form == null) {
            throw new ExecutionException(new Exception(
                    "Form  rel:" + String.valueOf(key) + " name:" + String.valueOf(name) + " not found"));
        }
        if (form.getInput() != null && payloadMediaType != null && !form.getInput().equals(payloadMediaType)) {
            throw new ExecutionException(new Exception("Invalid payload media type"));
        }
        try {
            Map<String, Object> properties = null;
            String url = form.getHref();
            JsonElement data;
            if (payload instanceof CoREHalBase) {
                data = CoREHalResourceFuture.serializeToJsonTree((CoREHalBase) payload);
            } else {
                data = ResourceFuture.gson.toJsonTree(payload);
            }
            if (form.getTemplated() != null && form.getTemplated() == true) {
                if (properties == null)
                    properties = dataToObjectMap(data);
                url = UriTemplate.fromTemplate(url).expand(properties);
            }
            url = Utils.resolve(getUrl(), url);
            String formPayload = "";
            if (form.getValue() != null) {
                if (properties == null)
                    properties = dataToObjectMap(data);
                Object val = properties.get(form.getValue());
                if (val instanceof String) {
                    formPayload = (String) val;
                } else {
                    formPayload = ResourceFuture.gson.toJson(val);
                }
            } else if (form.getExcludes() != null && form.getExcludes().length > 0) {
                for (String k : form.getExcludes()) {
                    data.getAsJsonObject().remove(k);
                }
                formPayload = ResourceFuture.gson.toJson(data);
            } else {
                formPayload = ResourceFuture.gson.toJson(data);
            }
            request.setMethod(form.getMethod());
            request.setUrl(url);
            // TODO: use expected payload media type
            request.setPayloadContentType(payloadContentType);
            request.setPayload(formPayload);
            request.setExpectedContentType(MediaTypeRegistry.UNDEFINED);
        } catch (URISyntaxException e) {
            throw new ExecutionException(e);
        }

    });
    return request;
}

From source file:ch.ethz.inf.vs.hypermedia.corehal.block.CoREHalResourceFuture.java

License:Open Source License

public JsonObject getEmbeddedRepresentation(CoREHalBase item, String key, String url) {
    JsonObject embeded = null;// w  w  w  .  ja  va  2 s.c  o  m
    List<JsonElement> elements = item.getEmbedded(key);
    if (elements == null) {
        return null;
    }
    for (JsonElement el : elements) {
        try {
            String elUrl = Utils.resolve(getUrl(), el.getAsJsonObject().get("_self").getAsString());
            if (url.equals(elUrl)) {
                embeded = el.getAsJsonObject();
                break;
            }
        } catch (Exception e) {
        }

    }
    return embeded;
}

From source file:ch.ethz.inf.vs.hypermedia.corehal.block.CoREHalResourceFuture.java

License:Open Source License

public static JsonElement serializeToJsonTree(CoREHalBase base) {
    Class<? extends CoREHalBase> type = base.getClass();
    if (ProxyFactory.isProxyClass(type)) {
        type = (Class<? extends CoREHalBase>) type.getSuperclass();
    }/* w  w w . j a v  a  2s. co m*/
    JsonElement s = CoREHalResourceFuture.getGson().toJsonTree(base, type);
    if (s.isJsonObject() && base.json() != null) {
        JsonObject json = s.getAsJsonObject();
        base.json().entrySet().forEach((el) -> {
            if (!json.has(el.getKey())) {
                json.add(el.getKey(), el.getValue());
            }
        });
    }
    return s;
}

From source file:ch.ethz.inf.vs.hypermedia.corehal.OptionalListDeserializer.java

License:Open Source License

public static JsonElement cleanup(JsonElement serialize) {
    if (serialize.isJsonObject()) {
        serialize.getAsJsonObject().entrySet().removeIf(x -> x.getValue().isJsonNull());
        serialize.getAsJsonObject().entrySet().forEach(x -> cleanup(x.getValue()));
    }//from  w  w  w. ja  va 2  s . com
    if (serialize.isJsonArray()) {
        serialize.getAsJsonArray().forEach(OptionalListDeserializer::cleanup);
    }
    return serialize;
}

From source file:ch.gaps.slasher.views.main.MainController.java

License:Open Source License

/**
 * Read the save file and laod all the data in the software
 *
 * @throws IOException//from ww w.  j  av a2  s .  c  o m
 */
private void readSave() {
    try {
        Gson gson = new Gson();
        JsonReader reader = new JsonReader(new FileReader("save.json"));
        JsonArray mainArray = gson.fromJson(reader, JsonArray.class);

        LinkedList<Driver> drivers = DriverService.instance().getAll();

        if (mainArray != null) {
            for (JsonElement e : mainArray) {
                JsonObject server = e.getAsJsonObject();

                Driver driver = null;

                String serverDriver = server.get("serverDriver").getAsString();

                for (Driver d : drivers) {
                    if (d.toString().equals(serverDriver)) {
                        driver = d.getClass().newInstance();
                    }
                }

                Server s = new Server(driver, server.get("serverHost").getAsString(),
                        server.get("serverPort").getAsInt(), server.get("serverDescription").getAsString());
                ServerTreeItem serverTreeItem = new ServerTreeItem(s);
                servers.add(s);

                JsonArray databases = server.get("databases").getAsJsonArray();

                if (databases != null) {
                    for (JsonElement d : databases) {
                        if (!serverDriver.equals("Sqlite")) {
                            driver = driver.getClass().newInstance();
                        }
                        JsonObject database = d.getAsJsonObject();

                        Database db = new Database(driver, database.get("databaseName").getAsString(),
                                database.get("databaseDescritpion").getAsString(), s,
                                database.get("databaseUsername").getAsString());
                        s.addDatabase(db);

                        if (serverDriver.equals("Sqlite")) {
                            try {
                                db.connect("");
                            } catch (SQLException | ClassNotFoundException e1) {
                                e1.printStackTrace();
                            }
                        }

                        JsonArray tabs = database.get("tabs").getAsJsonArray();

                        for (JsonElement t : tabs) {
                            JsonObject tab = t.getAsJsonObject();

                            if (tab.get("moduleName").getAsString().equals("Editor")) {
                                loadEditorTab(db, tab.get("content").getAsString());
                            }

                        }

                    }
                }
                rootTreeItem.getChildren().add(serverTreeItem);
            }
        }
    } catch (IOException | IllegalAccessException | InstantiationException e) {
        addToUserCommunication(e.getMessage());
    }
}

From source file:ch.icclab.cyclops.consume.data.BillDeserializer.java

License:Open Source License

@Override
public void preDeserialize(Class<? extends T> clazz, JsonElement jsonElement, Gson gson) {

    // valid JSON object
    if (jsonElement != null && jsonElement.isJsonObject()) {
        JsonObject root = jsonElement.getAsJsonObject();

        // map data to string so it can be persisted as jsonb
        if (root.has(Bill.DATA_FIELD.getName())) {
            root.addProperty(Bill.DATA_FIELD.getName(), new Gson().toJson(root.get(Bill.DATA_FIELD.getName())));
        }//  w w  w .j  a  v  a2  s .  c om
    }
}

From source file:ch.icclab.cyclops.consume.data.CDRDeserializer.java

License:Open Source License

@Override
public void preDeserialize(Class<? extends T> clazz, JsonElement jsonElement, Gson gson) {

    // valid JSON object
    if (jsonElement != null && jsonElement.isJsonObject()) {
        JsonObject root = jsonElement.getAsJsonObject();

        // map data to string so it can be persisted as jsonb
        if (root.has(CDR.DATA_FIELD.getName())) {
            root.addProperty(CDR.DATA_FIELD.getName(), new Gson().toJson(root.get(CDR.DATA_FIELD.getName())));
        }/*  w  w  w.j  a  va2s  . c om*/
    }
}