Java 类com.google.protobuf.InvalidProtocolBufferException 实例源码

项目:seldon-core    文件:JsonFormat.java   
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());
  }
}
项目:ditb    文件:FirstKeyValueMatchingQualifiersFilter.java   
/**
 * @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);
}
项目:ditb    文件:ZKUtil.java   
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;
    }
  }
}
项目:PeSanKita-lib    文件:SignalServiceMessageSender.java   
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);
  }
}
项目:PeSanKita-lib    文件:WebSocketConnection.java   
@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);
  }
}
项目:seldon-core    文件:TestPredictionProto.java   
@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);
}
项目:flume-release-1.7.0    文件:TestEventQueueBackingStoreFactory.java   
@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();
  }
}
项目:seldon-core    文件:AverageCombinerTest.java   
@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);
}
项目:twister2    文件:SharedFileSystemStateManager.java   
@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;
}
项目:ditb    文件:SingleColumnValueExcludeFilter.java   
/**
 * @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());
}
项目:fpm    文件:PbfBlobDecoder.java   
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;
}
项目:nifi-protobuf-processor    文件:ProtobufService.java   
/**
 * 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);
}
项目:CodeBroker    文件:ProtobuffSystemProtocolCodec.java   
@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;
}
项目:OpenYOLO-Android    文件:QueryResponseSenderTest.java   
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);
}
项目:ditb    文件:FamilyFilter.java   
/**
 * @param pbBytes A pb serialized {@link FamilyFilter} instance
 * @return An instance of {@link FamilyFilter} made from <code>bytes</code>
 * @throws DeserializationException
 * @see #toByteArray
 */
public static FamilyFilter parseFrom(final byte [] pbBytes)
throws DeserializationException {
  FilterProtos.FamilyFilter proto;
  try {
    proto = FilterProtos.FamilyFilter.parseFrom(pbBytes);
  } catch (InvalidProtocolBufferException e) {
    throw new DeserializationException(e);
  }
  final CompareOp valueCompareOp =
    CompareOp.valueOf(proto.getCompareFilter().getCompareOp().name());
  ByteArrayComparable valueComparator = null;
  try {
    if (proto.getCompareFilter().hasComparator()) {
      valueComparator = ProtobufUtil.toComparator(proto.getCompareFilter().getComparator());
    }
  } catch (IOException ioe) {
    throw new DeserializationException(ioe);
  }
  return new FamilyFilter(valueCompareOp,valueComparator);
}
项目:hadoop    文件:DFSZKFailoverController.java   
@Override
protected HAServiceTarget dataToTarget(byte[] data) {
  ActiveNodeInfo proto;
  try {
    proto = ActiveNodeInfo.parseFrom(data);
  } catch (InvalidProtocolBufferException e) {
    throw new RuntimeException("Invalid data in ZK: " +
        StringUtils.byteToHexString(data));
  }
  NNHAServiceTarget ret = new NNHAServiceTarget(
      conf, proto.getNameserviceId(), proto.getNamenodeId());
  InetSocketAddress addressFromProtobuf = new InetSocketAddress(
      proto.getHostname(), proto.getPort());

  if (!addressFromProtobuf.equals(ret.getAddress())) {
    throw new RuntimeException("Mismatched address stored in ZK for " +
        ret + ": Stored protobuf was " + proto + ", address from our own " +
        "configuration for this NameNode was " + ret.getAddress());
  }

  ret.setZkfcPort(proto.getZkfcPort());
  return ret;
}
项目:bubichain-sdk-java    文件:BlockChainAdapter.java   
private void OnResponsePing(byte[] msg, int length) {
    WebSocket conn = getConnection();
    try {
        Pong.parseFrom(msg);
        heartbeat_time_ = System.currentTimeMillis();
        logger_.debug("OnRequestPing: Recv pong from " + conn.getRemoteSocketAddress().getHostString() 
                + ":" + conn.getRemoteSocketAddress().getPort());
    } catch (InvalidProtocolBufferException e) {
        logger_.error("OnResponsePing: parse pong data failed" + " (" + conn.getRemoteSocketAddress().getHostString() 
                + ":" + conn.getRemoteSocketAddress().getPort() + ")");
    }
}
项目:GitHub    文件:ProtoConverterFactoryTest.java   
@Test public void deserializeWrongValue() throws IOException {
  ByteString encoded = ByteString.decodeBase64("////");
  server.enqueue(new MockResponse().setBody(new Buffer().write(encoded)));

  Call<?> call = service.get();
  try {
    call.execute();
    fail();
  } catch (RuntimeException e) {
    assertThat(e.getCause()).isInstanceOf(InvalidProtocolBufferException.class)
        .hasMessageContaining("input ended unexpectedly");
  }
}
项目:seldon-core    文件:PredictionService.java   
public void sendFeedback(Feedback feedback) throws InterruptedException, ExecutionException, InvalidProtocolBufferException
{
    PredictorState predictorState = predictorBean.predictorStateFromPredictorSpec(enginePredictor.getPredictorSpec());

    predictorBean.sendFeedback(feedback, predictorState);

    return;
}
项目:fernet-java8    文件:ProtocolBuffersExampleIT.java   
public Function<byte[], Session> getTransformer() {
    return bytes -> {
        try {
            return Session.parseFrom(bytes);
        } catch (final InvalidProtocolBufferException e) {
            throw new TokenValidationException("Invalid payload: " + e.getMessage(), e);
        }
    };
}
项目:ditb    文件:FirstKeyOnlyFilter.java   
/**
 * @param pbBytes A pb serialized {@link FirstKeyOnlyFilter} instance
 * @return An instance of {@link FirstKeyOnlyFilter} made from <code>bytes</code>
 * @throws org.apache.hadoop.hbase.exceptions.DeserializationException
 * @see #toByteArray
 */
