本文整理汇总了Java中com.google.protobuf.InvalidProtocolBufferException类的典型用法代码示例。如果您正苦于以下问题:Java InvalidProtocolBufferException类的具体用法?Java InvalidProtocolBufferException怎么用?Java InvalidProtocolBufferException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
InvalidProtocolBufferException类属于com.google.protobuf包,在下文中一共展示了InvalidProtocolBufferException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: mergeMapField
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
private void mergeMapField(FieldDescriptor field, JsonElement json, Message.Builder builder)
throws InvalidProtocolBufferException {
if (!(json instanceof JsonObject)) {
throw new InvalidProtocolBufferException("Expect a map object but found: " + json);
}
Descriptor type = field.getMessageType();
FieldDescriptor keyField = type.findFieldByName("key");
FieldDescriptor valueField = type.findFieldByName("value");
if (keyField == null || valueField == null) {
throw new InvalidProtocolBufferException("Invalid map field: " + field.getFullName());
}
JsonObject object = (JsonObject) json;
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
Message.Builder entryBuilder = builder.newBuilderForField(field);
Object key = parseFieldValue(keyField, new JsonPrimitive(entry.getKey()), entryBuilder);
Object value = parseFieldValue(valueField, entry.getValue(), entryBuilder);
if (value == null) {
throw new InvalidProtocolBufferException("Map value cannot be null.");
}
entryBuilder.setField(keyField, key);
entryBuilder.setField(valueField, value);
builder.addRepeatedField(field, entryBuilder.build());
}
}
示例2: parseFrom
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
/**
* @param pbBytes A pb serialized {@link FirstKeyValueMatchingQualifiersFilter} instance
* @return An instance of {@link FirstKeyValueMatchingQualifiersFilter} made from <code>bytes</code>
* @throws DeserializationException
* @see #toByteArray
*/
public static FirstKeyValueMatchingQualifiersFilter parseFrom(final byte [] pbBytes)
throws DeserializationException {
FilterProtos.FirstKeyValueMatchingQualifiersFilter proto;
try {
proto = FilterProtos.FirstKeyValueMatchingQualifiersFilter.parseFrom(pbBytes);
} catch (InvalidProtocolBufferException e) {
throw new DeserializationException(e);
}
TreeSet<byte []> qualifiers = new TreeSet<byte []>(Bytes.BYTES_COMPARATOR);
for (ByteString qualifier : proto.getQualifiersList()) {
qualifiers.add(qualifier.toByteArray());
}
return new FirstKeyValueMatchingQualifiersFilter(qualifiers);
}
示例3: test
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
@Test
public void test() throws InvalidProtocolBufferException {
//模拟将对象转成byte[],方便传输
PersonDomain.Person.Builder builder = PersonDomain.Person.newBuilder();
builder.setId(1);
builder.setName("zzqfsy");
builder.setEmail("[email protected]");
PersonDomain.Person person = builder.build();
System.out.println("before :"+ person.toString());
System.out.println("===========Person Byte==========");
for(byte b : person.toByteArray()){
System.out.print(b);
}
System.out.println();
System.out.println(person.toByteString());
System.out.println("================================");
//模拟接收Byte[],反序列化成Person类
byte[] byteArray =person.toByteArray();
PersonDomain.Person p2 = PersonDomain.Person.parseFrom(byteArray);
System.out.println("after :" +p2.toString());
}
示例4: appendPeerState
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
private static void appendPeerState(ZooKeeperWatcher zkw, String znodeToProcess,
StringBuilder sb) throws KeeperException, InvalidProtocolBufferException {
String peerState = zkw.getConfiguration().get("zookeeper.znode.replication.peers.state",
"peer-state");
int pblen = ProtobufUtil.lengthOfPBMagic();
for (String child : ZKUtil.listChildrenNoWatch(zkw, znodeToProcess)) {
if (!child.equals(peerState)) continue;
String peerStateZnode = ZKUtil.joinZNode(znodeToProcess, child);
sb.append("\n").append(peerStateZnode).append(": ");
byte[] peerStateData;
try {
peerStateData = ZKUtil.getData(zkw, peerStateZnode);
ZooKeeperProtos.ReplicationState.Builder builder =
ZooKeeperProtos.ReplicationState.newBuilder();
ProtobufUtil.mergeFrom(builder, peerStateData, pblen, peerStateData.length - pblen);
sb.append(builder.getState().name());
} catch (IOException ipbe) {
LOG.warn("Got Exception while parsing peer: " + znodeToProcess, ipbe);
} catch (InterruptedException e) {
zkw.interruptedException(e);
return;
}
}
}
示例5: createMultiDeviceSentTranscriptContent
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
private byte[] createMultiDeviceSentTranscriptContent(byte[] content, Optional<SignalServiceAddress> recipient, long timestamp)
{
try {
Content.Builder container = Content.newBuilder();
SyncMessage.Builder syncMessage = SyncMessage.newBuilder();
SyncMessage.Sent.Builder sentMessage = SyncMessage.Sent.newBuilder();
DataMessage dataMessage = DataMessage.parseFrom(content);
sentMessage.setTimestamp(timestamp);
sentMessage.setMessage(dataMessage);
if (recipient.isPresent()) {
sentMessage.setDestination(recipient.get().getNumber());
}
if (dataMessage.getExpireTimer() > 0) {
sentMessage.setExpirationStartTimestamp(System.currentTimeMillis());
}
return container.setSyncMessage(syncMessage.setSent(sentMessage)).build().toByteArray();
} catch (InvalidProtocolBufferException e) {
throw new AssertionError(e);
}
}
示例6: onMessage
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
@Override
public synchronized void onMessage(WebSocket webSocket, ByteString payload) {
Log.w(TAG, "WSC onMessage()");
try {
WebSocketMessage message = WebSocketMessage.parseFrom(payload.toByteArray());
Log.w(TAG, "Message Type: " + message.getType().getNumber());
if (message.getType().getNumber() == WebSocketMessage.Type.REQUEST_VALUE) {
incomingRequests.add(message.getRequest());
} else if (message.getType().getNumber() == WebSocketMessage.Type.RESPONSE_VALUE) {
SettableFuture<Pair<Integer, String>> listener = outgoingRequests.get(message.getResponse().getId());
if (listener != null) listener.set(new Pair<>(message.getResponse().getStatus(),
new String(message.getResponse().getBody().toByteArray())));
}
notifyAll();
} catch (InvalidProtocolBufferException e) {
Log.w(TAG, e);
}
}
示例7: customStringRequest
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
@Test
public void customStringRequest() throws InvalidProtocolBufferException
{
String customData = "{\"c\":1.0}";
SeldonMessage.Builder b = SeldonMessage.newBuilder();
b.setStrData(customData);
SeldonMessage request = b.build();
String json = ProtoBufUtils.toJson(request);
System.out.println(json);
SeldonMessage.Builder b2 = SeldonMessage.newBuilder();
ProtoBufUtils.updateMessageBuilderFromJson(b2, json);
SeldonMessage request2 = b2.build();
String json2 = ProtoBufUtils.toJson(request2);
System.out.println(json2);
Assert.assertEquals(json, json2);
}
示例8: testCorruptMeta
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
@Test(expected = InvalidProtocolBufferException.class)
public void testCorruptMeta() throws Throwable {
EventQueueBackingStore backingStore =
EventQueueBackingStoreFactory.get(checkpoint, 10, "test");
backingStore.close();
Assert.assertTrue(checkpoint.exists());
File metaFile = Serialization.getMetaDataFile(checkpoint);
Assert.assertTrue(metaFile.length() != 0);
RandomAccessFile writer = new RandomAccessFile(metaFile, "rw");
writer.seek(10);
writer.writeLong(new Random().nextLong());
writer.getFD().sync();
writer.close();
try {
backingStore = EventQueueBackingStoreFactory.get(checkpoint, 10, "test");
} catch (BadCheckpointException ex) {
throw ex.getCause();
}
}
示例9: testGetOutputNoChildren
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
@Test
public void testGetOutputNoChildren() throws InterruptedException, ExecutionException, InvalidProtocolBufferException{
SeldonMessage p = SeldonMessage.newBuilder().build();
PredictiveUnitState state = new PredictiveUnitState("Cool_name",null,new ArrayList<PredictiveUnitState>(),null,null,null,null,PredictiveUnitImplementation.AVERAGE_COMBINER);
PredictiveUnitBean predictiveUnit = new PredictiveUnitBean();
SimpleModelUnit simpleModel = new SimpleModelUnit();
SimpleRouterUnit simpleRouterUnit = new SimpleRouterUnit();
AverageCombinerUnit averageCombiner = new AverageCombinerUnit();
RandomABTestUnit randomABTest = new RandomABTestUnit();
PredictorConfigBean predictorConfig = new PredictorConfigBean(
simpleModel,
simpleRouterUnit,
averageCombiner,
randomABTest);
predictiveUnit.predictorConfig = predictorConfig;
predictiveUnit.getOutput(p, state);
}
示例10: getNodeData
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
@Override
@SuppressWarnings("unchecked")
protected <M extends Message> ListenableFuture<M> getNodeData(
WatchCallback watcher, String path, Message.Builder builder) {
final SettableFuture<M> future = SettableFuture.create();
byte[] data = new byte[]{};
if (FileUtils.isFileExists(path)) {
data = FileUtils.readFromFile(path);
}
if (data.length == 0) {
future.set(null);
return future;
}
try {
builder.mergeFrom(data);
future.set((M) builder.build());
} catch (InvalidProtocolBufferException e) {
future.setException(new RuntimeException("Could not parse " + Message.Builder.class, e));
}
return future;
}
示例11: parseFrom
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
/**
* @param pbBytes A pb serialized {@link SingleColumnValueExcludeFilter} instance
* @return An instance of {@link SingleColumnValueExcludeFilter} made from <code>bytes</code>
* @throws DeserializationException
* @see #toByteArray
*/
public static SingleColumnValueExcludeFilter parseFrom(final byte [] pbBytes)
throws DeserializationException {
FilterProtos.SingleColumnValueExcludeFilter proto;
try {
proto = FilterProtos.SingleColumnValueExcludeFilter.parseFrom(pbBytes);
} catch (InvalidProtocolBufferException e) {
throw new DeserializationException(e);
}
FilterProtos.SingleColumnValueFilter parentProto = proto.getSingleColumnValueFilter();
final CompareOp compareOp =
CompareOp.valueOf(parentProto.getCompareOp().name());
final ByteArrayComparable comparator;
try {
comparator = ProtobufUtil.toComparator(parentProto.getComparator());
} catch (IOException ioe) {
throw new DeserializationException(ioe);
}
return new SingleColumnValueExcludeFilter(parentProto.hasColumnFamily() ? parentProto
.getColumnFamily().toByteArray() : null, parentProto.hasColumnQualifier() ? parentProto
.getColumnQualifier().toByteArray() : null, compareOp, comparator, parentProto
.getFilterIfMissing(), parentProto.getLatestVersionOnly());
}
示例12: inflate
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
public static byte[] inflate(PbfRawBlob rawBlob) throws InvalidProtocolBufferException {
Blob blob = Blob.parseFrom(rawBlob.getData());
byte[] blobData;
if (blob.hasRaw()) {
blobData = blob.getRaw().toByteArray();
}
else if (blob.hasZlibData()) {
Inflater inflater = new Inflater();
inflater.setInput(blob.getZlibData().toByteArray());
blobData = new byte[blob.getRawSize()];
try {
inflater.inflate(blobData);
}
catch (DataFormatException e) {
throw new OsmosisRuntimeException("Unable to decompress PBF blob.", e);
}
if (!inflater.finished()) {
throw new OsmosisRuntimeException("PBF blob contains incomplete compressed data.");
}
}
else {
throw new OsmosisRuntimeException("PBF blob uses unsupported compression, only raw or zlib may be used.");
}
return blobData;
}
示例13: decodeProtobuf
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
/**
* Handle all the logic leading to the decoding of a Protobuf-encoded binary given a schema file path.
* @param schema Schema used to decode the binary data
* @param messageType Type of Protobuf Message
* @param encodedData Encoded data source
* @return A JSON representation of the data, contained in a Java String
* @throws InvalidProtocolBufferException Thrown when an error occurs during the encoding of the decoded data into JSON
* @throws Descriptors.DescriptorValidationException Thrown when the schema is invalid
* @throws UnknownMessageTypeException Thrown when the given message type is not contained in the schema
* @throws MessageDecodingException Thrown when an error occurs during the binary decoding
* @throws SchemaLoadingException Thrown when an error occurs while reading the schema file
*/
public static String decodeProtobuf(DynamicSchema schema, String messageType, InputStream encodedData) throws InvalidProtocolBufferException, Descriptors.DescriptorValidationException, UnknownMessageTypeException, MessageDecodingException, SchemaLoadingException {
Descriptors.Descriptor descriptor;
DynamicMessage message;
descriptor = schema.getMessageDescriptor(messageType);
if (descriptor == null) {
throw new UnknownMessageTypeException(messageType);
}
try {
message = DynamicMessage.parseFrom(descriptor, encodedData);
} catch (IOException e) {
throw new MessageDecodingException(e);
}
return JSONMapper.toJSON(message);
}
示例14: unpackByteArrayPacket
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
@Override
public IObject unpackByteArrayPacket(ByteArrayPacket byteArrayPacket) {
int opCode = byteArrayPacket.getOpCode();
IObject cObject = CObject.newInstance();
switch (SystemRequest.get(opCode)) {
case USER_LOGIN_PB:
try {
PBSystem.CS_USER_CONNECT_TO_SERVER login = PBSystem.CS_USER_CONNECT_TO_SERVER.parseFrom(byteArrayPacket.getRawData());
String name = login.getName();
String params = login.getParams();
cObject.putUtfString("name", name);
cObject.putUtfString("params", params);
return cObject;
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
break;
default:
break;
}
return cObject;
}
示例15: checkBroadcastResponse
import com.google.protobuf.InvalidProtocolBufferException; //导入依赖的package包/类
private void checkBroadcastResponse(ByteString expectedResponseBytes)
throws InvalidProtocolBufferException {
List<Intent> broadcasts =
Shadows.shadowOf(RuntimeEnvironment.application).getBroadcastIntents();
assertThat(broadcasts.size()).isEqualTo(1);
Intent broadcastIntent = broadcasts.get(0);
assertThat(broadcastIntent.getAction())
.isEqualTo("example:0000000000000080");
assertThat(broadcastIntent.getCategories()).containsExactly(QueryUtil.BBQ_CATEGORY);
assertThat(broadcastIntent.getPackage()).isEqualTo(mQuery.getRequestingApp());
assertThat(broadcastIntent.getByteArrayExtra(QueryUtil.EXTRA_RESPONSE_MESSAGE)).isNotNull();
byte[] responseBytes = broadcastIntent.getByteArrayExtra(QueryUtil.EXTRA_RESPONSE_MESSAGE);
BroadcastQueryResponse response = BroadcastQueryResponse.parseFrom(responseBytes);
assertThat(response.getRequestId()).isEqualTo(mQuery.getRequestId());
assertThat(response.getResponseId()).isEqualTo(mQuery.getResponseId());
assertThat(response.getResponseMessage()).isEqualTo(expectedResponseBytes);
}