Example usage for com.google.gson JsonPrimitive isString

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

Introduction

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

Prototype

public boolean isString() 

Source Link

Document

Check whether this primitive contains a String value.

Usage

From source file:com.facebook.buck.json.RawParser.java

License:Apache License

/**
 * @return One of: String, Boolean, Long, Number, List<Object>, Map<String, Object>.
 *//*from   w w  w  .ja v a2 s.c o  m*/
@Nullable
@VisibleForTesting
static Object toRawTypes(JsonElement json) {
    // Cases are ordered from most common to least common.
    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            return interner.intern(primitive.getAsString());
        } else if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isNumber()) {
            Number number = primitive.getAsNumber();
            // Number is likely an instance of class com.google.gson.internal.LazilyParsedNumber.
            if (number.longValue() == number.doubleValue()) {
                return number.longValue();
            } else {
                return number;
            }
        } else {
            throw new IllegalStateException("Unknown primitive type: " + primitive);
        }
    } else if (json.isJsonArray()) {
        JsonArray array = json.getAsJsonArray();
        List<Object> out = Lists.newArrayListWithCapacity(array.size());
        for (JsonElement item : array) {
            out.add(toRawTypes(item));
        }
        return out;
    } else if (json.isJsonObject()) {
        Map<String, Object> out = new LinkedHashMap<>(json.getAsJsonObject().entrySet().size());
        for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            // On a large project, without invoking intern(), we have seen `buck targets` OOM. When this
            // happened, according to the .hprof file generated using -XX:+HeapDumpOnOutOfMemoryError,
            // 39.6% of the memory was spent on char[] objects while 14.5% was spent on Strings.
            // (Another 10.5% was spent on java.util.HashMap$Entry.) Introducing intern() stopped the
            // OOM from happening.
            out.put(interner.intern(entry.getKey()), toRawTypes(entry.getValue()));
        }
        return out;
    } else if (json.isJsonNull()) {
        return null;
    } else {
        throw new IllegalStateException("Unknown type: " + json);
    }
}

From source file:com.flipkart.polyguice.config.JsonConfiguration.java

License:Apache License

private void flatten(String prefix, JsonElement element) {
    if (element.isJsonPrimitive()) {
        JsonPrimitive jsonPrim = element.getAsJsonPrimitive();
        if (jsonPrim.isBoolean()) {
            configTab.put(prefix, jsonPrim.getAsBoolean());
        } else if (jsonPrim.isNumber()) {
            configTab.put(prefix, jsonPrim.getAsNumber());
        } else if (jsonPrim.isString()) {
            configTab.put(prefix, jsonPrim.getAsString());
        }// ww w .j  a v a2  s.c  om
    } else if (element.isJsonObject()) {
        JsonObject jsonObj = element.getAsJsonObject();
        for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
            String prefix1 = ((prefix != null) ? prefix + "." : "") + entry.getKey();
            flatten(prefix1, entry.getValue());
        }
    }
}

From source file:com.frontier45.flume.sink.elasticsearch2.ElasticSearchLogStashEventSerializer.java

License:Apache License

private Object getValue(JsonElement obj) {
    JsonPrimitive jp = obj.getAsJsonPrimitive();
    if (jp.isBoolean()) {
        return jp.getAsBoolean();
    } else if (jp.isNumber()) {
        String value = jp.getAsString();
        if (value.indexOf(".") > 0) {
            return jp.getAsDouble();
        } else {/*from w  ww.ja v  a 2  s.  c o  m*/
            return jp.getAsLong();
        }
    } else if (jp.isString()) {
        return jp.getAsString();
    }
    return obj;
}

From source file:com.github.autermann.matlab.json.MatlabValueSerializer.java

License:Open Source License

private MatlabScalar parseMatlabScalar(JsonElement value) {
    JsonPrimitive p = (JsonPrimitive) value;
    if (p.isString()) {
        return new MatlabScalar(Double.valueOf(p.getAsString()));
    } else {/*w  w w  .  ja  v  a 2  s  . c  o m*/
        return new MatlabScalar(p.getAsDouble());
    }
}

From source file:com.github.maoo.indexer.client.WebScriptsAlfrescoClient.java

License:Apache License

private List<String> getAuthorities(JsonObject userObject) {
    List<String> authorities = new ArrayList<String>();
    if (!userObject.has(AUTHORITIES)) {
        throw new AlfrescoParseException("Json response is authorities.");
    }/*from ww w .jav  a2s.  com*/
    JsonElement authoritiesElement = userObject.get(AUTHORITIES);
    if (!authoritiesElement.isJsonArray()) {
        throw new AlfrescoParseException(
                "Authorities must be a json array. It was: " + authoritiesElement.toString());
    }
    JsonArray authoritiesArray = authoritiesElement.getAsJsonArray();
    for (JsonElement authorityElement : authoritiesArray) {
        if (!authorityElement.isJsonPrimitive()) {
            throw new AlfrescoParseException(
                    "Authority entry must be a string. It was: " + authoritiesElement.toString());
        }
        JsonPrimitive authorityPrimitive = authorityElement.getAsJsonPrimitive();
        if (!authorityPrimitive.isString()) {
            throw new AlfrescoParseException(
                    "Authority entry must be a string. It was: " + authoritiesElement.toString());
        }
        authorities.add(authorityPrimitive.getAsString());
    }
    return authorities;
}

