com.googlecode.protobuf.format.JsonFormat Java Examples

The following examples show how to use com.googlecode.protobuf.format.JsonFormat. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Pb2JsonUtils.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
public static void checkPbVersion() {
    if (isClassExist("com.google.protobuf.MapField")) {
        pbVersion = PbVersion.PROTO3;
        try {
            Class jsonFormatClazz = Class.forName("com.google.protobuf.util.JsonFormat");
            Method method = jsonFormatClazz.getMethod("printer");
            pb3Printer = method.invoke(jsonFormatClazz);
            pb3PrinterClazz = Class.forName("com.google.protobuf.util.JsonFormat$Printer");
            method = pb3PrinterClazz.getDeclaredMethod("includingDefaultValueFields");
            method.invoke(pb3Printer);
            pb3PrintMethod = pb3PrinterClazz.getDeclaredMethod("print", MessageOrBuilder.class);

            method = jsonFormatClazz.getMethod("parser");
            pb3Parser = method.invoke(jsonFormatClazz);
            pb3ParserClazz = Class.forName("com.google.protobuf.util.JsonFormat$Parser");
            method = pb3ParserClazz.getDeclaredMethod("ignoringUnknownFields");
            method.invoke(pb3Parser);
            pb3ParseMethod = pb3ParserClazz.getDeclaredMethod("merge", String.class, Message.Builder.class);
        } catch (Exception ex) {
            throw new RuntimeException("dependency of protobuf-java-util not exist");
        }
    } else {
        pbVersion = PbVersion.PROTO2;
        pb2Converter = new JsonFormat() {
            protected void print(Message message, JsonGenerator generator) throws IOException {
                for (Iterator<Map.Entry<Descriptors.FieldDescriptor, Object>> iter =
                     message.getAllFields().entrySet().iterator(); iter.hasNext(); ) {
                    Map.Entry<Descriptors.FieldDescriptor, Object> field = iter.next();
                    printField(field.getKey(), field.getValue(), generator);
                    if (iter.hasNext()) {
                        generator.print(",");
                    }
                }
                // ignore UnknownFields
            }
        };
    }
}
 
Example #2
Source File: Pb2JsonUtils.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
public static void json2Pb(CharSequence input, Message.Builder builder) throws JsonFormat.ParseException {
    if (pbVersion == PbVersion.PROTO2) {
        pb2Converter.merge(input, ExtensionRegistry.getEmptyRegistry(), builder);
    } else {
        try {
            pb3ParseMethod.invoke(pb3Parser, input, builder);
        } catch (Exception ex) {
            log.warn("pb3 json2pb failed, ex:", ex);
        }
    }
}
 
Example #3
Source File: ClientMain.java    From raft-java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    if (args.length < 2) {
        System.out.printf("Usage: ./run_client.sh CLUSTER KEY [VALUE]\n");
        System.exit(-1);
    }

    // parse args
    String ipPorts = args[0];
    String key = args[1];
    String value = null;
    if (args.length > 2) {
        value = args[2];
    }

    // init rpc client
    RpcClient rpcClient = new RpcClient(ipPorts);
    ExampleService exampleService = BrpcProxy.getProxy(rpcClient, ExampleService.class);
    final JsonFormat jsonFormat = new JsonFormat();

    // set
    if (value != null) {
        ExampleProto.SetRequest setRequest = ExampleProto.SetRequest.newBuilder()
                .setKey(key).setValue(value).build();
        ExampleProto.SetResponse setResponse = exampleService.set(setRequest);
        System.out.printf("set request, key=%s value=%s response=%s\n",
                key, value, jsonFormat.printToString(setResponse));
    } else {
        // get
        ExampleProto.GetRequest getRequest = ExampleProto.GetRequest.newBuilder()
                .setKey(key).build();
        ExampleProto.GetResponse getResponse = exampleService.get(getRequest);
        System.out.printf("get request, key=%s, response=%s\n",
                key, jsonFormat.printToString(getResponse));
    }

    rpcClient.stop();
}
 
Example #4
Source File: ProtobufHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected Message readInternal(Class<? extends Message> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	MediaType contentType = inputMessage.getHeaders().getContentType();
	contentType = (contentType != null ? contentType : PROTOBUF);

	Charset charset = getCharset(inputMessage.getHeaders());
	InputStreamReader reader = new InputStreamReader(inputMessage.getBody(), charset);

	try {
		Message.Builder builder = getMessageBuilder(clazz);

		if (MediaType.APPLICATION_JSON.isCompatibleWith(contentType)) {
			JsonFormat.merge(reader, this.extensionRegistry, builder);
		}
		else if (MediaType.TEXT_PLAIN.isCompatibleWith(contentType)) {
			TextFormat.merge(reader, this.extensionRegistry, builder);
		}
		else if (MediaType.APPLICATION_XML.isCompatibleWith(contentType)) {
			XmlFormat.merge(reader, this.extensionRegistry, builder);
		}
		else {
			builder.mergeFrom(inputMessage.getBody(), this.extensionRegistry);
		}
		return builder.build();
	}
	catch (Exception e) {
		throw new HttpMessageNotReadableException("Could not read Protobuf message: " + e.getMessage(), e);
	}
}
 
Example #5
Source File: Java7BaseTest.java    From compiler with Apache License 2.0 5 votes vote down vote up
protected static String parseJava(final String content) {
	final StringBuilder sb = new StringBuilder();
	final FileASTRequestor r = new FileASTRequestor() {
		@Override
		public void acceptAST(String sourceFilePath, CompilationUnit cu) {
			final ASTRoot.Builder ast = ASTRoot.newBuilder();
			try {
				ast.addNamespaces(visitor.getNamespaces(cu));
			} catch (final Exception e) {
				System.err.println(e);
				e.printStackTrace();
			}

			sb.append(JsonFormat.printToString(ast.build()));
		}
	};
	Map<String, String> fileContents = new HashMap<String, String>();
	fileContents.put("", content);
	@SuppressWarnings("rawtypes")
	Map options = JavaCore.getOptions();
	options.put(JavaCore.COMPILER_COMPLIANCE, javaVersion);
	options.put(JavaCore.COMPILER_SOURCE, javaVersion);
	ASTParser parser = ASTParser.newParser(astLevel);
	parser.setCompilerOptions(options);
	parser.setEnvironment(new String[0], new String[]{}, new String[]{}, true);
	parser.setResolveBindings(true);
	parser.createASTs(fileContents, new String[]{""}, null, new String[0], r, null);

	return FileIO.normalizeEOL(sb.toString());
}
 
Example #6
Source File: GenomicsDBUtils.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Parse the vid json and create an in-memory Protobuf structure representing the
 * information in the JSON file
 *
 * @param vidmapJson vid JSON file
 * @return Protobuf object
 */
public static GenomicsDBVidMapProto.VidMappingPB getProtobufVidMappingFromJsonFile(final String vidmapJson)
        throws IOException {
    final GenomicsDBVidMapProto.VidMappingPB.Builder vidMapBuilder = GenomicsDBVidMapProto.VidMappingPB.newBuilder();
    try (final Reader reader = Files.newBufferedReader(IOUtils.getPath(vidmapJson))) {
        JsonFormat.merge(reader, vidMapBuilder);
    }
    return vidMapBuilder.build();
}
 
Example #7
Source File: ApplicationIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
private String convertProtobufMessageStreamToJsonString(InputStream protobufStream) throws IOException {
    JsonFormat jsonFormat = new JsonFormat();
    Course course = Course.parseFrom(protobufStream);
    return jsonFormat.printToString(course);
}