com.google.protobuf.util.JsonFormat Java Examples
The following examples show how to use
com.google.protobuf.util.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: Sandbox.java From phenopacket-schema with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test void testEvidence() throws Exception { OntologyClass publishedClinicalStudy = OntologyClass. newBuilder(). setId("ECO:0006017"). setLabel("author statement from published clinical study used in manual assertion"). build(); ExternalReference reference = ExternalReference.newBuilder(). setId("PMID:20375004"). setDescription("Mutations in fibrillin-1 cause congenital scleroderma: stiff skin syndrome"). build(); Evidence evidence = Evidence.newBuilder(). setEvidenceCode(publishedClinicalStudy). setReference(reference). build(); System.out.println(JsonFormat.printer().includingDefaultValueFields().print(evidence)); }
Example #2
Source File: PowerRestController.java From sctalk with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/power/list",method = RequestMethod.GET) public void listPower(HttpServletRequest request, HttpServletResponse response) throws InvalidProtocolBufferException, InvalidProtocolBufferException { // Create a blocking stub with the channel PowerServiceGrpc.PowerServiceBlockingStub stub = PowerServiceGrpc.newBlockingStub(channel); // Create a request PowerRequest listPowerRequest = PowerRequest.newBuilder().build(); // Send the request using the stub System.out.println("Client sending request"); PowerResponse powerResponse = stub.listPower(listPowerRequest); if(powerResponse.getStatusId()==0){ String data= JsonFormat.printer().includingDefaultValueFields().preservingProtoFieldNames().print(powerResponse); HttpUtils.setJsonBody(response,new ResponseInfo(0,"显示所有用户",data)); }else { System.out.println("nothing"); HttpUtils.setJsonBody(response,new ResponseInfo(1,"无内容")); } }
Example #3
Source File: ManagerRestController.java From sctalk with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/manager/list", method = RequestMethod.GET) public void listManager(HttpServletRequest request, HttpServletResponse response) throws InvalidProtocolBufferException { // Create a blocking stub with the channel ManagerServiceGrpc.ManagerServiceBlockingStub stub = ManagerServiceGrpc.newBlockingStub(channel); // Create a request ManagerRequest listManagerRequest = ManagerRequest.newBuilder().build(); // Send the request using the stub System.out.println("Client sending request"); ManagerResponse managerResponse = stub.listManager(listManagerRequest); if (managerResponse.getStatusId() == 0) { String data = JsonFormat.printer().preservingProtoFieldNames().print(managerResponse); HttpUtils.setJsonBody(response, new ResponseInfo(0, "显示所有", data)); } else { System.out.println("nothing"); HttpUtils.setJsonBody(response, new ResponseInfo(1, "无内容")); } }
Example #4
Source File: JobSubmitCommand.java From titus-control-plane with Apache License 2.0 | 6 votes |
private JobDescriptor loadTemplate(CommandContext context) throws IOException { File templateFile = new File(context.getCLI().getOptionValue('f')); System.out.println("Submitting job from file " + templateFile); JobDescriptor.Builder builder = JobDescriptor.newBuilder(); try (FileReader fr = new FileReader(templateFile)) { JsonFormat.parser().merge(fr, builder); } JobDescriptor applicajobDescriptorionInfo = builder.build(); if (context.getCLI().hasOption('d')) { System.out.println(JsonFormat.printer().print(applicajobDescriptorionInfo)); } return applicajobDescriptorionInfo; }
Example #5
Source File: NotificationReceiver.java From java-docs-samples with Apache License 2.0 | 6 votes |
@Override public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) { NotificationMessage.Builder notificationMessageBuilder = NotificationMessage.newBuilder(); try { String jsonString = message.getData().toStringUtf8(); JsonFormat.parser().merge(jsonString, notificationMessageBuilder); NotificationMessage notificationMessage = notificationMessageBuilder.build(); System.out.println( String.format("Config id: %s", notificationMessage.getNotificationConfigName())); System.out.println(String.format("Finding: %s", notificationMessage.getFinding())); } catch (InvalidProtocolBufferException e) { System.out.println("Could not parse message: " + e); } finally { consumer.ack(); } }
Example #6
Source File: ProtobufUtil.java From ja-micro with Apache License 2.0 | 6 votes |
/** * Converts a protobuf message to a JSON object * <p> * Note: Camel-cases the field names as defined in the proto definition * * @param input the protobuf message to convert * @return the converted JSON object */ public static JsonObject protobufToJsonCamelCase(Message input) { JsonObject object = new JsonObject(); if (input == null) { logger.warn("Protobuf message was null"); } else { try { String jsonString = JsonFormat.printer() .print(input); object = new JsonParser().parse(jsonString).getAsJsonObject(); } catch (Exception e) { throw new RuntimeException("Error deserializing protobuf to json", e); } } return object; }
Example #7
Source File: VariantTest.java From phenopacket-schema with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test void compoundHeterozygousVariant() throws Exception { Variant het1 = Variant.newBuilder() .setVcfAllele(FGFR2_PATH_ALLELE_1) .setZygosity(HET) .build(); Variant het2 = Variant.newBuilder() .setVcfAllele(FGFR2_LIKELY_PATH_ALLELE_2) .setZygosity(HET) .build(); Phenopacket phenopacket = Phenopacket.newBuilder() .setId("pfeiffer_compound_heterozygous_case") .addVariants(het1) .addVariants(het2) .addDiseases(PFIEFFER_SYNDROME) .setMetaData(META_DATA) .build(); System.out.println(JsonFormat.printer().print(phenopacket)); }
Example #8
Source File: DirectRunnerJobManager.java From feast with Apache License 2.0 | 6 votes |
private ImportOptions getPipelineOptions( String jobName, SourceProto.Source source, Set<StoreProto.Store> sinks) throws IOException, IllegalAccessException { ImportOptions pipelineOptions = PipelineOptionsFactory.fromArgs(defaultOptions.toArgs()).as(ImportOptions.class); JsonFormat.Printer printer = JsonFormat.printer(); pipelineOptions.setSpecsStreamingUpdateConfigJson(printer.print(specsStreamingUpdateConfig)); pipelineOptions.setSourceJson(printer.print(source)); pipelineOptions.setJobName(jobName); pipelineOptions.setStoresJson( sinks.stream().map(wrapException(printer::print)).collect(Collectors.toList())); pipelineOptions.setRunner(DirectRunner.class); pipelineOptions.setDefaultFeastProject(Project.DEFAULT_NAME); pipelineOptions.setProject(""); // set to default value to satisfy validation if (metrics.isEnabled()) { pipelineOptions.setMetricsExporterType(metrics.getType()); if (metrics.getType().equals("statsd")) { pipelineOptions.setStatsdHost(metrics.getHost()); pipelineOptions.setStatsdPort(metrics.getPort()); } } pipelineOptions.setBlockOnRun(false); return pipelineOptions; }
Example #9
Source File: ProtobufHttpMessageConverterTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void writeJsonWithGoogleProtobuf() throws IOException { this.converter = new ProtobufHttpMessageConverter( new ProtobufHttpMessageConverter.ProtobufJavaUtilSupport(null, null), this.extensionRegistry); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MediaType contentType = MediaType.APPLICATION_JSON; this.converter.write(this.testMsg, contentType, outputMessage); assertEquals(contentType, outputMessage.getHeaders().getContentType()); final String body = outputMessage.getBodyAsString(Charset.forName("UTF-8")); assertFalse("body is empty", body.isEmpty()); Msg.Builder builder = Msg.newBuilder(); JsonFormat.parser().merge(body, builder); assertEquals(this.testMsg, builder.build()); assertNull(outputMessage.getHeaders().getFirst( ProtobufHttpMessageConverter.X_PROTOBUF_MESSAGE_HEADER)); assertNull(outputMessage.getHeaders().getFirst( ProtobufHttpMessageConverter.X_PROTOBUF_SCHEMA_HEADER)); }
Example #10
Source File: ClientRpcStore.java From seldon-server with Apache License 2.0 | 6 votes |
public ClassificationReply getPredictReplyFromJson(String client,JsonNode json) { RPCConfig config = services.get(client); try { TypeRegistry registry = null; if (config != null && config.replyClass != null && json.has(PredictionBusinessServiceImpl.REPLY_CUSTOM_DATA_FIELD)) { if (!json.get(PredictionBusinessServiceImpl.REPLY_CUSTOM_DATA_FIELD).has("@type")) ((ObjectNode) json.get(PredictionBusinessServiceImpl.REPLY_CUSTOM_DATA_FIELD)).put("@type", "type.googleapis.com/" + config.replyClass.getName()); Method m = config.replyBuilder; Message.Builder o = (Message.Builder) m.invoke(null); registry = TypeRegistry.newBuilder().add(o.getDescriptorForType()).build(); } ClassificationReply.Builder builder = ClassificationReply.newBuilder(); JsonFormat.Parser jFormatter = JsonFormat.parser(); if (registry != null) jFormatter = jFormatter.usingTypeRegistry(registry); jFormatter.merge(json.toString(), builder); ClassificationReply reply = builder.build(); return reply; } catch (Exception e) { logger.error("Failed to convert json "+json.toString()+" to PredictReply",e); return null; } }
Example #11
Source File: GithubClient.java From startup-os with Apache License 2.0 | 6 votes |
public CreateIssueCommentResponse createIssueComment(CreateIssueCommentRequest request) { try { String requestData = JsonFormat.printer().print(request.getRequestData()); String response = doRequest( RequestMethod.POST, String.format( CREATE_COMMENT_ON_ISSUE, request.getOwner(), request.getRepo(), request.getNumber()), requestData); CreateIssueCommentResponse.Builder builder = CreateIssueCommentResponse.newBuilder(); JsonFormat.parser() .ignoringUnknownFields() .merge(String.format("{\"issue_comment\":%s}", response), builder); return builder.build(); } catch (IOException e) { throw new RuntimeException(e); } }
Example #12
Source File: AbstractMetricsPublisher.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
protected static String formatRequestMetadataToJson( OperationRequestMetadata operationRequestMetadata) throws InvalidProtocolBufferException { JsonFormat.TypeRegistry typeRegistry = JsonFormat.TypeRegistry.newBuilder() .add(ExecuteResponse.getDescriptor()) .add(ExecuteOperationMetadata.getDescriptor()) .add(PreconditionFailure.getDescriptor()) .build(); String formattedRequestMetadata = JsonFormat.printer() .usingTypeRegistry(typeRegistry) .omittingInsignificantWhitespace() .print(operationRequestMetadata); logger.log(Level.FINE, "{}", formattedRequestMetadata); return formattedRequestMetadata; }
Example #13
Source File: FamilyTest.java From phenopacket-schema with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test void roundTrippingFamily() throws IOException { Family original = TestExamples.rareDiseaseFamily(); String json = JsonFormat.printer().print(original); String asYaml = FormatMapper.jsonToYaml(json); System.out.println(asYaml); System.out.println(json); String asJson = FormatMapper.yamlToJson(asYaml); System.out.println(asJson); Family.Builder familyBuilder = Family.newBuilder(); JsonFormat.parser().merge(asJson, familyBuilder); Family fromJson = familyBuilder.build(); //Ta-da! assertThat(fromJson, equalTo(original)); }
Example #14
Source File: GetSizeCommandTest.java From bundletool with Apache License 2.0 | 6 votes |
@Test @Theory public void checkFlagsConstructionWithDeviceSpec( @FromDataPoints("deviceSpecs") String deviceSpecPath) throws Exception { DeviceSpec.Builder expectedDeviceSpecBuilder = DeviceSpec.newBuilder(); try (Reader reader = TestData.openReader(deviceSpecPath)) { JsonFormat.parser().merge(reader, expectedDeviceSpecBuilder); } DeviceSpec expectedDeviceSpec = expectedDeviceSpecBuilder.build(); BuildApksResult tableOfContentsProto = BuildApksResult.getDefaultInstance(); Path apksArchiveFile = createApksArchiveFile(tableOfContentsProto, tmpDir.resolve("bundle.apks")); Path deviceSpecFile = copyToTempDir(deviceSpecPath); GetSizeCommand command = GetSizeCommand.fromFlags( new FlagParser() .parse( "get-size", "total", "--device-spec=" + deviceSpecFile, "--apks=" + apksArchiveFile)); assertThat(command.getDeviceSpec()).isEqualTo(expectedDeviceSpec); }
Example #15
Source File: GetDeviceSpecCommand.java From bundletool with Apache License 2.0 | 6 votes |
private void writeDeviceSpecToFile(DeviceSpec deviceSpec, Path outputFile) { try { if (getOverwriteOutput()) { Files.deleteIfExists(getOutputPath()); } Path outputDirectory = getOutputPath().getParent(); if (outputDirectory != null && !Files.exists(outputDirectory)) { logger.info("Output directory '" + outputDirectory + "' does not exist, creating it."); Files.createDirectories(outputDirectory); } Files.write(outputFile, JsonFormat.printer().print(deviceSpec).getBytes(UTF_8)); } catch (IOException e) { throw new UncheckedIOException( String.format("Error while writing the output file '%s'.", outputFile), e); } }
Example #16
Source File: RedisBackedJobService.java From feast with Apache License 2.0 | 6 votes |
@Override public Optional<Job> get(String id) { Job job = null; try { String json = new String(syncCommand.get(id.getBytes())); if (json.isEmpty()) { return Optional.empty(); } Builder builder = Job.newBuilder(); JsonFormat.parser().merge(json, builder); job = builder.build(); } catch (Exception e) { log.error(String.format("Failed to parse JSON for Feast job: %s", e.getMessage())); } return Optional.ofNullable(job); }
Example #17
Source File: GithubClient.java From startup-os with Apache License 2.0 | 6 votes |
public PullRequestCommentsResponse getPullRequestComments(PullRequestCommentsRequest request) throws IOException { PullRequestCommentsResponse.Builder builder = PullRequestCommentsResponse.newBuilder(); String response = doRequest( RequestMethod.GET, String.format( GET_COMMENTS_ON_PULL_REQUEST, request.getOwner(), request.getRepo(), request.getNumber())); JsonFormat.parser() .ignoringUnknownFields() .merge(String.format("{\"review_comment\":%s}", response), builder); return builder.build(); }
Example #18
Source File: RedisShardBackplane.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
private void removeInvalidWorkers(JedisCluster jedis, long testedAt, List<ShardWorker> workers) { if (!workers.isEmpty()) { for (ShardWorker worker : workers) { String name = worker.getEndpoint(); String reason = format("registration expired at %d, tested at %d", worker.getExpireAt(), testedAt); WorkerChange workerChange = WorkerChange.newBuilder() .setEffectiveAt(toTimestamp(Instant.now())) .setName(name) .setRemove( WorkerChange.Remove.newBuilder().setSource(source).setReason(reason).build()) .build(); try { String workerChangeJson = JsonFormat.printer().print(workerChange); removeWorkerAndPublish(jedis, name, workerChangeJson); } catch (InvalidProtocolBufferException e) { logger.log(Level.SEVERE, "error printing workerChange", e); } } } }
Example #19
Source File: GithubClient.java From startup-os with Apache License 2.0 | 6 votes |
public CreatePullRequestResponse createPullRequest(CreatePullRequestRequest request) { try { String requestData = JsonFormat.printer().print(request.getRequestData()); String response = doRequest( RequestMethod.POST, String.format(CREATE_PULL_REQUEST, request.getOwner(), request.getRepo()), requestData); CreatePullRequestResponse.Builder builder = CreatePullRequestResponse.newBuilder(); JsonFormat.parser() .ignoringUnknownFields() .merge(String.format("{\"pull_request\":%s}", response), builder); return builder.build(); } catch (IOException e) { throw new RuntimeException(e); } }
Example #20
Source File: RedisShardBackplane.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
@Override public boolean pollOperation(QueueEntry queueEntry, ExecutionStage.Value stage, long requeueAt) throws IOException { String operationName = queueEntry.getExecuteEntry().getOperationName(); DispatchedOperation o = DispatchedOperation.newBuilder().setQueueEntry(queueEntry).setRequeueAt(requeueAt).build(); String json; try { json = JsonFormat.printer().print(o); } catch (InvalidProtocolBufferException e) { logger.log(Level.SEVERE, "error printing dispatched operation " + operationName, e); return false; } return client.call( jedis -> { if (jedis.hexists(config.getDispatchedOperationsHashName(), operationName)) { if (jedis.hset(config.getDispatchedOperationsHashName(), operationName, json) == 0) { return true; } /* someone else beat us to the punch, delete our incorrectly added key */ jedis.hdel(config.getDispatchedOperationsHashName(), operationName); } return false; }); }
Example #21
Source File: ClientRpcStore.java From seldon-server with Apache License 2.0 | 6 votes |
private ClassificationRequest getPredictRequestWithCustomDefaultFromJSON(JsonNode json) throws InvalidProtocolBufferException { ObjectMapper mapper = new ObjectMapper(); ObjectNode data = mapper.createObjectNode(); data.put("@type", "type.googleapis.com/" + DefaultCustomPredictRequest.class.getName()); data.put("values", json.get(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD)); ((ObjectNode) json).put(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD, data); Message.Builder o = DefaultCustomPredictRequest.newBuilder(); TypeRegistry registry = TypeRegistry.newBuilder().add(o.getDescriptorForType()).build(); ClassificationRequest.Builder builder = ClassificationRequest.newBuilder(); JsonFormat.Parser jFormatter = JsonFormat.parser(); if (registry != null) jFormatter = jFormatter.usingTypeRegistry(registry); jFormatter.merge(json.toString(), builder); ClassificationRequest request = builder.build(); return request; }
Example #22
Source File: LoggerDoFn.java From feast with Apache License 2.0 | 5 votes |
@ProcessElement public void processElement(ProcessContext context) { Printer printer = JsonFormat.printer().omittingInsignificantWhitespace(); String message; try { message = prefix + printer.print(context.element()); } catch (Exception e) { log.error(e.getMessage(), e); message = prefix + context.element().toString(); } switch (level) { case INFO: log.info(message); break; case ERROR: log.error(message); break; case WARN: log.warn(message); break; case DEBUG: log.debug(message); break; case TRACE: log.trace(message); break; } }
Example #23
Source File: RedisShardBackplane.java From bazel-buildfarm with Apache License 2.0 | 5 votes |
@Override public void prequeue(ExecuteEntry executeEntry, Operation operation) throws IOException { String operationName = operation.getName(); String operationJson = operationPrinter.print(operation); String executeEntryJson = JsonFormat.printer().print(executeEntry); Operation publishOperation = onPublish.apply(operation); client.run( jedis -> { jedis.setex(operationKey(operationName), config.getOperationExpire(), operationJson); prequeue.push(jedis, executeEntryJson); publishReset(jedis, publishOperation); }); }
Example #24
Source File: GithubClient.java From startup-os with Apache License 2.0 | 5 votes |
public PullRequestResponse getPullRequest(PullRequestRequest request) throws IOException { PullRequestResponse.Builder builder = PullRequestResponse.newBuilder(); String response = doRequest( RequestMethod.GET, String.format( GET_PULL_REQUEST, request.getOwner(), request.getRepo(), request.getNumber())); JsonFormat.parser() .ignoringUnknownFields() .merge(String.format("{\"pull_request\":%s}", response), builder); return builder.build(); }
Example #25
Source File: K8sHTTPAnalysisTest.java From skywalking with Apache License 2.0 | 5 votes |
@Test public void testIngressRoleIdentify() throws IOException { try (InputStreamReader isr = new InputStreamReader(getResourceAsStream("envoy-ingress.msg"))) { StreamAccessLogsMessage.Builder requestBuilder = StreamAccessLogsMessage.newBuilder(); JsonFormat.parser().merge(isr, requestBuilder); Role identify = analysis.identify(requestBuilder.getIdentifier(), Role.NONE); Assert.assertEquals(Role.PROXY, identify); } }
Example #26
Source File: RpcUtil.java From snowblossom with Apache License 2.0 | 5 votes |
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 #27
Source File: RedisShardBackplane.java From bazel-buildfarm with Apache License 2.0 | 5 votes |
public void visit(String entry) { QueueEntry.Builder queueEntry = QueueEntry.newBuilder(); try { JsonFormat.parser().merge(entry, queueEntry); visit(queueEntry.build(), entry); } catch (InvalidProtocolBufferException e) { logger.log(Level.SEVERE, "invalid QueueEntry json: " + entry, e); } }
Example #28
Source File: JsonLedgerFactory.java From julongchain with Apache License 2.0 | 5 votes |
private ReadWriteBase newGroup(String directory){ JsonLedger jl = new JsonLedger(); jl.setDirectory(directory); jl.setPrinter(JsonFormat.printer()); jl.initializeBlockHeight(); log.debug("Initialized to block height " + (jl.getHeight() - 1)); return jl; }
Example #29
Source File: SpecUtil.java From feast with Apache License 2.0 | 5 votes |
public static List<Store> parseStoreJsonList(List<String> jsonList) throws InvalidProtocolBufferException { List<Store> stores = new ArrayList<>(); for (String json : jsonList) { Store.Builder builder = Store.newBuilder(); JsonFormat.parser().merge(json, builder); stores.add(builder.build()); } return stores; }
Example #30
Source File: ProtobufJsonTest.java From compliance with Apache License 2.0 | 5 votes |
/** * Method: avroToJson(DatumWriter dw, Schema schema, T srcBytes) * Note this test is specific to the Avro-using JSON serializer * so the "expected" JSON is in the Avro style, with JSON blocks * for non-null fields, like ... "start": { "long" : "0"} * <p> * This is fine for an Avro deserializer, but doesn't work with * default Jackson deserializing, so we'll have a distinct test * for Jackson. */ @Test @Category(ProtobufJsonTests.class) public void ProtobufGeneratesJsonBytesForDefaultGA() throws Exception { SearchReadsRequest srr = SearchReadsRequest.newBuilder() .setStart(0L) .build(); assertNotNull("test data is default GaSearchReadsRequest", srr); String actual = JsonFormat.printer().print(srr); String expected = "{\n}"; JSONAssert.assertEquals(expected, actual, true); }