public static FirstKeyOnlyFilter parseFrom(final byte [] pbBytes)
throws DeserializationException {
  // There is nothing to deserialize.  Why do this at all?
  try {
    FilterProtos.FirstKeyOnlyFilter.parseFrom(pbBytes);
  } catch (InvalidProtocolBufferException e) {
    throw new DeserializationException(e);
  }
  // Just return a new instance.
  return new FirstKeyOnlyFilter();
}
项目:iotplatform    文件:ZkDiscoveryService.java   
@Override
public List<ServerInstance> getOtherServers() {
  return cache.getCurrentData().stream().filter(cd -> !cd.getPath().equals(nodePath)).map(cd -> {
    try {
      return new ServerInstance(ServerInfo.parseFrom(cd.getData()));
    } catch (InvalidProtocolBufferException e) {
      log.error("Failed to decode ZK node", e);
      throw new RuntimeException(e);
    }
  }).collect(Collectors.toList());
}
项目:seldon-core    文件:JsonFormat.java   
private void mergeDuration(JsonElement json, Message.Builder builder)
    throws InvalidProtocolBufferException {
  try {
    Duration value = Durations.parse(json.getAsString());
    builder.mergeFrom(value.toByteString());
  } catch (ParseException e) {
    throw new InvalidProtocolBufferException("Failed to parse duration: " + json);
  }
}
项目:seldon-core    文件:JsonFormat.java   
private void mergeDuration(JsonElement json, Message.Builder builder)
    throws InvalidProtocolBufferException {
  try {
    Duration value = Durations.parse(json.getAsString());
    builder.mergeFrom(value.toByteString());
  } catch (ParseException e) {
    throw new InvalidProtocolBufferException("Failed to parse duration: " + json);
  }
}
项目:os    文件:AuthService.java   
@Override
public String auth(int serverId, Proto proto) throws ConnectionAuthException {
    Auth.AuthReq req;
    try {
        req = Auth.AuthReq.parseFrom(proto.getBody());
    } catch (InvalidProtocolBufferException e) {
        logger.error("invalid proto {} {}", proto, e.getMessage());
        throw new ConnectionAuthException("invalid proto", e);
    }
    cacheManager.getCache(CachingConfig.ONLINE).put(req.getUid(), serverId);

    logger.debug("auth serverId={}, userId={}, token={}", serverId, req.getUid(), req.getToken());
    return encodeKey(req.getUid());
}
项目:cf-java-client-sap    文件:LoggregatorMessageHandler.java   
public void onMessage(byte[] rawMessage) {
    try {
        listener.onMessage(messageParser.parseMessage(rawMessage));
    } catch (InvalidProtocolBufferException e) {
        listener.onError(e);
    }
}
项目:seldon-core    文件:JsonFormat.java   
private void mergeTimestamp(JsonElement json, Message.Builder builder)
    throws InvalidProtocolBufferException {
  try {
    Timestamp value = Timestamps.parse(json.getAsString());
    builder.mergeFrom(value.toByteString());
  } catch (ParseException e) {
    throw new InvalidProtocolBufferException("Failed to parse timestamp: " + json);
  }
}
项目:dremio-oss    文件:HiveStoragePlugin2.java   
@Override
public boolean hasAccessPermission(String user, NamespaceKey key, DatasetConfig datasetConfig) {
  if (!metastoreImpersonationEnabled) {
    return true;
  }

  List<String> path = key.getPathComponents();
  try {
    Table table = null;
    if (path.size() == 3) {
      table = clientsByUser.get(user).getTable(path.get(1), path.get(2), true);
    } else if (path.size() == 2) {
      table = clientsByUser.get(user).getTable("default", path.get(1), true);
    }
    if (table == null) {
      return false;
    }
    if (storageImpersonationEnabled) {
      if (datasetConfig.getReadDefinition() != null && datasetConfig.getReadDefinition().getReadSignature() != null) {
        final HiveReadSignature readSignature = HiveReadSignature.parseFrom(datasetConfig.getReadDefinition().getReadSignature().toByteArray());
        // for now we only support fs based read signatures
        if (readSignature.getType() == HiveReadSignatureType.FILESYSTEM) {
          // get list of partition properties from read definition
          HiveTableXattr tableXattr = HiveTableXattr.parseFrom(datasetConfig.getReadDefinition().getExtendedProperty().toByteArray());
          return hasFSPermission(user, key, readSignature.getFsPartitionUpdateKeysList(), tableXattr.getPartitionPropertiesList());
        }
      }
    }
    return true;
  } catch (TException | ExecutionException | InvalidProtocolBufferException e) {
    throw UserException.dataReadError(e).message("Unable to connect to Hive metastore.").build(logger);
  }
}
项目:seldon-core    文件:JsonFormat.java   
private boolean parseBool(JsonElement json) throws InvalidProtocolBufferException {
  if (json.getAsString().equals("true")) {
    return true;
  }
  if (json.getAsString().equals("false")) {
    return false;
  }
  throw new InvalidProtocolBufferException("Invalid bool value: " + json);
}
项目:iotplatform    文件:TelemetryRpcMsgHandler.java   
private void processSubscriptionCmd(PluginContext ctx, RpcMsg msg) {
  SubscriptionProto proto;
  try {
    proto = SubscriptionProto.parseFrom(msg.getMsgData());
  } catch (InvalidProtocolBufferException e) {
    throw new RuntimeException(e);
  }
  Map<String, Long> statesMap = proto.getKeyStatesList().stream()
      .collect(Collectors.toMap(SubscriptionKetStateProto::getKey, SubscriptionKetStateProto::getTs));
  Subscription subscription = new Subscription(new SubscriptionState(proto.getSessionId(), proto.getSubscriptionId(),
      EntityIdFactory.getByTypeAndId(proto.getEntityType(), proto.getEntityId()),
      SubscriptionType.valueOf(proto.getType()), proto.getAllKeys(), statesMap), false, msg.getServerAddress());
  subscriptionManager.addRemoteWsSubscription(ctx, msg.getServerAddress(), proto.getSessionId(), subscription);
}
项目:ditb    文件:RandomRowFilter.java   
/**
 * @param pbBytes A pb serialized {@link RandomRowFilter} instance
 * @return An instance of {@link RandomRowFilter} made from <code>bytes</code>
 * @throws DeserializationException
 * @see #toByteArray
 */