From source file:com.github.strawberry.util.Json.java

License:Open Source License

public static Object parsePrimitive(JsonElement e) {
    JsonPrimitive p = e.getAsJsonPrimitive();
    if (p.isString()) {
        return e.getAsString();
    }/*w  w w  .j a  v  a  2 s.  c  o  m*/
    if (p.isBoolean()) {
        return e.getAsBoolean();
    }
    if (p.isNumber()) {
        return e.getAsInt();
    }
    return p.getAsString();
}

From source file:com.google.appinventor.components.runtime.GoogleMap.java

License:Open Source License

@SimpleFunction(description = "Adding a list of markers that are represented as JsonArray. "
        + " The inner JsonObject represents a marker"
        + "and is composed of name-value pairs. Name fields for a marker are: "
        + "\"lat\" (type double) [required], \"lng\"(type double) [required], "
        + "\"color\"(type int)[in hue value ranging from 0~360], "
        + "\"title\"(type String), \"snippet\"(type String), \"draggable\"(type boolean)")
public void AddMarkersFromJson(String jsonString) {
    ArrayList<Integer> markerIds = new ArrayList<Integer>();
    JsonParser parser = new JsonParser();
    float[] hsv = new float[3];

    // parse jsonString into jsonArray
    try {//from   w w w .j a va2s .  co  m
        JsonElement markerList = parser.parse(jsonString);
        if (markerList.isJsonArray()) {
            JsonArray markerArray = markerList.getAsJsonArray();

            Log.i(TAG, "It's a JsonArry: " + markerArray.toString());
            for (JsonElement marker : markerArray) {
                boolean addOne = true;
                // now we have marker
                if (marker.isJsonObject()) {
                    JsonObject markerJson = marker.getAsJsonObject();
                    if (markerJson.get("lat") == null || markerJson.get("lng") == null) {
                        addOne = false;

                    } else { // having correct syntax of a marker in Json

                        // check for cases: "lat" : "40.7561"  (as String)
                        JsonPrimitive jpLat = (JsonPrimitive) markerJson.get("lat");
                        JsonPrimitive jpLng = (JsonPrimitive) markerJson.get("lng");

                        double latitude = 0;
                        double longitude = 0;

                        try { //it's possible that when converting to Double, we will have errors
                              // for example, some json has "lat": "" (empty string for lat, lng values)

                            if (jpLat.isString() && jpLng.isString()) {
                                Log.i(TAG, "jpLat:" + jpLat.toString());
                                Log.i(TAG, "jpLng:" + jpLng.toString());

                                latitude = new Double(jpLat.getAsString());
                                longitude = new Double(jpLng.getAsString());
                                Log.i(TAG, "convert to double:" + latitude + "," + longitude);
                            } else {
                                latitude = markerJson.get("lat").getAsDouble();
                                longitude = markerJson.get("lng").getAsDouble();
                            }

                        } catch (NumberFormatException e) {
                            addOne = false;
                        }
                        // check for Lat, Lng correct range

                        if ((latitude < -90) || (latitude > 90) || (longitude < -180) || (longitude > 180)) {
                            Log.i(TAG, "Lat/Lng wrong range:" + latitude + "," + longitude);
                            addOne = false;

                        }

                        Color.colorToHSV(mMarkerColor, hsv);
                        float defaultColor = hsv[0];
                        float color = (markerJson.get("color") == null) ? defaultColor
                                : markerJson.get("color").getAsInt();

                        if ((color < 0) || (color > 360)) {
                            Log.i(TAG, "Wrong color");
                            addOne = false;
                        }

                        String title = (markerJson.get("title") == null) ? ""
                                : markerJson.get("title").getAsString();
                        String snippet = (markerJson.get("snippet") == null) ? ""
                                : markerJson.get("snippet").getAsString();
                        boolean draggable = (markerJson.get("draggable") == null) ? mMarkerDraggable
                                : markerJson.get("draggable").getAsBoolean();

                        if (addOne) {
                            Log.i(TAG, "Adding marker" + latitude + "," + longitude);
                            int uniqueId = generateMarkerId();
                            markerIds.add(uniqueId);
                            addMarkerToMap(latitude, longitude, uniqueId, color, title, snippet, draggable);
                        }
                    }
                }
            } //end of JsonArray

        } else { // not a JsonArray
            form.dispatchErrorOccurredEvent(this, "AddMarkersFromJson",
                    ErrorMessages.ERROR_GOOGLE_MAP_INVALID_INPUT,
                    "markers needs to be represented as JsonArray");
            markersList = YailList.makeList(markerIds);
        }

    } catch (JsonSyntaxException e) {
        form.dispatchErrorOccurredEvent(this, "AddMarkersFromJson",
                ErrorMessages.ERROR_GOOGLE_MAP_JSON_FORMAT_DECODE_FAILED, jsonString);
        markersList = YailList.makeList(markerIds); // return an empty markerIds list
    }

    markersList = YailList.makeList(markerIds);
    //  return YailList.makeList(markerIds);
}

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;
    }/*  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;
    }/*from www .j a v  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  2 s  . c om
 */
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;
}