Example usage for com.google.gson JsonPrimitive getAsString

List of usage examples for com.google.gson JsonPrimitive getAsString

Introduction

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

Prototype

@Override
public String getAsString() 

Source Link

Document

convenience method to get this element as a String.

Usage

From source file:com.google.gms.googleservices.GoogleServicesTask.java

License:Apache License

/**
 * Finds a service by name in the client object. Returns null if the service is not found
 * or if the service is disabled./* www .  ja va 2s.c  om*/
 *
 * @param clientObject the json object that represents the client.
 * @param serviceName the service name
 * @return the service if found.
 */
private JsonObject getServiceByName(JsonObject clientObject, String serviceName) {
    JsonObject services = clientObject.getAsJsonObject("services");
    if (services == null)
        return null;

    JsonObject service = services.getAsJsonObject(serviceName);
    if (service == null)
        return null;

    JsonPrimitive status = service.getAsJsonPrimitive("status");
    if (status == null)
        return null;

    String statusStr = status.getAsString();

    if (STATUS_DISABLED.equals(statusStr))
        return null;
    if (!STATUS_ENABLED.equals(statusStr)) {
        getLogger().warn(String.format("Status with value '%1$s' for service '%2$s' is unknown", statusStr,
                serviceName));
        return null;
    }

    return service;
}

From source file:com.google.gwtjsonrpc.server.SqlDateDeserializer.java

License:Apache License

public java.sql.Date deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonNull()) {
        return null;
    }/*from w  w  w.  ja v  a 2  s.  c  om*/
    if (!json.isJsonPrimitive()) {
        throw new JsonParseException("Expected string for date type");
    }
    final JsonPrimitive p = (JsonPrimitive) json;
    if (!p.isString()) {
        throw new JsonParseException("Expected string for date type");
    }
    try {
        return java.sql.Date.valueOf(p.getAsString());
    } catch (IllegalArgumentException e) {
        throw new JsonParseException("Not a date string");
    }
}

From source file:com.google.gwtjsonrpc.server.SqlTimestampDeserializer.java

License:Apache License

public java.sql.Timestamp deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonNull()) {
        return null;
    }/*w  w w.j av  a  2  s .  c  o m*/
    if (!json.isJsonPrimitive()) {
        throw new JsonParseException("Expected string for timestamp type");
    }
    final JsonPrimitive p = (JsonPrimitive) json;
    if (!p.isString()) {
        throw new JsonParseException("Expected string for timestamp type");
    }

    return JavaSqlTimestamp_JsonSerializer.parseTimestamp(p.getAsString());
}

From source file:com.google.iosched.model.DataCheck.java

License:Open Source License

/**
 * @param sources/* w ww .  j  a  v  a  2s  .  c  o  m*/
 */