public static RandomRowFilter parseFrom(final byte [] pbBytes)
throws DeserializationException {
  FilterProtos.RandomRowFilter proto;
  try {
    proto = FilterProtos.RandomRowFilter.parseFrom(pbBytes);
  } catch (InvalidProtocolBufferException e) {
    throw new DeserializationException(e);
  }
  return new RandomRowFilter(proto.getChance());
}
项目:seldon-core    文件:JsonFormatTest.java   
@Test
public void testStrValCustomFormat() throws InvalidProtocolBufferException
{
    final String val = "String Value";
    IntOrString is = IntOrString.newBuilder().setStrVal(val).build();
    Printer jf = JsonFormat.printer().usingTypeConverter(is.getDescriptorForType().getFullName(), new IntOrStringUtils.IntOrStringConverter());
    Assert.assertTrue(jf.print(is).equals("\""+val+"\""));
}
项目:seldon-core    文件:JsonFormat.java   
private void mergeRepeatedField(
    FieldDescriptor field, JsonElement json, Message.Builder builder)
    throws InvalidProtocolBufferException {
  if (!(json instanceof JsonArray)) {
    throw new InvalidProtocolBufferException("Expect an array but found: " + json);
  }
  JsonArray array = (JsonArray) json;
  for (int i = 0; i < array.size(); ++i) {
    Object value = parseFieldValue(field, array.get(i), builder);
    if (value == null) {
      throw new InvalidProtocolBufferException("Repeated field elements cannot be null");
    }
    builder.addRepeatedField(field, value);
  }
}
项目:seldon-core    文件:PredictiveUnitBean.java   
@Async
private Future<Boolean> sendFeedbackAsync(Feedback feedback, PredictiveUnitState state) throws InterruptedException, ExecutionException, InvalidProtocolBufferException{
    System.out.println("NODE " + state.name + ": entered feedback");
    List<PredictiveUnitState> children = new ArrayList<PredictiveUnitState>();
    List<Future<Boolean>> returns = new ArrayList<Future<Boolean>>();

    // Getting the actual implementation (microservice or hardcoded? )
    PredictiveUnitImpl implementation = predictorConfig.getImplementation(state);
    if (implementation == null){ implementation = this; }

    // First we determine children we will send feedback to according to routingDict info
    int routing = feedback.getResponse().getMeta().getRoutingMap().getOrDefault(state.name, -1);

    // TODO: Throw exception if routing is invalid (<-1 or > n_children)
    if (routing == -1){
        children = state.children;
    }
    else if (routing>=0) {
        children.add(state.children.get(routing));
    }

    // First we call sendFeebackAsync on children
    for (PredictiveUnitState child : children){
        returns.add(sendFeedbackAsync(feedback,child));
    }

    // Then we wait for our own feedback
    implementation.doSendFeedback(feedback, state);

    //Then we wait for children feedback
    for (Future<Boolean> ret : returns){
        ret.get();
    }

    // Finally we store the feedback metrics
    doStoreFeedbackMetrics(feedback,state);

    return new AsyncResult<>(true);
}
项目:ditb    文件:NullComparator.java   
/**
 * @param pbBytes A pb serialized {@link NullComparator} instance
 * @return An instance of {@link NullComparator} made from <code>bytes</code>
 * @throws DeserializationException
 * @see #toByteArray
 */
