Java Code Examples for com.google.protobuf.util.JsonFormat#Printer

The following examples show how to use com.google.protobuf.util.JsonFormat#Printer . 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: ClientRpcStore.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: IndexResource.java    From lumongo with Apache License 2.0 5 votes vote down vote up
@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();
	}

}
 
Example 3
Source File: DataflowJobManager.java    From feast with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 4
Source File: ClientRpcStore.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 5
Source File: FeatureSetJsonByteConverter.java    From feast with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 6
Source File: RpcUtil.java    From snowblossom with Apache License 2.0 5 votes vote down vote up
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);

}
 
Example 7
Source File: ProtoUtil.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 8
Source File: JsonLedger.java    From julongchain with Apache License 2.0 4 votes vote down vote up
public JsonFormat.Printer getPrinter() {
    return printer;
}
 
Example 9
Source File: ConfigGeneratorDriver.java    From api-compiler with Apache License 2.0 4 votes vote down vote up
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);
    }
  }
}
 
Example 10
Source File: VanityGen.java    From snowblossom with Apache License 2.0 4 votes vote down vote up
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()));


  
}
 
Example 11
Source File: JsonLedger.java    From julongchain with Apache License 2.0 4 votes vote down vote up
public void setPrinter(JsonFormat.Printer printer) {
    this.printer = printer;
}
 
Example 12
Source File: Writer.java    From karate-grpc with MIT License 4 votes vote down vote up
Writer(JsonFormat.Printer jsonPrinter, List<Object> output) {
    this.jsonPrinter = jsonPrinter.preservingProtoFieldNames().includingDefaultValueFields();
    this.output = output;
}
 
Example 13
Source File: ProtobufHttpMessageConverter.java    From java-technology-stack with MIT License 4 votes vote down vote up
public ProtobufJavaUtilSupport(@Nullable JsonFormat.Parser parser, @Nullable JsonFormat.Printer printer) {
	this.parser = (parser != null ? parser : JsonFormat.parser());
	this.printer = (printer != null ? printer : JsonFormat.printer());
}
 
Example 14
Source File: ProtobufHttpMessageConverter.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public ProtobufJavaUtilSupport(@Nullable JsonFormat.Parser parser, @Nullable JsonFormat.Printer printer) {
	this.parser = (parser != null ? parser : JsonFormat.parser());
	this.printer = (printer != null ? printer : JsonFormat.printer());
}
 
Example 15
Source File: ProtobufJsonFormatHttpMessageConverter.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * 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);
	}
}
 
Example 16
Source File: ProtobufJsonFormatHttpMessageConverter.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * 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);
}
 
Example 17
Source File: ProtobufJsonFormatHttpMessageConverter.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * 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);
}
 
Example 18
Source File: ProtobufJsonFormatHttpMessageConverter.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * 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);
}
 
Example 19
Source File: ProtobufJsonFormatHttpMessageConverter.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * 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);
}
 
Example 20
Source File: JSONMapper.java    From nifi-protobuf-processor with MIT License 2 votes vote down vote up
/**
 * 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);
}