Skip to content

Instantly share code, notes, and snippets.

@pierre
Created September 23, 2011 17:40
Show Gist options
  • Save pierre/1237974 to your computer and use it in GitHub Desktop.
Save pierre/1237974 to your computer and use it in GitHub Desktop.
streaming
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/json")
@Timed
public StreamingOutput listingToJson(
@QueryParam("path") final String path,
@QueryParam("recursive") final boolean recursive,
@QueryParam("pretty") final boolean pretty,
@QueryParam("raw") final boolean raw
) throws IOException
{
final HdfsListing hdfsListing = hdfsReader.getListing(path, raw, recursive);
return new StreamingOutput()
{
@Override
public void write(OutputStream output) throws IOException, WebApplicationException
{
final String parentPath = getParentPath() == null ? "" : getParentPath();
final JsonGenerator generator = new JsonFactory().createJsonGenerator(out);
generator.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
if (pretty) {
generator.setPrettyPrinter(new DefaultPrettyPrinter());
}
generator.writeStartObject();
generator.writeObjectField(JSON_LISTING_PATH, getPath());
generator.writeObjectField(JSON_LISTING_PARENT_PATH, parentPath);
generator.writeArrayFieldStart(JSON_LISTING_ENTRIES);
// Important: need to flush before appending pre-serialized events
generator.flush();
int i = 0;
generator.writeStartObject();
for (T item : data) {
generator.writeFieldName(schema.getFieldNameByPosition(i));
jsonObjectMapper.writeValue(generator, getJsonValue(item));
i++;
}
generator.writeEndObject();
generator.flush();
generator.writeEndArray();
generator.writeEndObject();
generator.close();
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment