Example usage for com.google.gson JsonObject entrySet

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

Introduction

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

Prototype

public Set<Map.Entry<String, JsonElement>> entrySet() 

Source Link

Document

Returns a set of members of this object.

Usage

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

License:Apache License

public Map<Object, Object> deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    final Type kt = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
    final Type vt = ((ParameterizedType) typeOfT).getActualTypeArguments()[1];

    if (json.isJsonNull()) {
        return null;
    }/*w  w w.  ja v  a 2 s .  com*/

    if (kt == String.class) {
        if (!json.isJsonObject()) {
            throw new JsonParseException("Expected object for map type");
        }
        final JsonObject p = (JsonObject) json;
        final Map<Object, Object> r = createInstance(typeOfT);
        for (final Map.Entry<String, JsonElement> e : p.entrySet()) {
            final Object v = context.deserialize(e.getValue(), vt);
            r.put(e.getKey(), v);
        }
        return r;
    } else {
        if (!json.isJsonArray()) {
            throw new JsonParseException("Expected array for map type");
        }

        final JsonArray p = (JsonArray) json;
        final Map<Object, Object> r = createInstance(typeOfT);
        for (int n = 0; n < p.size();) {
            final Object k = context.deserialize(p.get(n++), kt);
            final Object v = context.deserialize(p.get(n++), vt);
            r.put(k, v);
        }
        return r;
    }
}

From source file:com.google.identitytoolkit.GitkitVerifierManager.java

License:Open Source License

@VisibleForTesting
Map<String, String> parseCertsResponse(String response) throws GitkitServerException {
    try {// ww  w.j  a va 2 s  .co  m
        JsonObject jsonCerts = new JsonParser().parse(response).getAsJsonObject();
        Map<String, String> certs = Maps.newHashMap();
        for (Map.Entry<String, JsonElement> entry : jsonCerts.entrySet()) {
            certs.put(entry.getKey(), entry.getValue().getAsString());
        }
        return certs;
    } catch (JsonSyntaxException e) {
        throw new GitkitServerException(e);
    }
}

From source file:com.google.iosched.input.fetcher.RemoteJsonHelper.java

License:Open Source License

public static JsonObject mergeJsonFiles(JsonObject target, String... filenames) throws IOException {
    if (target == null) {
        target = new JsonObject();
    }/*from ww w . j a va 2s . com*/
    for (String filename : filenames) {
        String url = Config.CLOUD_STORAGE_BASE_URL + filename;
        JsonObject obj = fetchJsonFromPublicURL(url);
        if (obj == null) {
            throw new FileNotFoundException(url);
        } else {
            for (Entry<String, JsonElement> entry : obj.entrySet()) {
                if (entry.getValue().isJsonArray()) {
                    // tries to merge an array with the existing one, if it's the case:
                    JsonArray existing = target.getAsJsonArray(entry.getKey());
                    if (existing == null) {
                        existing = new JsonArray();
                        target.add(entry.getKey(), existing);
                    }
                    existing.addAll(entry.getValue().getAsJsonArray());
                } else {
                    target.add(entry.getKey(), entry.getValue());
                }
            }
        }
    }
    return target;
}

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

License:Open Source License

/**
 * @param sources/* w  w  w.  j ava  2s.com*/
 */
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.DataCheck.java

License:Open Source License

public void checkUsingPredicator(CheckResult result, JsonObject oldData, JsonObject newData,
        ArrayValidator predicate) {/*from   www  .  j  av a 2s  . c om*/
    for (Map.Entry<String, JsonElement> entry : oldData.entrySet()) {
        String oldKey = entry.getKey();
        JsonArray oldValues = entry.getValue().getAsJsonArray();
        predicate.evaluate(result, oldKey, oldValues, newData.getAsJsonArray(oldKey));
    }
}

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

License:Open Source License

private JsonObject clone(JsonObject source) {
    JsonObject dest = new JsonObject();
    for (Map.Entry<String, JsonElement> entry : source.entrySet()) {
        JsonArray values = entry.getValue().getAsJsonArray();
        JsonArray cloned = new JsonArray();
        cloned.addAll(values);/*from   w w w. j  a  v  a 2 s. c  o  m*/
        dest.add(entry.getKey(), cloned);
    }
    return dest;
}

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

License:Open Source License