public static NullComparator parseFrom(final byte [] pbBytes)
throws DeserializationException {
  try {
    // Just parse.  Don't use what we parse since on end we are returning new NullComparator.
    ComparatorProtos.NullComparator.parseFrom(pbBytes);
  } catch (InvalidProtocolBufferException e) {
    throw new DeserializationException(e);
  }
  return new NullComparator();
}
项目:ditb    文件:PrefixFilter.java   
/**
 * @param pbBytes A pb serialized {@link PrefixFilter} instance
 * @return An instance of {@link PrefixFilter} made from <code>bytes</code>
 * @throws org.apache.hadoop.hbase.exceptions.DeserializationException
 * @see #toByteArray
 */
public static PrefixFilter parseFrom(final byte [] pbBytes)
throws DeserializationException {
  FilterProtos.PrefixFilter proto;
  try {
    proto = FilterProtos.PrefixFilter.parseFrom(pbBytes);
  } catch (InvalidProtocolBufferException e) {
    throw new DeserializationException(e);
  }
  return new PrefixFilter(proto.hasPrefix()?proto.getPrefix().toByteArray():null);
}
项目:seldon-core    文件:JsonFormat.java   
private void mergeField(FieldDescriptor field, JsonElement json, Message.Builder builder)
    throws InvalidProtocolBufferException {
  if (field.isRepeated()) {
    if (builder.getRepeatedFieldCount(field) > 0) {
      throw new InvalidProtocolBufferException(
          "Field " + field.getFullName() + " has already been set.");
    }
  } else {
    if (builder.hasField(field)) {
      throw new InvalidProtocolBufferException(
          "Field " + field.getFullName() + " has already been set.");
    }
    if (field.getContainingOneof() != null
        && builder.getOneofFieldDescriptor(field.getContainingOneof()) != null) {
      FieldDescriptor other = builder.getOneofFieldDescriptor(field.getContainingOneof());
      throw new InvalidProtocolBufferException(
          "Cannot set field "
              + field.getFullName()
              + " because another field "
              + other.getFullName()
              + " belonging to the same oneof has already been set ");
    }
  }
  if (field.isRepeated() && json instanceof JsonNull) {
    // We allow "null" as value for all field types and treat it as if the
    // field is not present.
    return;
  }
  if (field.isMapField()) {
    mergeMapField(field, json, builder);
  } else if (field.isRepeated()) {
    mergeRepeatedField(field, json, builder);
  } else {
    Object value = parseFieldValue(field, json, builder);
    if (value != null) {
      builder.setField(field, value);
    }
  }
}
项目:ditb    文件:TestUpgradeTo96.java   
private void checkTableState(byte[] data, State expectedState)
    throws InvalidProtocolBufferException {
  ZooKeeperProtos.Table.Builder builder = ZooKeeperProtos.Table.newBuilder();
  int magicLen = ProtobufUtil.lengthOfPBMagic();
  ZooKeeperProtos.Table t = builder.mergeFrom(data, magicLen, data.length - magicLen).build();
  assertTrue(t.getState() == expectedState);
}
项目:ditb    文件:BinaryPrefixComparator.java   
/**
 * @param pbBytes A pb serialized {@link BinaryPrefixComparator} instance
 * @return An instance of {@link BinaryPrefixComparator} made from <code>bytes</code>
 * @throws DeserializationException
 * @see #toByteArray
 */
public static BinaryPrefixComparator parseFrom(final byte [] pbBytes)
throws DeserializationException {
  ComparatorProtos.BinaryPrefixComparator proto;
  try {
    proto = ComparatorProtos.BinaryPrefixComparator.parseFrom(pbBytes);
  } catch (InvalidProtocolBufferException e) {
    throw new DeserializationException(e);
  }
  return new BinaryPrefixComparator(proto.getComparable().getValue().toByteArray());
}