下面列出了com.google.protobuf.util.JsonFormat#Printer ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private JsonNode getDefaultRequestJSON(Message msg) throws JsonParseException, IOException
{
Message.Builder o2 = DefaultCustomPredictRequest.newBuilder();
TypeRegistry registry = TypeRegistry.newBuilder().add(o2.getDescriptorForType()).build();
JsonFormat.Printer jPrinter = JsonFormat.printer();
String result = jPrinter.usingTypeRegistry(registry).print(msg);
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser parser = factory.createParser(result);
JsonNode jNode = mapper.readTree(parser);
if (jNode.has(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD))
{
JsonNode values = jNode.get(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD).get("values");
((ObjectNode) jNode).set(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD, values);
}
return jNode;
}
public static String toJson(Message msg) throws InvalidProtocolBufferException {
JsonFormat.Printer printer = JsonFormat.printer()
.omittingInsignificantWhitespace()
.usingTypeRegistry(JsonFormat.TypeRegistry.newBuilder()
.add(msg.getDescriptorForType())
.build());
return printer.print(msg);
}
private JsonNode getJSON(Message msg,String fieldname) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, JsonParseException, IOException
{
JsonFormat.Printer jPrinter = JsonFormat.printer();
String result = jPrinter.print(msg);
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser parser = factory.createParser(result);
JsonNode jNode = mapper.readTree(parser);
return jNode;
}
public static JSONObject protoToJson(com.google.protobuf.Message m)
throws Exception
{
JsonFormat.Printer printer = JsonFormat.printer();
String str = printer.print(m);
JSONParser parser = new JSONParser(JSONParser.MODE_STRICTEST);
return (JSONObject) parser.parse(str);
}
/**
* Convert list of feature sets to json strings joined by new line, represented as byte arrays
*
* @param featureSets List of feature set protobufs
* @return Byte array representation of the json strings
* @throws InvalidProtocolBufferException
*/
@Override
public byte[] toByte(List<FeatureSetProto.FeatureSet> featureSets)
throws InvalidProtocolBufferException {
JsonFormat.Printer printer =
JsonFormat.printer().omittingInsignificantWhitespace().printingEnumsAsInts();
List<String> featureSetsJson = new ArrayList<>();
for (FeatureSetProto.FeatureSet featureSet : featureSets) {
featureSetsJson.add(printer.print(featureSet.getSpec()));
}
return String.join("\n", featureSetsJson).getBytes();
}
private ImportOptions getPipelineOptions(
String jobName, SourceProto.Source source, Set<StoreProto.Store> sinks, boolean update)
throws IOException, IllegalAccessException {
ImportOptions pipelineOptions =
PipelineOptionsFactory.fromArgs(defaultOptions.toArgs()).as(ImportOptions.class);
JsonFormat.Printer jsonPrinter = JsonFormat.printer();
pipelineOptions.setSpecsStreamingUpdateConfigJson(
jsonPrinter.print(specsStreamingUpdateConfig));
pipelineOptions.setSourceJson(jsonPrinter.print(source));
pipelineOptions.setStoresJson(
sinks.stream().map(wrapException(jsonPrinter::print)).collect(Collectors.toList()));
pipelineOptions.setProject(projectId);
pipelineOptions.setDefaultFeastProject(Project.DEFAULT_NAME);
pipelineOptions.setUpdate(update);
pipelineOptions.setRunner(DataflowRunner.class);
pipelineOptions.setJobName(jobName);
pipelineOptions.setFilesToStage(
detectClassPathResourcesToStage(DataflowRunner.class.getClassLoader()));
if (metrics.isEnabled()) {
pipelineOptions.setMetricsExporterType(metrics.getType());
if (metrics.getType().equals("statsd")) {
pipelineOptions.setStatsdHost(metrics.getHost());
pipelineOptions.setStatsdPort(metrics.getPort());
}
}
return pipelineOptions;
}
@GET
@Produces({ MediaType.APPLICATION_JSON + ";charset=utf-8" })
public Response get(@Context Response response, @QueryParam(LumongoConstants.INDEX) String index, @QueryParam(LumongoConstants.PRETTY) boolean pretty) {
try {
StringBuilder responseBuilder = new StringBuilder();
IndexConfig indexConfig = indexManager.getIndexConfig(index);
responseBuilder.append("{");
responseBuilder.append("\"indexName\": ");
responseBuilder.append("\"");
responseBuilder.append(indexConfig.getIndexName());
responseBuilder.append("\"");
responseBuilder.append(",");
responseBuilder.append("\"numberOfSegments\": ");
responseBuilder.append(indexConfig.getNumberOfSegments());
responseBuilder.append(",");
responseBuilder.append("\"indexSettings\": ");
JsonFormat.Printer printer = JsonFormat.printer();
responseBuilder.append(printer.print(indexConfig.getIndexSettings()));
responseBuilder.append("}");
String docString = responseBuilder.toString();
if (pretty) {
docString = JsonWriter.formatJson(docString);
}
return Response.status(LumongoConstants.SUCCESS).entity(docString).build();
}
catch (Exception e) {
return Response.status(LumongoConstants.INTERNAL_ERROR).entity("Failed to get index names: " + e.getMessage()).build();
}
}
public ProtobufJavaUtilSupport(@Nullable JsonFormat.Parser parser, @Nullable JsonFormat.Printer printer) {
this.parser = (parser != null ? parser : JsonFormat.parser());
this.printer = (printer != null ? printer : JsonFormat.printer());
}
public ProtobufJavaUtilSupport(@Nullable JsonFormat.Parser parser, @Nullable JsonFormat.Printer printer) {
this.parser = (parser != null ? parser : JsonFormat.parser());
this.printer = (printer != null ? printer : JsonFormat.printer());
}
Writer(JsonFormat.Printer jsonPrinter, List<Object> output) {
this.jsonPrinter = jsonPrinter.preservingProtoFieldNames().includingDefaultValueFields();
this.output = output;
}
public JsonFormat.Printer getPrinter() {
return printer;
}
public void setPrinter(JsonFormat.Printer printer) {
this.printer = printer;
}
public VanityGen(String find, boolean starts, boolean ends)
throws Exception
{
this.find = find;
this.starts = starts;
this.ends = ends;
counter = new MultiAtomicLong();
params = new NetworkParamsProd();
for(int i=0; i<32; i++)
{
new WorkerThread().start();
}
long last = 0;
while(!done)
{
Thread.sleep(5000);
long n = counter.sum();
double diff = n - last;
double rate = diff / 5.0;
DecimalFormat df = new DecimalFormat("0.0");
System.out.println(String.format("Checked %d at rate %s", n, df.format(rate)));
last = n;
}
WalletKeyPair wkp = found_wkp;
WalletDatabase.Builder wallet_builder = WalletDatabase.newBuilder();
wallet_builder.addKeys(wkp);
AddressSpec claim = AddressUtil.getSimpleSpecForKey(wkp);
wallet_builder.addAddresses(claim);
String address = AddressUtil.getAddressString(claim, params);
wallet_builder.putUsedAddresses(address, true);
JsonFormat.Printer printer = JsonFormat.printer();
System.out.println(printer.print(wallet_builder.build()));
}
private void generateOutputFiles(Service serviceConfig)
throws FileNotFoundException, IOException {
// Create normalized service proto, in binary form.
if (!Strings.isNullOrEmpty(options.get(BIN_OUT))) {
File outFileBinaryServiceConfig = new File(options.get(BIN_OUT));
OutputStream normalizedOut = new FileOutputStream(outFileBinaryServiceConfig);
serviceConfig.writeTo(normalizedOut);
normalizedOut.close();
}
// Create normalized service proto, in text form.
if (!Strings.isNullOrEmpty(options.get(TXT_OUT))) {
File outFileTxtServiceConfig = new File(options.get(TXT_OUT));
try (PrintWriter textPrintWriter =
new PrintWriter(outFileTxtServiceConfig, StandardCharsets.UTF_8.name())) {
TextFormat.print(serviceConfig, textPrintWriter);
}
}
// Create normalized service proto, in json form.
if (!Strings.isNullOrEmpty(options.get(JSON_OUT))) {
File outFileJsonServiceConfig = new File(options.get(JSON_OUT));
TypeRegistry registry =
addPlatformExtensions(TypeRegistry.newBuilder())
.add(Service.getDescriptor())
.add(com.google.protobuf.BoolValue.getDescriptor())
.add(com.google.protobuf.BytesValue.getDescriptor())
.add(com.google.protobuf.DoubleValue.getDescriptor())
.add(com.google.protobuf.FloatValue.getDescriptor())
.add(com.google.protobuf.Int32Value.getDescriptor())
.add(com.google.protobuf.Int64Value.getDescriptor())
.add(com.google.protobuf.StringValue.getDescriptor())
.add(com.google.protobuf.UInt32Value.getDescriptor())
.add(com.google.protobuf.UInt64Value.getDescriptor())
.build();
JsonFormat.Printer jsonPrinter = JsonFormat.printer().usingTypeRegistry(registry);
try (PrintWriter jsonPrintWriter =
new PrintWriter(outFileJsonServiceConfig, StandardCharsets.UTF_8.name())) {
jsonPrinter.appendTo(serviceConfig, jsonPrintWriter);
}
}
}
/**
* Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with the given
* {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration, also
* accepting an initializer that allows the registration of message extensions.
* @param parser the JSON parser configuration
* @param printer the JSON printer configuration
* @param registryInitializer an initializer for message extensions
* @deprecated as of 5.1, in favor of
* {@link #ProtobufJsonFormatHttpMessageConverter(JsonFormat.Parser, JsonFormat.Printer, ExtensionRegistry)}
*/
@Deprecated
public ProtobufJsonFormatHttpMessageConverter(@Nullable JsonFormat.Parser parser,
@Nullable JsonFormat.Printer printer, @Nullable ExtensionRegistryInitializer registryInitializer) {
super(new ProtobufJavaUtilSupport(parser, printer), null);
if (registryInitializer != null) {
registryInitializer.initializeExtensionRegistry(this.extensionRegistry);
}
}
/**
* Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with the given
* {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration.
* @param parser the JSON parser configuration
* @param printer the JSON printer configuration
*/
public ProtobufJsonFormatHttpMessageConverter(
@Nullable JsonFormat.Parser parser, @Nullable JsonFormat.Printer printer) {
this(parser, printer, (ExtensionRegistry)null);
}
/**
* Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with the given
* {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration, also
* accepting a registry that specifies protocol message extensions.
* @param parser the JSON parser configuration
* @param printer the JSON printer configuration
* @param extensionRegistry the registry to populate
* @since 5.1
*/
public ProtobufJsonFormatHttpMessageConverter(@Nullable JsonFormat.Parser parser,
@Nullable JsonFormat.Printer printer, @Nullable ExtensionRegistry extensionRegistry) {
super(new ProtobufJavaUtilSupport(parser, printer), extensionRegistry);
}
/**
* Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with the given
* {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration.
* @param parser the JSON parser configuration
* @param printer the JSON printer configuration
*/
public ProtobufJsonFormatHttpMessageConverter(
@Nullable JsonFormat.Parser parser, @Nullable JsonFormat.Printer printer) {
this(parser, printer, (ExtensionRegistry)null);
}
/**
* Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with the given
* {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration, also
* accepting a registry that specifies protocol message extensions.
* @param parser the JSON parser configuration
* @param printer the JSON printer configuration
* @param extensionRegistry the registry to populate
* @since 5.1
*/
public ProtobufJsonFormatHttpMessageConverter(@Nullable JsonFormat.Parser parser,
@Nullable JsonFormat.Printer printer, @Nullable ExtensionRegistry extensionRegistry) {
super(new ProtobufJavaUtilSupport(parser, printer), extensionRegistry);
}
/**
* Format a Protocol Buffers Message to a JSON string
* @param data The Message to be formatted
* @return A JSON String representing the data
* @throws InvalidProtocolBufferException Thrown in case of invalid Message data
*/
public static String toJSON(Message data) throws InvalidProtocolBufferException {
JsonFormat.Printer printer = JsonFormat.printer();
return printer.print(data);
}