Search in sources :

Example 46 with JsonElement

use of com.google.gson.JsonElement in project weave by continuuity.

the class YarnWeaveRunnerService method getApplicationId.

/**
   * Decodes application ID stored inside the node data.
   * @param nodeData The node data to decode from. If it is {@code null}, this method would return {@code null}.
   * @return The ApplicationId or {@code null} if failed to decode.
   */
private ApplicationId getApplicationId(NodeData nodeData) {
    byte[] data = nodeData == null ? null : nodeData.getData();
    if (data == null) {
        return null;
    }
    Gson gson = new Gson();
    JsonElement json = gson.fromJson(new String(data, Charsets.UTF_8), JsonElement.class);
    if (!json.isJsonObject()) {
        LOG.warn("Unable to decode live data node.");
        return null;
    }
    JsonObject jsonObj = json.getAsJsonObject();
    json = jsonObj.get("data");
    if (!json.isJsonObject()) {
        LOG.warn("Property data not found in live data node.");
        return null;
    }
    try {
        ApplicationMasterLiveNodeData amLiveNode = gson.fromJson(json, ApplicationMasterLiveNodeData.class);
        return YarnUtils.createApplicationId(amLiveNode.getAppIdClusterTime(), amLiveNode.getAppId());
    } catch (Exception e) {
        LOG.warn("Failed to decode application live node data.", e);
        return null;
    }
}
Also used : JsonElement(com.google.gson.JsonElement) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) ApplicationMasterLiveNodeData(com.continuuity.weave.internal.appmaster.ApplicationMasterLiveNodeData) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException)

Example 47 with JsonElement

use of com.google.gson.JsonElement in project buck by facebook.

the class ChromeTraceParser method parse.

/**
   * Parses a Chrome trace and stops parsing once all of the specified matchers have been
   * satisfied. This method parses only one Chrome trace event at a time, which avoids loading the
   * entire trace into memory.
   * @param pathToTrace is a relative path [to the ProjectFilesystem] to a Chrome trace in the
   *     "JSON Array Format."
   * @param chromeTraceEventMatchers set of matchers this invocation of {@code parse()} is trying to
   *     satisfy. Once a matcher finds a match, it will not consider any other events in the trace.
   * @return a {@code Map} where every matcher that found a match will have an entry whose key is
   *     the matcher and whose value is the one returned by
   *     {@link ChromeTraceEventMatcher#test(JsonObject, String)} without the {@link Optional}
   *     wrapper.
   */
public Map<ChromeTraceEventMatcher<?>, Object> parse(Path pathToTrace, Set<ChromeTraceEventMatcher<?>> chromeTraceEventMatchers) throws IOException {
    Set<ChromeTraceEventMatcher<?>> unmatchedMatchers = new HashSet<>(chromeTraceEventMatchers);
    Preconditions.checkArgument(!unmatchedMatchers.isEmpty(), "Must specify at least one matcher");
    Map<ChromeTraceEventMatcher<?>, Object> results = new HashMap<>();
    try (InputStream input = projectFilesystem.newFileInputStream(pathToTrace);
        JsonReader jsonReader = new JsonReader(new InputStreamReader(input))) {
        jsonReader.beginArray();
        Gson gson = new Gson();
        featureSearch: while (true) {
            // If END_ARRAY is the next token, then there are no more elements in the array.
            if (jsonReader.peek().equals(JsonToken.END_ARRAY)) {
                break;
            }
            // Verify and extract the name property before invoking any of the matchers.
            JsonElement eventEl = gson.fromJson(jsonReader, JsonElement.class);
            JsonObject event = eventEl.getAsJsonObject();
            JsonElement nameEl = event.get("name");
            if (nameEl == null || !nameEl.isJsonPrimitive()) {
                continue;
            }
            String name = nameEl.getAsString();
            // Prefer Iterator to Iterable+foreach so we can use remove().
            for (Iterator<ChromeTraceEventMatcher<?>> iter = unmatchedMatchers.iterator(); iter.hasNext(); ) {
                ChromeTraceEventMatcher<?> chromeTraceEventMatcher = iter.next();
                Optional<?> result = chromeTraceEventMatcher.test(event, name);
                if (result.isPresent()) {
                    iter.remove();
                    results.put(chromeTraceEventMatcher, result.get());
                    if (unmatchedMatchers.isEmpty()) {
                        break featureSearch;
                    }
                }
            }
        }
    }
    // We could throw if !unmatchedMatchers.isEmpty(), but that might be overbearing.
    return results;
}
Also used : InputStreamReader(java.io.InputStreamReader) Optional(java.util.Optional) HashMap(java.util.HashMap) InputStream(java.io.InputStream) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) JsonElement(com.google.gson.JsonElement) Iterator(java.util.Iterator) JsonReader(com.google.gson.stream.JsonReader) JsonObject(com.google.gson.JsonObject) HashSet(java.util.HashSet)

