Search in sources :

Example 16 with JsonReader

use of com.google.gson.stream.JsonReader in project elastic-job by dangdangdotcom.

the class GsonFactoryTest method assertRegisterTypeAdapter.

@Test
public void assertRegisterTypeAdapter() {
    Gson beforeRegisterGson = GsonFactory.getGson();
    GsonFactory.registerTypeAdapter(GsonFactoryTest.class, new TypeAdapter() {

        @Override
        public Object read(final JsonReader in) throws IOException {
            return null;
        }

        @Override
        public void write(final JsonWriter out, final Object value) throws IOException {
            out.jsonValue("test");
        }
    });
    assertThat(beforeRegisterGson.toJson(new GsonFactoryTest()), is("{}"));
    assertThat(GsonFactory.getGson().toJson(new GsonFactoryTest()), is("test"));
}
Also used : TypeAdapter(com.google.gson.TypeAdapter) Gson(com.google.gson.Gson) JsonReader(com.google.gson.stream.JsonReader) IOException(java.io.IOException) JsonWriter(com.google.gson.stream.JsonWriter) Test(org.junit.Test)

Example 17 with JsonReader

use of com.google.gson.stream.JsonReader in project buck by facebook.

the class WorkerProcess method ensureLaunchAndHandshake.

public synchronized void ensureLaunchAndHandshake() throws IOException {
    if (handshakePerformed) {
        return;
    }
    LOG.debug("Starting up process %d using command: \'%s\'", this.hashCode(), Joiner.on(' ').join(processParams.getCommand()));
    launchedProcess = executor.launchProcess(processParams);
    JsonWriter processStdinWriter = new JsonWriter(new BufferedWriter(new OutputStreamWriter(launchedProcess.getOutputStream())));
    JsonReader processStdoutReader = new JsonReader(new BufferedReader(new InputStreamReader(launchedProcess.getInputStream())));
    protocol = new WorkerProcessProtocolZero(executor, launchedProcess, processStdinWriter, processStdoutReader, stdErr);
    int messageID = currentMessageID.getAndAdd(1);
    LOG.debug("Sending handshake to process %d", this.hashCode());
    protocol.sendHandshake(messageID);
    LOG.debug("Receiving handshake from process %d", this.hashCode());
    protocol.receiveHandshake(messageID);
    handshakePerformed = true;
}
Also used : InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) JsonReader(com.google.gson.stream.JsonReader) OutputStreamWriter(java.io.OutputStreamWriter) JsonWriter(com.google.gson.stream.JsonWriter) BufferedWriter(java.io.BufferedWriter)

Example 18 with JsonReader

use of com.google.gson.stream.JsonReader 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 19 with JsonReader

use of com.google.gson.stream.JsonReader in project buck by facebook.

the class WorkerProcessProtocolZeroTest method testProcessIsStillDestroyedEvenIfErrorOccursWhileClosingStreams.

@Test
public void testProcessIsStillDestroyedEvenIfErrorOccursWhileClosingStreams() throws IOException {
    JsonWriter writer = new JsonWriter(new StringWriter());
    // write an opening bracket now, so the writer doesn't throw due to invalid JSON when it goes
    // to write the closing bracket
    writer.beginArray();
    JsonReader reader = new JsonReader(new StringReader("invalid JSON"));
    WorkerProcessProtocol protocol = new WorkerProcessProtocolZero(fakeProcessExecutor, fakeLaunchedProcess, writer, reader, newTempFile());
    try {
        protocol.close();
    } catch (IOException e) {
        assertThat(e.getMessage(), Matchers.containsString("malformed JSON"));
        // assert that process was still destroyed despite the exception
        assertTrue(fakeProcess.isDestroyed());
    }
}
Also used : StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) JsonReader(com.google.gson.stream.JsonReader) IOException(java.io.IOException) JsonWriter(com.google.gson.stream.JsonWriter) Test(org.junit.Test)

Example 20 with JsonReader

use of com.google.gson.stream.JsonReader in project buck by facebook.

the class WorkerProcessProtocolZeroTest method testReceiveHandshakeWithMalformedJSON.

@Test
public void testReceiveHandshakeWithMalformedJSON() throws IOException {
    String malformedJson = "=^..^= meow";
    WorkerProcessProtocol protocol = new WorkerProcessProtocolZero(fakeProcessExecutor, fakeLaunchedProcess, dummyJsonWriter, new JsonReader(new StringReader(malformedJson)), newTempFile());
    try {
        protocol.receiveHandshake(123);
    } catch (HumanReadableException e) {
        assertThat(e.getMessage(), Matchers.containsString("Error receiving handshake response"));
    }
}
Also used : HumanReadableException(com.facebook.buck.util.HumanReadableException) StringReader(java.io.StringReader) JsonReader(com.google.gson.stream.JsonReader) Test(org.junit.Test)

Aggregations

JsonReader (com.google.gson.stream.JsonReader)95 StringReader (java.io.StringReader)36 JsonElement (com.google.gson.JsonElement)30 Test (org.junit.Test)19 JsonObject (com.google.gson.JsonObject)17 IOException (java.io.IOException)17 InputStreamReader (java.io.InputStreamReader)17 JsonParser (com.google.gson.JsonParser)11 HumanReadableException (com.facebook.buck.util.HumanReadableException)10 Gson (com.google.gson.Gson)9 TypeToken (com.google.gson.reflect.TypeToken)8 JsonWriter (com.google.gson.stream.JsonWriter)8 Map (java.util.Map)7 JsonToken (com.google.gson.stream.JsonToken)6 HashMap (java.util.HashMap)6 InputStream (java.io.InputStream)5 StringWriter (java.io.StringWriter)5 Type (java.lang.reflect.Type)5 ArrayList (java.util.ArrayList)5 BufferedReader (java.io.BufferedReader)4