public CheckResult check(JsonDataSources sources, JsonObject newSessionData, ManifestData manifest)
        throws IOException {
    newSessionData = clone(newSessionData);
    JsonObject newData = new JsonObject();
    merge(newSessionData, newData);
    JsonObject oldData = new JsonObject();
    for (JsonElement dataFile : manifest.dataFiles) {
        String filename = dataFile.getAsString();
        // except for session data, merge all other files:
        Matcher matcher = Config.SESSIONS_PATTERN.matcher(filename);
        if (!matcher.matches()) {
            JsonObject data = fileManager.readFileAsJsonObject(filename);
            merge(data, oldData);
            merge(data, newData);
        }
    }

    CheckResult result = new CheckResult();

    // check if array of entities is more than 80% the size of the old data:
    checkUsingPredicator(result, oldData, newData, new ArraySizeValidator());

    // Check that no existing tag was removed or had its name changed in a significant way
    checkUsingPredicator(result, oldData, newData, OutputJsonKeys.MainTypes.tags, OutputJsonKeys.Tags.tag,
            new EntityValidator() {
                @Override
                public void evaluate(CheckResult result, String entity, JsonObject oldData,
                        JsonObject newData) {
                    if (newData == null) {
                        String tagName = get(oldData, OutputJsonKeys.Tags.tag).getAsString();
                        String originalId = get(oldData, OutputJsonKeys.Tags.original_id).getAsString();
                        result.failures.add(new CheckFailure(entity, tagName,
                                "Tag could not be found or changed name. Original category ID = "
                                        + originalId));
                    }
                }
            });

    // Check that no room was removed
    checkUsingPredicator(result, oldData, newData, OutputJsonKeys.MainTypes.rooms, OutputJsonKeys.Rooms.id,
            new EntityValidator() {
                @Override
                public void evaluate(CheckResult result, String entity, JsonObject oldData,
                        JsonObject newData) {
                    if (newData == null) {
                        String id = get(oldData, OutputJsonKeys.Rooms.id).getAsString();
                        result.failures.add(new CheckFailure(entity, id,
                                "Room could not be found. Original room: " + oldData));
                    }
                }
            });

    // Check if blocks start and end timestamps are valid
    JsonArray newBlocks = getAsArray(newData, OutputJsonKeys.MainTypes.blocks);
    if (newBlocks == null) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, JsonElement> entry : newData.entrySet()) {
            sb.append(entry.getKey()).append(", ");
        }
        throw new IllegalArgumentException(
                "Could not find the blocks entities. Entities in newData are: " + sb);
    }
    for (JsonElement el : newBlocks) {
        JsonObject block = el.getAsJsonObject();
        try {
            Date start = blockDateFormat.parse(get(block, OutputJsonKeys.Blocks.start).getAsString());
            Date end = blockDateFormat.parse(get(block, OutputJsonKeys.Blocks.end).getAsString());
            if (start.getTime() >= end.getTime() || // check for invalid start/end combinations
                    start.getTime() < Config.CONFERENCE_DAYS[0][0] || // check for block starting before the conference
                    end.getTime() > Config.CONFERENCE_DAYS[1][1]) { // check for block ending after the conference
                result.failures.add(new CheckFailure(OutputJsonKeys.MainTypes.blocks.name(), null,
                        "Invalid block start or end date. Block=" + block));
            }
        } catch (ParseException ex) {
            result.failures.add(new CheckFailure(OutputJsonKeys.MainTypes.blocks.name(), null,
                    "Could not parse block start or end date. Exception=" + ex.getMessage() + ". Block="
                            + block));
        }
    }

    // Check if sessions start and end timestamps are valid
    JsonArray newSessions = getAsArray(newData, OutputJsonKeys.MainTypes.sessions);
    for (JsonElement el : newSessions) {
        JsonObject session = el.getAsJsonObject();
        try {
            Date start = sessionDateFormat
                    .parse(get(session, OutputJsonKeys.Sessions.startTimestamp).getAsString());
            Date end = sessionDateFormat
                    .parse(get(session, OutputJsonKeys.Sessions.endTimestamp).getAsString());
            if (start.getTime() >= end.getTime()) { // check for invalid start/end combinations
                result.failures.add(new CheckFailure(OutputJsonKeys.MainTypes.sessions.name(),
                        get(session, OutputJsonKeys.Sessions.id).getAsString(),
                        "Session ends before or at the same time as it starts. Session=" + session));
            } else if (end.getTime() - start.getTime() > 6 * 60 * 60 * 1000L) { // check for session longer than 6 hours
                result.failures.add(new CheckFailure(OutputJsonKeys.MainTypes.sessions.name(),
                        get(session, OutputJsonKeys.Sessions.id).getAsString(),
                        "Session is longer than 6 hours. Session=" + session));
            } else if (start.getTime() < Config.CONFERENCE_DAYS[0][0] || // check for session starting before the conference
                    end.getTime() > Config.CONFERENCE_DAYS[1][1]) { // check for session ending after the conference
                result.failures.add(new CheckFailure(OutputJsonKeys.MainTypes.sessions.name(),
                        get(session, OutputJsonKeys.Sessions.id).getAsString(),
                        "Session starts before or ends after the days of the conference. Session=" + session));
            } else {
                // Check if all sessions are covered by at least one free block (except the keynote):
                boolean valid = false;
                if (!get(session, OutputJsonKeys.Sessions.id).getAsString().equals("__keynote__")) {
                    for (JsonElement bl : newBlocks) {
                        JsonObject block = bl.getAsJsonObject();
                        Date blockStart = blockDateFormat
                                .parse(get(block, OutputJsonKeys.Blocks.start).getAsString());
                        Date blockEnd = blockDateFormat
                                .parse(get(block, OutputJsonKeys.Blocks.end).getAsString());
                        String blockType = get(block, OutputJsonKeys.Blocks.type).getAsString();
                        if ("free".equals(blockType) && start.compareTo(blockStart) >= 0
                                && start.compareTo(blockEnd) < 0) {
                            valid = true;
                            break;
                        }
                    }
                    if (!valid) {
                        result.failures.add(new CheckFailure(OutputJsonKeys.MainTypes.sessions.name(),
                                get(session, OutputJsonKeys.Sessions.id).getAsString(),
                                "There is no FREE block where this session start date lies on. Session="
                                        + session));
                    }
                }
            }
        } catch (ParseException ex) {
            result.failures.add(new CheckFailure(OutputJsonKeys.MainTypes.sessions.name(),
                    get(session, OutputJsonKeys.Sessions.id).getAsString(),
                    "Could not parse session start or end date. Exception=" + ex.getMessage() + ". Session="
                            + session));
        }
    }

    // Check if video sessions (video library) have valid video URLs
    JsonArray newVideoLibrary = getAsArray(newData, OutputJsonKeys.MainTypes.video_library);
    for (JsonElement el : newVideoLibrary) {
        JsonObject session = el.getAsJsonObject();
        JsonPrimitive videoUrl = (JsonPrimitive) get(session, OutputJsonKeys.VideoLibrary.vid);
        if (videoUrl == null || !videoUrl.isString() || videoUrl.getAsString() == null
                || videoUrl.getAsString().isEmpty()) {
            result.failures.add(new CheckFailure(InputJsonKeys.VendorAPISource.MainTypes.topics.name(),
                    "" + get(session, OutputJsonKeys.VideoLibrary.id),
                    "Video Session has empty vid info. Session: " + session));
        }
    }

    return result;
}

