Example usage for com.google.gson JsonObject getAsJsonObject

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

Introduction

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

Prototype

public JsonObject getAsJsonObject(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonObject.

Usage

From source file:com.licensetokil.atypistcalendar.gcal.Syncer.java

private boolean isIdenticalSchedule(JsonObject remoteTask, Schedule localSchedule) {
    boolean locationIsIdentical = Utilities
            .getJsonObjectValueOrEmptyString(remoteTask, EVENT_RESOURCE_LABEL_LOCATION)
            .equals(localSchedule.getPlace());
    boolean summaryIsIdentical = Utilities
            .getJsonObjectValueOrEmptyString(remoteTask, EVENT_RESOURCE_LABEL_SUMMARY)
            .equals(localSchedule.getDescription());
    boolean startTimeIsIdentical = remoteTask.getAsJsonObject(EVENT_RESOURCE_LABEL_START)
            .equals(Utilities.createGoogleDateTimeObject(localSchedule.getStartTime()));
    boolean endTimeIsIdentical = remoteTask.getAsJsonObject(EVENT_RESOURCE_LABEL_END)
            .equals(Utilities.createGoogleDateTimeObject(localSchedule.getEndTime()));

    return locationIsIdentical && summaryIsIdentical && startTimeIsIdentical && endTimeIsIdentical;
}

From source file:com.licensetokil.atypistcalendar.gcal.Syncer.java

private boolean isIdenticalDeadline(JsonObject remoteTask, Deadline localDeadline) {
    // TODO handle done/undone
    boolean locationIsIdentical = Utilities
            .getJsonObjectValueOrEmptyString(remoteTask, EVENT_RESOURCE_LABEL_LOCATION)
            .equals(localDeadline.getPlace());
    boolean summaryIsIdentical = Utilities
            .getJsonObjectValueOrEmptyString(remoteTask, EVENT_RESOURCE_LABEL_SUMMARY)
            .equals(TASK_DESCRIPTION_PREFIX_DEADLINE + localDeadline.getDescription());
    boolean startTimeIsIdentical = remoteTask.getAsJsonObject(EVENT_RESOURCE_LABEL_START)
            .equals(Utilities.createGoogleDateTimeObject(localDeadline.getEndTime()));
    boolean endTimeIsIdentical = remoteTask.getAsJsonObject(EVENT_RESOURCE_LABEL_END)
            .equals(Utilities.createGoogleDateTimeObject(localDeadline.getEndTime()));

    return locationIsIdentical && summaryIsIdentical && startTimeIsIdentical && endTimeIsIdentical;
}

From source file:com.licensetokil.atypistcalendar.gcal.Syncer.java

private boolean isIdenticalTodo(JsonObject remoteTask, Todo localTodo) {
    // TODO handle done/undone
    boolean locationIsIdentical = Utilities
            .getJsonObjectValueOrEmptyString(remoteTask, CALENDAR_RESOURCE_LABEL_LOCATION)
            .equals(localTodo.getPlace());
    boolean summaryIsIdentical = Utilities
            .getJsonObjectValueOrEmptyString(remoteTask, EVENT_RESOURCE_LABEL_SUMMARY)
            .equals(TASK_DESCRIPTION_PREFIX_TODO + localTodo.getDescription());
    boolean startTimeIsIdentical = remoteTask.getAsJsonObject(EVENT_RESOURCE_LABEL_START)
            .equals(Utilities.createGoogleDateObject(SyncManager.REMOTE_TODO_START_END_DATE));
    boolean endTimeIsIdentical = remoteTask.getAsJsonObject(EVENT_RESOURCE_LABEL_END)
            .equals(Utilities.createGoogleDateObject(SyncManager.REMOTE_TODO_START_END_DATE));

    boolean recurrenceIsIdentical = false;
    if (remoteTask.get(EVENT_RESOURCE_LABEL_RECURRENCE) != null) {
        recurrenceIsIdentical = remoteTask.getAsJsonArray(EVENT_RESOURCE_LABEL_RECURRENCE)
                .equals(SyncManager.REMOTE_TODO_RECURRENCE_PROPERTY);
    }//from  ww  w  .  ja  v  a  2  s .c  om

    return locationIsIdentical && summaryIsIdentical && startTimeIsIdentical && endTimeIsIdentical
            && recurrenceIsIdentical;
}

From source file:com.licensetokil.atypistcalendar.gcal.SyncManager.java

protected Task insertRemoteTaskIntoTasksManager(JsonObject remoteTask) {
    //Extracting the (common) fields from the RemoteTask object.
    String remoteTaskId = Utilities.getJsonObjectValueOrEmptyString(remoteTask, "id");
    String description = Utilities.getJsonObjectValueOrEmptyString(remoteTask, "summary");
    String location = Utilities.getJsonObjectValueOrEmptyString(remoteTask, "location");
    Calendar lastModifiedDate = getLastModifiedDateOrTimeNow(remoteTask);

    Task newLocalTask = null;/*from  www .j  a v a  2  s.com*/
    if (remoteTask.getAsJsonObject("start").get("date") != null) {
        //Task type is a todo
        newLocalTask = GoogleCalendarManager.getInstance().insertLocalTaskIntoTasksManager(description,
                location, lastModifiedDate, remoteTaskId);
    } else {
        Calendar startTime = null;
        Calendar endTime = null;
        try {
            startTime = Utilities.parseGoogleDateTimeObject(remoteTask.getAsJsonObject("start"));
            endTime = Utilities.parseGoogleDateTimeObject(remoteTask.getAsJsonObject("end"));
        } catch (ParseException e) {
            logger.severe(
                    "Unable to parse Google DateTime object (this is unexpected as Google only returns a standardised format)");
            e.printStackTrace();
            return null;
        }

        boolean startTimeIsTheSameAsEndTime = startTime.compareTo(endTime) == 0;
        if (startTimeIsTheSameAsEndTime) {
            //Task type is a deadline
            newLocalTask = GoogleCalendarManager.getInstance().insertLocalTaskIntoTasksManager(description,
                    location, lastModifiedDate, remoteTaskId, endTime);
        } else {
            //Task type is a schedule
            newLocalTask = GoogleCalendarManager.getInstance().insertLocalTaskIntoTasksManager(description,
                    location, lastModifiedDate, remoteTaskId, endTime, startTime);
        }
    }

    //We update the remote task so it gets the local task's ID gets recorded remotely.
    SyncManager.getInstance().updateRemoteTask(newLocalTask, remoteTaskId);
    return newLocalTask;
}

From source file:com.liferay.mobile.sdk.json.ActionDeserializer.java

License:Open Source License

@Override
public Action deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    JsonObject root = json.getAsJsonObject();

    String path = root.get("path").getAsString();
    String response = root.getAsJsonObject("returns").get("type").getAsString();

    String serviceClassName = null;
    String methodName = null;/*from w  ww .  j a  v a  2s  . c  o m*/

    String name = root.get("name").getAsString();

    String[] values = name.split("#");

    if (values.length == 2) {
        serviceClassName = values[0];
        methodName = values[1];
    }

    JsonArray jsonArray = root.getAsJsonArray("parameters").getAsJsonArray();

    try {
        ArrayList<Parameter> parameters = JSONParser.fromJSON(jsonArray,
                new GenericListType<>(Parameter.class));

        return new Action(serviceClassName, methodName, path, response, parameters);
    } catch (Exception e) {
        throw new JsonParseException(e);
    }
}

