in proto-tools/src/main/java/org/apache/avro/tool/ProtoToJsonTool.java [33:80]
public int run(InputStream in, PrintStream out, PrintStream err,
List<String> args) throws Exception {
OptionParser optionParser = new OptionParser();
OptionSpec<Void> prettyOption = optionParser
.accepts("pretty", "Turns on pretty printing.");
OptionSet optionSet = optionParser.parse(args.toArray(new String[0]));
Boolean pretty = optionSet.has(prettyOption);
List<String> nargs = (List<String>)optionSet.nonOptionArguments();
if (nargs.size() != 1) {
printHelp(err);
err.println();
optionParser.printHelpOn(err);
return 1;
}
Path p = new Path(nargs.get(0));
Configuration conf = new Configuration();
InputStream input = nargs.get(0).equals("-") ? in : p.getFileSystem(conf).open(p);
BufferedInputStream inStream = new BufferedInputStream(input);
GenericDatumReader<Object> reader = new GenericDatumReader<>();
DataFileStream<Object> streamReader = new DataFileStream<>(inStream, reader);
ObjectMapper mapper = new ObjectMapper();
try {
String schema = streamReader.getMetaString("protobuf.generic.schema");
checkNotNull(schema, "Missing metadata key protobuf.generic.schema");
ProtobufReader protoReader = new ProtobufReader(schema);
for (Object datum : streamReader) {
ByteBuffer byteBuffer = (ByteBuffer) ((GenericRecord) datum).get("bytes");
String json = protoReader.toJson(byteBuffer);
if (pretty) {
String prettyJson = mapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(mapper.readValue(json, Object.class));
out.println(prettyJson);
} else {
out.println(json);
}
}
out.println();
out.flush();
} finally {
streamReader.close();
}
return 0;
}