Example 48 with JsonElement

use of com.google.gson.JsonElement in project JsonPath by jayway.

the class GsonJsonProviderTest method longs_are_unwrapped.

@Test
public void longs_are_unwrapped() {
    JsonElement node = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.long-max-property");
    long val = using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.long-max-property", Long.class);
    assertThat(val).isEqualTo(Long.MAX_VALUE);
    assertThat(val).isEqualTo(node.getAsLong());
}
Also used : JsonElement(com.google.gson.JsonElement) Test(org.junit.Test)

Example 49 with JsonElement

use of com.google.gson.JsonElement in project useful-java-links by Vedenin.

the class TreeModel method readJson.

/**
     *  Example to readJson using TreeModel
     */
private static void readJson() throws IOException {
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse("{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}");
    JsonObject rootObject = jsonElement.getAsJsonObject();
    // get property "message"
    String message = rootObject.get("message").getAsString();
    // get place object
    JsonObject childObject = rootObject.getAsJsonObject("place");
    // get property "name"
    String place = childObject.get("name").getAsString();
    // print "Hi World!"*/
    System.out.println(message + " " + place);
}
Also used : JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject) JsonParser(com.google.gson.JsonParser)

Example 50 with JsonElement

use of com.google.gson.JsonElement in project malmo by Microsoft.

the class ObservationFromServer method writeObservationsToJSON.

@Override
public void writeObservationsToJSON(JsonObject json, MissionInit missionInit) {
    String jsonstring = "";
    synchronized (this.latestJsonStats) {
        jsonstring = this.latestJsonStats;
    }
    if (// "{}" is the empty JSON string.
    jsonstring.length() > 2) {
        // Parse the string into json:
        JsonParser parser = new JsonParser();
        JsonElement root = parser.parse(jsonstring);
        // Now copy the children of root into the provided json object:
        if (root.isJsonObject()) {
            JsonObject rootObj = root.getAsJsonObject();
            for (Map.Entry<String, JsonElement> entry : rootObj.entrySet()) {
                json.add(entry.getKey(), entry.getValue());
            }
        }
    }
}
Also used : JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject) HashMap(java.util.HashMap) Map(java.util.Map) JsonParser(com.google.gson.JsonParser)

Aggregations

JsonElement (com.google.gson.JsonElement)682 JsonObject (com.google.gson.JsonObject)381 JsonArray (com.google.gson.JsonArray)166 JsonPrimitive (com.google.gson.JsonPrimitive)107 JsonParser (com.google.gson.JsonParser)105 Gson (com.google.gson.Gson)69 Map (java.util.Map)63 ArrayList (java.util.ArrayList)51 HashMap (java.util.HashMap)50 IOException (java.io.IOException)48 Test (org.testng.annotations.Test)45 JsonReader (com.google.gson.stream.JsonReader)31 InputStreamReader (java.io.InputStreamReader)28 GsonBuilder (com.google.gson.GsonBuilder)26 Pager (com.willshex.blogwt.shared.api.Pager)26 Type (java.lang.reflect.Type)25 StringReader (java.io.StringReader)21 Test (org.junit.Test)21 User (com.willshex.blogwt.shared.api.datatype.User)19 JsonParseException (com.google.gson.JsonParseException)17