From source file:com.lithium.luces.Luces.java

License:Apache License

@Override
public Luces mapping(String typename, JsonObject mapping) {
    if (log.isDebugEnabled()) {
        log.debug("Adding mapping for type " + typename);
    }//w  w  w. ja  v a2 s  .c o m
    if (log.isTraceEnabled()) {
        log.trace("Sending mapping: " + new GsonBuilder().setPrettyPrinting().create().toJson(mapping));
    }

    if (null == typename || null == mapping) {
        if (errIfMappingNull) {
            throw new IllegalStateException(
                    String.format("%1$s cannot be set to null", typename == null ? "Type" : "Mapping"));
        }
        log.warn("Setting mapping and type to null, no primitive type conversion will be done");
        typeName = null;
        typeMap = null;
    } else {
        typeName = typename;
        typeMap = new HashMap<>();
        JsonObject workingJson = mapping.getAsJsonObject(typename);
        if (null == workingJson) {
            throw new NoSuchElementException(typename + " type not present or misnamed in mapping");
        }
        // TODO account for nesting
        workingJson = workingJson.getAsJsonObject("properties");
        for (Entry<String, JsonElement> entry : workingJson.entrySet()) {
            JsonElement typeElt = entry.getValue().getAsJsonObject().get("type");
            if (null == typeElt) {
                throw new NoSuchElementException(
                        "Invalid mapping: No type defined for " + entry.getKey() + " field.");
            }
            ParseType parseType;
            try {
                parseType = ParseType.valueOf(typeElt.getAsString().toUpperCase());
            } catch (UnsupportedOperationException ex) {
                throw new UnsupportedOperationException(
                        "Invalid Mapping: Type defined is not a string: " + typeElt.toString());
            } catch (IllegalArgumentException illegal) {
                throw new UnsupportedOperationException(
                        "The " + typeElt.getAsString() + " type is not supported for conversion");
            }
            typeMap.put(entry.getKey(), parseType);
        }
    }
    return this;
}