private void merge(JsonObject source, JsonObject dest) {
    for (Map.Entry<String, JsonElement> entry : source.entrySet()) {
        JsonArray values = entry.getValue().getAsJsonArray();
        if (dest.has(entry.getKey())) {
            dest.get(entry.getKey()).getAsJsonArray().addAll(values);
        } else {/*from   w  w  w.  j av a2s  . c o  m*/
            dest.add(entry.getKey(), values);
        }
    }
}

From source file:com.google.iosched.server.input.fetcher.CloudStorageRemoteFilesEntityFetcher.java

License:Open Source License

@Override
public JsonElement fetch(Enum<?> entityType, Map<String, String> params) throws IOException {
    // On the first call, read all the files
    if (object == null) {
        object = new JsonObject();
        for (String filename : filenames) {
            JsonObject obj = fileManager.readFileAsJsonObject(filename);
            if (obj == null
                    && SystemProperty.environment.value() == SystemProperty.Environment.Value.Development) {
                // In the development server, cloud storage files cannot be directly accessed.
                obj = RemoteJsonHelper.fetchJsonFromPublicURL(Config.CLOUD_STORAGE_BASE_URL + filename);
            }//from  ww  w  .java2  s.c om
            if (obj == null) {
                LOGGER.warning("Could not find file " + filename);
            } else {
                for (Entry<String, JsonElement> entry : obj.entrySet()) {
                    object.add(entry.getKey(), entry.getValue());
                }
            }
        }
    }
    return object.get(entityType.name());
}

From source file:com.google.iosched.server.UpdateRunLogger.java

License:Open Source License

public void logUpdateRun(int majorVersion, int minorVersion, String filename, byte[] hash, JsonObject data,
        boolean forced) {
    Entity updateRun = new Entity(UPDATERUN_ENTITY_KIND);
    updateRun.setProperty("date", new Date());
    updateRun.setProperty("hash", new ShortBlob(hash));
    updateRun.setProperty("forced", forced);
    updateRun.setProperty("majorVersion", majorVersion);
    updateRun.setProperty("minorVersion", minorVersion);
    for (Entry<String, Long> performanceItem : timers.entrySet()) {
        updateRun.setProperty("time_" + performanceItem.getKey(), performanceItem.getValue());
    }// w  w  w .  j  a  v a  2s. co m
    updateRun.setProperty("filename", filename);
    StringBuilder sb = new StringBuilder();
    for (Entry<String, JsonElement> el : data.entrySet()) {
        if (el.getValue().isJsonArray()) {
            sb.append(el.getKey()).append("=").append(el.getValue().getAsJsonArray().size()).append(" ");
        }
    }
    if (sb.length() > 0) {
        // remove trailing space
        sb.deleteCharAt(sb.length() - 1);
    }
    updateRun.setProperty("summary", sb.toString());
    datastore.put(updateRun);
    timers.clear();
}

From source file:com.google.wallet.online.jwt.util.JwtGenerator.java

License:Open Source License

/**
 * Generates the Json Web Token (JWT) based on BaseJWT object provided.
 * @param target the BaseJWT object to convert into a JWT string.
 * @return Signed Json Web Token./*from  w  ww. j a va2 s .c  o  m*/
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public static String javaToJWT(BaseJwt target, String merchantSecret)
        throws InvalidKeyException, SignatureException {

    Clock clock = new SystemClock();

    JsonObject jsonData = GsonHelper.getGson().toJsonTree(target).getAsJsonObject();

    // Get signer for JWT
    HmacSHA256Signer signer = new HmacSHA256Signer(target.getIss(), null, merchantSecret.getBytes());

    // Create new JWT and set params
    JsonToken token = new JsonToken(signer);

    // Get the payload object to modify
    JsonObject payload = token.getPayloadAsJsonObject();

    Set<Map.Entry<String, JsonElement>> params = jsonData.entrySet();

    // Iterate through HashMap adding each item to the payload
    for (Map.Entry<String, JsonElement> param : params) {
        payload.add(param.getKey(), param.getValue());
    }

    if (token.getIssuedAt() == null) {
        token.setIssuedAt(clock.now());
    }
    if (token.getExpiration() == null) {
        token.setExpiration(clock.now().plus(EXPIRATION_DELTA));
    }

    return token.serializeAndSign();
}