本文整理汇总了Java中com.googlecode.protobuf.format.JsonFormat类的典型用法代码示例。如果您正苦于以下问题:Java JsonFormat类的具体用法?Java JsonFormat怎么用?Java JsonFormat使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
JsonFormat类属于com.googlecode.protobuf.format包,在下文中一共展示了JsonFormat类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: write
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
/**
* Writes as a string using the format specified the FileTrackingStatus
*
* @param format
* @param file
* @return
*/
public String write(FORMAT format, FileStatus.FileTrackingStatus file) {
String ret = null;
if (format.equals(FORMAT.JSON)) {
try {
ret = JsonFormat.printToString(file);
} catch (Exception excp) {
RuntimeException rte = new RuntimeException(excp.toString(),
excp);
rte.setStackTrace(excp.getStackTrace());
throw rte;
}
} else {
ret = toTXT(file);
}
return ret;
}
示例2: sendCall
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
protected void sendCall(GeneratedMessage call) {
try {
StringWriter body = new StringWriter();
new JsonFormat().print(call, body);
logger.debug("[call] " + body);
Request request = new Request(url)
.method(Request.Method.POST)
.contentType("application/json")
.accept("application/json")
.body(("" + body).getBytes("utf-8"));
if (streamId != null) // Mesos 0.25 has no streamId
request.header("Mesos-Stream-Id", streamId);
Request.Response response = request.send();
logger.debug("[response] " + response.code() + " - " + response.message() + (response.body() != null ? ": " + new String(response.body()) : ""));
if (response.code() != 202)
throw new DriverException("Response: " + response.code() + " - " + response.message() + (response.body() != null ? ": " + new String(response.body()) : ""));
} catch (IOException e) {
throw new DriverException(e);
}
}
示例3: parseJava
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
protected static String parseJava(final String content) {
final ASTParser parser = ASTParser.newParser(astLevel);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(content.toCharArray());
final Map options = JavaCore.getOptions();
JavaCore.setComplianceOptions(javaVersion, options);
parser.setCompilerOptions(options);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
final ASTRoot.Builder ast = ASTRoot.newBuilder();
try {
ast.addNamespaces(visitor.getNamespaces(cu));
for (final String s : visitor.getImports())
ast.addImports(s);
} catch (final Exception e) {
System.err.println(e);
e.printStackTrace();
return "";
}
return JsonFormat.printToString(ast.build());
}
示例4: buildOafObject
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
/**
* Builds {@link Oaf} object from JSON body represetation and updates.
*
* @param bodyRecords body records with optional updates
* @return {@link Oaf} object built from JSON representation or null when body was undefined
* @throws UnsupportedEncodingException
* @throws ParseException
*/
private Oaf buildOafObject(List<QualifiedOafJsonRecord> bodyRecords) throws UnsupportedEncodingException, ParseException {
if (bodyRecords !=null) {
OafBodyWithOrderedUpdates bodyWithUpdates = new OafBodyWithOrderedUpdates(bodyRecords);
if (bodyWithUpdates.getBody() != null) {
Oaf.Builder oafBuilder = Oaf.newBuilder();
JsonFormat.merge(bodyWithUpdates.getBody(), oafBuilder);
if (this.mergeBodyWithUpdates) {
for (String oafUpdate : bodyWithUpdates.getOrderedUpdates()) {
JsonFormat.merge(oafUpdate, oafBuilder);
}
}
return oafBuilder.build();
}
}
return null;
}
示例5: testReduceResultBelowTrustLevelThreshold
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
@Test
public void testReduceResultBelowTrustLevelThreshold() throws Exception {
// given
Configuration conf = setOutputDirs(new Configuration());
conf.set(IMPORT_TRUST_LEVEL_THRESHOLD, "0.8");
doReturn(conf).when(context).getConfiguration();
reducer.setup(context);
String resultId = "resultId";
String id = InfoSpaceConstants.ROW_PREFIX_RESULT + resultId;
Text key = new Text(id);
InfoSpaceRecord bodyRecord = new InfoSpaceRecord(
new Text(Type.result.name()),
new Text(OafBodyWithOrderedUpdates.BODY_QUALIFIER_NAME),
new Text(JsonFormat.printToString(buildResultEntity(resultId))));
List<InfoSpaceRecord> values = Lists.newArrayList(bodyRecord);
// execute
reducer.reduce(key, values, context);
// assert
verify(context, never()).write(any(), any());
verify(multipleOutputs, never()).write(any(), any());
}
示例6: testReduceResultWithProvenanceBlacklist
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
@Test
public void testReduceResultWithProvenanceBlacklist() throws Exception {
// given
Configuration conf = setOutputDirs(new Configuration());
conf.set(IMPORT_INFERENCE_PROVENANCE_BLACKLIST, INFERENCE_PROVENANCE_DEFAULT);
doReturn(conf).when(context).getConfiguration();
reducer.setup(context);
String resultId = "resultId";
String id = InfoSpaceConstants.ROW_PREFIX_RESULT + resultId;
Text key = new Text(id);
InfoSpaceRecord bodyRecord = new InfoSpaceRecord(
new Text(Type.result.name()),
new Text(OafBodyWithOrderedUpdates.BODY_QUALIFIER_NAME),
new Text(JsonFormat.printToString(buildResultEntity(resultId))));
List<InfoSpaceRecord> values = Lists.newArrayList(bodyRecord);
// execute
reducer.reduce(key, values, context);
// assert
verify(context, never()).write(any(), any());
verify(multipleOutputs, never()).write(any(), any());
}
示例7: testReduceResultDeletedByInference
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
@Test
public void testReduceResultDeletedByInference() throws Exception {
// given
Configuration conf = setOutputDirs(new Configuration());
conf.set(IMPORT_SKIP_DELETED_BY_INFERENCE, "true");
doReturn(conf).when(context).getConfiguration();
reducer.setup(context);
String resultId = "resultId";
String id = InfoSpaceConstants.ROW_PREFIX_RESULT + resultId;
Text key = new Text(id);
InfoSpaceRecord bodyRecord = new InfoSpaceRecord(
new Text(Type.result.name()),
new Text(OafBodyWithOrderedUpdates.BODY_QUALIFIER_NAME),
new Text(JsonFormat.printToString(buildResultEntity(resultId, true))));
List<InfoSpaceRecord> values = Lists.newArrayList(bodyRecord);
// execute
reducer.reduce(key, values, context);
// assert
verify(context, never()).write(any(), any());
verify(multipleOutputs, never()).write(any(), any());
}
示例8: readInternal
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
@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);
}
}
示例9: readList
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
/**
* Reads a collection of FileTrackingStatus.<br/>
* If plain text is a list of line separated plain text.<br/>
* If json this should be a json array.<br/>
*
* @param format
* @param reader
* @return
* @throws JsonParseException
* @throws JsonMappingException
* @throws IOException
*/
@SuppressWarnings("unchecked")
public Collection<FileStatus.FileTrackingStatus> readList(FORMAT format,
Reader reader) throws JsonParseException, JsonMappingException,
IOException {
Collection<FileStatus.FileTrackingStatus> coll = null;
if (format.equals(FORMAT.JSON)) {
Collection<String> strcoll = (Collection<String>) mapper.readValue(
reader, new TypeReference<Collection<String>>() {
});
coll = new ArrayList<FileStatus.FileTrackingStatus>();
for (String str : strcoll) {
Builder builder = FileStatus.FileTrackingStatus.newBuilder();
JsonFormat.merge(str, builder);
coll.add(builder.build());
}
} else {
BufferedReader buff = new BufferedReader(reader);
coll = new ArrayList<FileStatus.FileTrackingStatus>();
String line = null;
while ((line = buff.readLine()) != null) {
coll.add(read(FORMAT.TXT, line));
}
}
return coll;
}
示例10: run0
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
private void run0() throws IOException {
try (Request request = new Request(url)) {
request.method(Request.Method.POST)
.contentType("application/json")
.accept("application/json");
StringWriter requestJson = new StringWriter();
new JsonFormat().print(subscribeCall(), requestJson);
request.body(requestJson.toString().getBytes("utf-8"));
logger.debug("[subscribe] " + requestJson);
Request.Response response = request.send(true);
if (response.code() != 200)
throw new DriverException("Response: " + response.code() + " - " + response.message() + (response.body() != null ? ": " + new String(response.body()) : ""));
streamId = response.header("Mesos-Stream-Id");
InputStream stream = response.stream();
while (state != State.STOPPED) {
int size = readChunkSize(stream);
byte[] buffer = readChunk(stream, size);
String json = new String(buffer);
logger.debug("[event] " + json);
json = json
.replaceAll("\\\\/", "/") // wrong slash escaping bug
.replaceAll("\\{\\}", "{\"_t\":1}"); // expected identified } bug
onEvent(json);
}
stream.close();
} finally {
streamId = null;
}
}
示例11: onEvent
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
@Override
protected void onEvent(String json) {
Event.Builder builder = Event.newBuilder();
try { new JsonFormat().merge(json, ExtensionRegistry.getEmptyRegistry(), builder); }
catch (JsonFormat.ParseException e) { throw new DriverException(e); }
Event event = builder.build();
switch (event.getType()) {
case SUBSCRIBED:
state = State.SUBSCRIBED;
Event.Subscribed subscribed = event.getSubscribed();
framework.id(subscribed.getFrameworkId().getValue());
scheduler.subscribed(this, subscribed.getFrameworkId().getValue(), null);
break;
case OFFERS:
List<Offer> offers = new ArrayList<>();
for (Protos.Offer o : event.getOffers().getOffersList()) offers.add(new Offer().proto1(o));
scheduler.offers(offers);
break;
case UPDATE:
Protos.TaskStatus status = event.getUpdate().getStatus();
scheduler.status(new Task.Status().proto1(status));
if (status.hasUuid()) sendCall(acknowledgeCall(status));
break;
case MESSAGE:
Event.Message message = event.getMessage();
scheduler.message(message.getExecutorId().getValue(), message.getAgentId().getValue(), message.getData().toByteArray());
break;
case ERROR:
Event.Error error = event.getError();
throw new DriverException(error.getMessage(), isUnrecoverable(error));
case RESCIND: case FAILURE: case HEARTBEAT:
break; // ignore
default:
throw new UnsupportedOperationException("Unsupported event: " + event);
}
}
示例12: decode
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
@Override
public Message decode(byte[] buffer, Message.Builder builder) throws InvalidProtocolBufferException, ParseException {
if (builder == null)
throw new IllegalArgumentException("Message builder not specified");
if (buffer == null)
return null;
String json = new String(buffer, charset);
JsonFormat.merge(json, builder);
return builder.build();
}
示例13: encode
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
@Override
public byte[] encode(Message message) {
if (message == null)
return new byte[0];
String json = JsonFormat.printToString(message);
return json.getBytes(charset);
}
示例14: testReduceResultWithMergedBodyUpdates
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
@Test
public void testReduceResultWithMergedBodyUpdates() throws Exception {
// given
Configuration conf = setOutputDirs(new Configuration());
conf.set(IMPORT_MERGE_BODY_WITH_UPDATES, "true");
doReturn(conf).when(context).getConfiguration();
reducer.setup(context);
String resultId = "resultId";
String id = InfoSpaceConstants.ROW_PREFIX_RESULT + resultId;
Text key = new Text(id);
InfoSpaceRecord bodyRecord = new InfoSpaceRecord(
new Text(Type.result.name()),
new Text(OafBodyWithOrderedUpdates.BODY_QUALIFIER_NAME),
new Text(JsonFormat.printToString(buildResultEntity(resultId))));
String updatedPublisher = "updated publisher";
InfoSpaceRecord updateRecord = new InfoSpaceRecord(
new Text(Type.result.name()),
new Text("update"),
new Text(JsonFormat.printToString(buildResultEntity(resultId, updatedPublisher, false))));
List<InfoSpaceRecord> values = Lists.newArrayList(
bodyRecord, updateRecord);
// execute
reducer.reduce(key, values, context);
// assert
verify(context, never()).write(any(), any());
verify(multipleOutputs, times(1)).write(mosKeyCaptor.capture(), mosValueCaptor.capture());
// doc meta
assertEquals(conf.get(OUTPUT_NAME_DOCUMENT_META), mosKeyCaptor.getValue());
DocumentMetadata docMeta = (DocumentMetadata) mosValueCaptor.getValue().datum();
assertNotNull(docMeta);
assertEquals(resultId, docMeta.getId());
assertEquals(updatedPublisher, docMeta.getPublisher());
}
示例15: testReduceOrganization
import com.googlecode.protobuf.format.JsonFormat; //导入依赖的package包/类
@Test
public void testReduceOrganization() throws Exception {
// given
Configuration conf = setOutputDirs(new Configuration());
doReturn(conf).when(context).getConfiguration();
reducer.setup(context);
String orgId = "organizationId";
String id = InfoSpaceConstants.ROW_PREFIX_ORGANIZATION + orgId;
Text key = new Text(id);
List<InfoSpaceRecord> values = Lists.newArrayList(new InfoSpaceRecord(
new Text(Type.organization.name()),
new Text(OafBodyWithOrderedUpdates.BODY_QUALIFIER_NAME),
new Text(JsonFormat.printToString(buildOrganizationEntity(orgId)))));
// execute
reducer.reduce(key, values, context);
// assert
verify(context, never()).write(any(), any());
verify(multipleOutputs, times(1)).write(mosKeyCaptor.capture(), mosValueCaptor.capture());
assertEquals(conf.get(OUTPUT_NAME_ORGANIZATION), mosKeyCaptor.getValue());
Organization project = (Organization) mosValueCaptor.getValue().datum();
assertNotNull(project);
// in-depth output validation is not subject of this test case
assertEquals(orgId, project.getId());
}