Example usage for com.google.gson.stream JsonReader JsonReader

List of usage examples for com.google.gson.stream JsonReader JsonReader

Introduction

In this page you can find the example usage for com.google.gson.stream JsonReader JsonReader.

Prototype

public JsonReader(Reader in) 

Source Link

Document

Creates a new instance that reads a JSON-encoded stream from in .

Usage

From source file:com.example.endpoints.Echo.java

License:Apache License

public static void echo(MessageTranslator translator, HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    resp.addHeader("Content-Encoding", "application/json");

    try {/*from  www.  j  a v  a 2 s. co m*/
        JsonReader jsonReader = new JsonReader(req.getReader());
        Message message = translator.fromExternalToInternal(new Gson().fromJson(jsonReader, Map.class));
        performTask(message);
        new Gson().toJson(translator.fromInternalToExternal(message), resp.getWriter());
    } catch (JsonParseException je) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        JsonObject error = new JsonObject();
        error.addProperty("code", HttpServletResponse.SC_BAD_REQUEST);
        error.addProperty("message", "Body was not valid JSON.");
        new Gson().toJson(error, resp.getWriter());
    }
}

From source file:com.example.endpoints.EchoServlet.java

License:Open Source License

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.addHeader("Content-Encoding", "application/json");

    Object responseBody;/*from   w  w w  .  j  a  va 2s.com*/
    try {
        JsonReader jsonReader = new JsonReader(req.getReader());
        responseBody = new Gson().fromJson(jsonReader, Map.class);
    } catch (JsonParseException je) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        JsonObject error = new JsonObject();
        error.addProperty("code", HttpServletResponse.SC_BAD_REQUEST);
        error.addProperty("message", "Body was not valid JSON.");
        responseBody = error;
    }

    new Gson().toJson(responseBody, resp.getWriter());
}

From source file:com.facebook.buck.httpserver.TracesHelper.java

License:Apache License

private Optional<String> parseCommandFrom(Path pathToTrace) {
    try (InputStream input = projectFilesystem.newFileInputStream(pathToTrace);
            JsonReader jsonReader = new JsonReader(new InputStreamReader(input))) {
        jsonReader.beginArray();/*from  www  .j  a v a2s .  c om*/
        Gson gson = new Gson();

        // Look through the first few elements to see if one matches the schema for an event that
        // contains the command that the user ran.
        for (int i = 0; i < 4; i++) {
            // If END_ARRAY is the next token, then there are no more elements in the array.
            if (jsonReader.peek().equals(JsonToken.END_ARRAY)) {
                break;
            }

            JsonObject json = gson.fromJson(jsonReader, JsonObject.class);
            Optional<String> command = tryToFindCommand(json);
            if (command.isPresent()) {
                return command;
            }
        }

        // Oh well, we tried.
        return Optional.absent();
    } catch (IOException e) {
        logger.error(e);
        return Optional.absent();
    }
}

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

License:Apache License

/**
 * @param jsonReader That contains the JSON data.
 *///from ww  w . ja  va2  s.c o m
public BuildFileToJsonParser(Reader jsonReader) {
    this.gson = new Gson();
    this.reader = new JsonReader(jsonReader);

    // This is used to read one line at a time.
    reader.setLenient(true);
}

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

License:Apache License

/**
 * Consumes the next JSON map from the reader, parses it as a Java {@link Map} to return, and then
 * closes the reader.//ww  w.j  a  v a  2s .c om
 * <p>
 * <strong>Warning:</strong> This method closes the reader.
 */
@SuppressWarnings("unchecked")
public static Map<String, Object> parseFromReader(Reader reader) throws IOException {
    JsonReader jsonReader = new JsonReader(reader);
    try {
        JsonObject json = new Gson().fromJson(reader, JsonObject.class);
        Map<String, Object> map = (Map<String, Object>) toRawTypes(json);
        return Preconditions.checkNotNull(map);
    } finally {
        jsonReader.close();
    }
}

From source file:com.facebook.buck.shell.WorkerProcess.java

License:Apache License

public synchronized void ensureLaunchAndHandshake() throws IOException {
    if (handshakePerformed) {
        return;//w w w  .  ja  v a  2s.  c om
    }
    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;
}

From source file:com.facebook.buck.util.trace.ChromeTraceParser.java

License:Apache License

/**
 * 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.//w w w . j  a  va  2s  .  co  m
 * @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.
            JsonObject event = gson.fromJson(jsonReader, JsonObject.class);
            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;
}

From source file:com.fb.resttest.AuthorListReader.java

@Override
public List<Author> readFrom(Class<List<Author>> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {
    final Author[] authors = new Gson().fromJson(new JsonReader(new InputStreamReader(entityStream)),
            Author[].class);
    return Arrays.asList(authors);
}

From source file:com.fb.resttest.BookListReader.java

@Override
public List<Book> readFrom(Class<List<Book>> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {
    final Book[] books = new Gson().fromJson(new JsonReader(new InputStreamReader(entityStream)), Book[].class);
    return Arrays.asList(books);
}

From source file:com.fb.resttest.BookReader.java

@Override
public Book readFrom(Class<Book> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {
    return new Gson().fromJson(new JsonReader(new InputStreamReader(entityStream)), Book.class);
}