From source file:com.lunchareas.echomp.utils.MediaDataUtils.java

License:Open Source License

public static void updateSongMetadata(final long songId, final long albumId, final String url,
        final String path, final Context context) {

    // Get youtube ID and JSON object
    final String videoId = MusicDownloadUtils.getYoutubeId(url);

    /*/*from w ww  .  j  a  va 2  s  .c  o m*/
    Update cover art from YT
     */
    Thread image = new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                // Connect to URL
                Log.e(TAG, "Connecting to YT API for data.");
                URL jsonUrl = new URL("https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key="
                        + Constants.YT_API_KEY + "&part=snippet");
                HttpURLConnection request = (HttpURLConnection) jsonUrl.openConnection();
                request.connect();

                // Convert to json object
                JsonParser parser = new JsonParser();
                JsonElement root = parser.parse(new InputStreamReader((InputStream) request.getContent()));
                JsonObject object = root.getAsJsonObject();
                JsonObject thumbnails = object.getAsJsonArray("items").get(0).getAsJsonObject()
                        .getAsJsonObject("snippet").getAsJsonObject("thumbnails");

                // Change artist name
                boolean standard = thumbnails.has("standard");
                boolean maxres = thumbnails.has("maxres");

                // Download highest quality image
                if (maxres) {
                    String link = thumbnails.getAsJsonObject("maxres").get("url").toString();
                    link = link.substring(1, link.length() - 1);
                    ImageDownloadUtils.downloadSongArt(link, songId, albumId, context);
                    Log.e(TAG, "Downloading max res image.");
                } else if (standard) {
                    String link = thumbnails.getAsJsonObject("standard").get("url").toString();
                    link = link.substring(1, link.length() - 1);
                    ImageDownloadUtils.downloadSongArt(link, songId, albumId, context);
                    Log.e(TAG, "Downloading standard res image.");
                } else {
                    String link = thumbnails.getAsJsonObject("high").get("url").toString();
                    link = link.substring(1, link.length() - 1);
                    ImageDownloadUtils.downloadSongArt(link, songId, albumId, context);
                    Log.e(TAG, "Downloading low res image.");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    /*
    Get data from Youtube API, key in Constants.java
     */
    Thread metadata = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                // Connect to URL
                URL jsonUrl = new URL("https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key="
                        + Constants.YT_API_KEY + "&part=snippet");
                HttpURLConnection request = (HttpURLConnection) jsonUrl.openConnection();
                request.connect();

                // Convert to json object
                JsonParser parser = new JsonParser();
                JsonElement root = parser.parse(new InputStreamReader((InputStream) request.getContent()));
                JsonObject object = root.getAsJsonObject();
                JsonObject snippet = object.getAsJsonArray("items").get(0).getAsJsonObject()
                        .getAsJsonObject("snippet");

                /*
                for (Map.Entry<String, JsonElement> entry: artistObject.entrySet()) {
                Log.e(TAG, entry.getKey());
                if (entry.getKey().equals("channelTitle")) {
                    MediaDataUtils.changeSongArtist(songId, entry.getValue().toString(), context);
                    Log.e(TAG, "Changed artist to " + entry.getValue().toString() + ".");
                }
                }
                */

                // Change artist name
                String artist = snippet.get("channelTitle").toString();
                artist = artist.substring(1, artist.length() - 1);
                MediaDataUtils.changeSongArtist(songId, artist, context);

                // TODO Find better album names?
                String album = snippet.get("title").toString();
                album = album.substring(1, album.length() - 1);
                MediaDataUtils.changeSongAlbum(songId, album, context);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    // Wait for completions
    metadata.start();
    image.start();
    try {
        metadata.join();
        image.join();
    } catch (Exception e) {
        e.printStackTrace();
    }
    Log.d(TAG, "Finished waiting for image and metadata change.");
}

From source file:com.mattprecious.notisync.message.BaseMessage.java

License:Apache License

public static BaseMessage fromJsonString(String jsonString) {
    BaseMessage message = null;/*w  ww. j  a v a  2  s  .co m*/
    try {
        JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();
        String dataTypeStr = json.get("DATA_TYPE").getAsString();
        if (ClearMessage.class.getName().equals(dataTypeStr)) {
            Log.d("BaseMessage", "ClearMessage");
            json = json.getAsJsonObject("message");
            Class<?> dataType = Class.forName(json.get("DATA_TYPE").getAsString());

            BaseMessage subMessage = (BaseMessage) new Gson().fromJson(json, dataType);
            message = new ClearMessage(subMessage);
        } else {
            Log.d("BaseMessage", dataTypeStr);
            Class<?> dataType = Class.forName(json.get("DATA_TYPE").getAsString());
            message = (BaseMessage) new Gson().fromJson(json, dataType);
        }
    } catch (ClassNotFoundException e) {
        MyLog.e("BaseMessage", "Failed to convert to BaseMessage", e);
    }

    return message;
}

From source file:com.microsoft.applicationinsights.contracts.ContainerStateEvent.java

License:Open Source License

private void deserialize(String json) {
    JsonObject jsonObj = new JsonParser().parse(json).getAsJsonObject();
    this.eventName = jsonObj.get("name").getAsString();
    this.ikey = jsonObj.get("ikey").getAsString();

    JsonObject propertiesObject = jsonObj.getAsJsonObject("properties");

    for (Map.Entry<String, JsonElement> kv : propertiesObject.entrySet()) {
        this.properties.put(kv.getKey(), kv.getValue().getAsString());
    }//from   w w  w  . j  a v a2s .c  o m
}

From source file:com.microsoft.applicationinsights.contracts.ContainerStatsMetric.java

License:Open Source License

private void deserialize(String json) {
    JsonObject jsonObj = new JsonParser().parse(json).getAsJsonObject();
    JsonObject metricJson = jsonObj.getAsJsonObject("metric");

    this.metricName = metricJson.get("name").getAsString();
    this.value = metricJson.get("value").getAsDouble();
    this.count = metricJson.get("count").getAsInt();
    this.min = metricJson.get("min").getAsDouble();
    this.max = metricJson.get("max").getAsDouble();
    this.stdDev = metricJson.get("std").getAsDouble();

    JsonObject propertiesJson = jsonObj.getAsJsonObject("properties");
    this.dockerHost = propertiesJson.get(Constants.DOCKER_HOST_PROPERTY_KEY).getAsString();
    this.dockerImage = propertiesJson.get(Constants.DOCKER_IMAGE_PROPERTY_KEY).getAsString();
    this.dockerContainerName = propertiesJson.get(Constants.DOCKER_CONTAINER_NAME_PROPERTY_KEY).getAsString();
    this.dockerContainerId = propertiesJson.get(Constants.DOCKER_CONTAINER_ID_PROPERTY_KEY).getAsString();
}