From source file:com.google.iosched.model.DataExtractor.java

License:Open Source License

private boolean isLivestreamed(JsonObject sessionObj) {
    // data generated after the end of the conference should never have livestream URLs
    long endOfConference = Config.CONFERENCE_DAYS[Config.CONFERENCE_DAYS.length - 1][1];
    if (System.currentTimeMillis() > endOfConference) {
        return false;
    }/*  ww  w  . j a va  2 s .co  m*/
    JsonPrimitive livestream = getMapValue(get(sessionObj, VendorAPISource.Topics.info),
            InputJsonKeys.VendorAPISource.Topics.INFO_IS_LIVE_STREAM, null, null);
    return livestream != null && "true".equalsIgnoreCase(livestream.getAsString());
}

From source file:com.google.iosched.model.DataExtractor.java

License:Open Source License

private void setVideoPropertiesInSession(JsonObject origin, JsonObject dest) {
    boolean isLivestream = isLivestreamed(origin);
    set(new JsonPrimitive(isLivestream), dest, OutputJsonKeys.Sessions.isLivestream);

    JsonPrimitive vid = null;

    if (isLivestream) {
        vid = getVideoFromTopicInfo(origin, InputJsonKeys.VendorAPISource.Topics.INFO_STREAM_VIDEO_ID,
                Config.VIDEO_LIVESTREAMURL_FOR_EMPTY);
    } else {/*from   w  w w.j a v a2s  . c  o m*/
        vid = getMapValue(get(origin, VendorAPISource.Topics.info), VendorAPISource.Topics.INFO_VIDEO_URL,
                Converters.YOUTUBE_URL, null);
    }
    if (vid != null && !vid.getAsString().isEmpty()) {
        set(vid, dest, OutputJsonKeys.Sessions.youtubeUrl);
    }
}

From source file:com.google.iosched.model.DataExtractor.java

License:Open Source License

private JsonPrimitive getVideoFromTopicInfo(JsonObject origin, String sourceInfoKey, String defaultVideoUrl) {
    JsonPrimitive result = null;//from  w  ww .  j a va  2  s  . c om

    JsonPrimitive vid = getMapValue(get(origin, VendorAPISource.Topics.info), sourceInfoKey, null,
            defaultVideoUrl);
    if (!vid.getAsString().isEmpty()) {
        result = vid;
    }
    return (result == null && defaultVideoUrl != null) ? new JsonPrimitive(defaultVideoUrl) : result;
}

From source file:com.google.iosched.model.DataExtractor.java

License:Open Source License

private JsonPrimitive setVideoForVideoSession(JsonObject origin, JsonObject dest) {
    JsonPrimitive vid = getVideoFromTopicInfo(origin, InputJsonKeys.VendorAPISource.Topics.INFO_VIDEO_URL,
            null);/* w  ww  . j av a 2 s.  co m*/
    if (vid != null) {
        set(vid, dest, OutputJsonKeys.VideoLibrary.vid);
        JsonPrimitive thumbnail = new JsonPrimitive(
                "http://img.youtube.com/vi/" + vid.getAsString() + "/hqdefault.jpg");
        set(thumbnail, dest, OutputJsonKeys.VideoLibrary.thumbnailUrl);
    }
    return vid;
}

From source file:com.google.iosched.model.validator.BooleanConverter.java

License:Open Source License

@Override
public JsonPrimitive convert(JsonPrimitive value) {
    if (value == null) {
        return new JsonPrimitive(false);
    }//from   w w w  . j a  va  2  s. c om
    if (value.isBoolean()) {
        return value;
    }
    String str = value.getAsString();
    if (str.equalsIgnoreCase("false")) {
        return new JsonPrimitive(false);
    }
    if (str.equalsIgnoreCase("true")) {
        return new JsonPrimitive(true);
    }
    throw new ConverterException(value, this);
}

From source file:com.google.iosched.model.validator.DateTimeConverter.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override/*  ww w . j  av a 2  s . c o  m*/
public JsonPrimitive convert(JsonPrimitive value) {
    if (value == null) {
        return null;
    }
    Date date = null;
    Exception lastEx = null;
    for (int i = 0; i < inputFormats.length && date == null; i++) {
        try {
            date = inputFormats[i].parse(value.getAsString());
        } catch (NumberFormatException e) {
            lastEx = e;
        } catch (ParseException e) {
            lastEx = e;
        }
    }

    if (date == null) {
        throw new ConverterException(value, this, lastEx.getMessage());
    }

    if (date.getYear() < 100) {
        // hack to fix invalid dates on temporary data
        date.setYear(114);
        date.setMonth(Calendar.JUNE);
        date.setDate(25);
    }
    if (Config.TIME_TRAVEL_SHIFT != 0) {
        date = new Date(date.getTime() + Config.TIME_TRAVEL_SHIFT);
    }
    return new JsonPrimitive(outputFormat.format(date));
}