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

下面列出了怎么用com.google.protobuf.InvalidProtocolBufferException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: google-ads-java   文件: AbstractErrorUtilsTest.java
@Test
public void getGoogleAdsErrors_duplicates_whenErrorsDiffer()
    throws InvalidProtocolBufferException {
  MockPath path0 =
      MockPath.newBuilder()
          .setIndex(Int64Value.newBuilder().setValue(0))
          .setFieldName(operationsFieldName)
          .build();
  MockPath path1 =
      MockPath.newBuilder()
          .setIndex(Int64Value.newBuilder().setValue(0))
          .setFieldName(operationsFieldName)
          .build();
  MockPath path2 = MockPath.newBuilder().setFieldName("somethingelse").build();
  MockError error0 = MockError.newBuilder().addLocation(path0).build();
  MockError error1 = MockError.newBuilder().addLocation(path1).addLocation(path2).build();
  // Swap the order of the errors.
  MockFailure failure = MockFailure.newBuilder().addErrors(error0).addErrors(error1).build();
  Status status = Status.newBuilder().addDetails(Any.pack(failure)).build();
  List<MockError> result = impl.getGoogleAdsErrors(0, status);
  assertEquals(2, result.size());
  assertEquals(error0, result.get(0));
  assertEquals(error1, result.get(1));
}
 
源代码2 项目: modeldb   文件: DatasetVersionDAORdbImpl.java
@Override
public DatasetVersion addDatasetVersionAttributes(
    String datasetVersionId, List<KeyValue> attributesList)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    DatasetVersionEntity datasetVersionObj =
        session.get(DatasetVersionEntity.class, datasetVersionId);
    datasetVersionObj.setAttributeMapping(
        RdbmsUtils.convertAttributesFromAttributeEntityList(
            datasetVersionObj, ModelDBConstants.ATTRIBUTES, attributesList));
    long currentTimestamp = Calendar.getInstance().getTimeInMillis();
    datasetVersionObj.setTime_updated(currentTimestamp);
    Transaction transaction = session.beginTransaction();
    session.saveOrUpdate(datasetVersionObj);
    transaction.commit();
    LOGGER.debug("DatasetVersion attributes added successfully");
    return datasetVersionObj.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return addDatasetVersionAttributes(datasetVersionId, attributesList);
    } else {
      throw ex;
    }
  }
}
 
源代码3 项目: fdb-record-layer   文件: RecordCursor.java
/**
 * Resume a nested cursor with the given continuation or start if <code>null</code>.
 * @param outerFunc a function that takes the outer continuation and returns the outer cursor.
 * @param innerFunc a function that takes an outer record and an inner continuation and returns the inner cursor.
 * @param checker a function that takes an outer record and returns a way of recognizing it again or <code>null</code>.
 * When computing the continuation, this is called on the current outer record and the result, if not <code>null</code>,
 * becomes part of the continuation. When this continuation is used, the function (presumably the same one) is called
 * on the outer record again. If the results match, the inner cursor picks up where it left off. If not, the entire
 * inner cursor is run.
 * This handles common cases of the data changing between transactions, such as the outer record being deleted (skip rest of inner record)
 * or a new record being inserted right before it (do full inner cursor, not partial based on previous).
 * @param continuation the continuation returned from a previous instance of this pipeline or <code>null</code> at start.
 * @param pipelineSize the number of outer items to work ahead; inner cursors for these will be started in parallel.
 * @param <T> the result type of the outer cursor
 * @param <V> the result type of the inner cursor produced by the mapping function
 * @return a {@link FlatMapPipelinedCursor} that maps the inner function across the results of the outer function
 */
@Nonnull
static <T, V> RecordCursor<V> flatMapPipelined(@Nonnull Function<byte[], ? extends RecordCursor<T>> outerFunc,
                                                      @Nonnull BiFunction<T, byte[], ? extends RecordCursor<V>> innerFunc,
                                                      @Nullable Function<T, byte[]> checker,
                                                      @Nullable byte[] continuation,
                                                      int pipelineSize) {
    if (continuation == null) {
        return new FlatMapPipelinedCursor<>(outerFunc.apply(null), innerFunc, checker,
                null, null, null,
                pipelineSize);
    }
    RecordCursorProto.FlatMapContinuation parsed;
    try {
        parsed = RecordCursorProto.FlatMapContinuation.parseFrom(continuation);
    } catch (InvalidProtocolBufferException ex) {
        throw new RecordCoreException("error parsing continuation", ex)
                .addLogInfo("raw_bytes", ByteArrayUtil2.loggable(continuation));
    }
    final byte[] outerContinuation = parsed.hasOuterContinuation() ? parsed.getOuterContinuation().toByteArray() : null;
    final byte[] innerContinuation = parsed.hasInnerContinuation() ? parsed.getInnerContinuation().toByteArray() : null;
    final byte[] checkValue = parsed.hasCheckValue() ? parsed.getCheckValue().toByteArray() : null;
    final RecordCursor<T> outerCursor = outerFunc.apply(outerContinuation);
    return new FlatMapPipelinedCursor<>(outerCursor, innerFunc, checker, outerContinuation, checkValue, innerContinuation, pipelineSize);
}
 
源代码4 项目: grpc-java-contrib   文件: MoreMetadata.java
/**
 * A metadata marshaller that encodes objects as protobuf according to their proto IDL specification.
 *
 * @param clazz the type to serialize
 * @param <T>
 */
public static <T extends GeneratedMessageV3> Metadata.BinaryMarshaller<T> PROTOBUF_MARSHALLER(Class<T> clazz) {
    try {
        Method defaultInstance = clazz.getMethod("getDefaultInstance");
        GeneratedMessageV3 instance = (GeneratedMessageV3) defaultInstance.invoke(null);

        return new Metadata.BinaryMarshaller<T>() {
            @Override
            public byte[] toBytes(T value) {
                return value.toByteArray();
            }

            @SuppressWarnings("unchecked")
            @Override
            public T parseBytes(byte[] serialized) {
                try {
                    return (T) instance.getParserForType().parseFrom(serialized);
                } catch (InvalidProtocolBufferException ipbe) {
                    throw new IllegalArgumentException(ipbe);
                }
            }
        };
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
        throw new IllegalStateException(ex);
    }
}
 
源代码5 项目: distkv   文件: ParseSetCommandTest.java
@Test
public void testSetPut() throws InvalidProtocolBufferException {
  final String command = "set.put k1 v1 v2 v3 v4";
  DistkvParsedResult result = distkvParser.parse(command);
  final DistkvRequest request = result.getRequest();
  Assert.assertEquals(DistkvRequest.class, request.getClass());
  Assert.assertEquals("k1", request.getKey());
  Assert.assertEquals(4, request.getRequest()
      .unpack(SetPutRequest.class).getValuesCount());
  Assert.assertEquals("v1", request.getRequest()
      .unpack(SetPutRequest.class).getValues(0));
  Assert.assertEquals("v2", request.getRequest()
      .unpack(SetPutRequest.class).getValues(1));
  Assert.assertEquals("v3", request.getRequest()
      .unpack(SetPutRequest.class).getValues(2));
  Assert.assertEquals("v4", request.getRequest()
      .unpack(SetPutRequest.class).getValues(3));
}
 
@Override
public @NonNull Map<Integer, AuthCredentialResponse> read() {
  byte[] credentialBlob = store.getBlob(KEY, null);

  if (credentialBlob == null) {
    Log.i(TAG, "No credentials responses are cached locally");
    return Collections.emptyMap();
  }

  try {
    TemporalAuthCredentialResponses          temporalCredentials = TemporalAuthCredentialResponses.parseFrom(credentialBlob);
    HashMap<Integer, AuthCredentialResponse> result              = new HashMap<>(temporalCredentials.getCredentialResponseCount());

    for (TemporalAuthCredentialResponse credential : temporalCredentials.getCredentialResponseList()) {
      result.put(credential.getDate(), new AuthCredentialResponse(credential.getAuthCredentialResponse().toByteArray()));
    }

    Log.i(TAG, String.format(Locale.US, "Loaded %d credentials from local storage", result.size()));

    return result;
  } catch (InvalidProtocolBufferException | InvalidInputException e) {
    throw new AssertionError(e);
  }
}
 
源代码7 项目: api-compiler   文件: TextFormatForTest.java
/**
 * Attempt to unpack if its an any instance. Returns null if not unpacked.
 */
@Nullable private Message maybeUnpackAnyType(FieldDescriptor field, Object value) {
  if (field.getType() == FieldDescriptor.Type.MESSAGE
      && field.getMessageType().getFullName().equals(Any.getDescriptor().getFullName())) {
    Any any = (Any) value;
    Message defaultInstance = anyConverterRegistry.get(any.getTypeUrl());
    if (defaultInstance != null) {
      try {
        return defaultInstance.toBuilder().mergeFrom(any.getValue()).build();
      } catch (InvalidProtocolBufferException e) {
        throw new RuntimeException(e);
      }
    }
  }
  return null;
}
 
源代码8 项目: compliance   文件: ReadsSearchIT.java
/**
 * Call <tt>/reads/search</tt> with a range that contains zero reads, and verify that it returns none.
 * (Adapted from an old JavaScript test.)
 *
 * @throws GAWrapperException if the server finds the request invalid in some way
 * @throws UnirestException if there's a problem speaking HTTP to the server
 * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server
 */
@Test
public void searchRangeWithNoReadsReturnsZeroResults() throws InvalidProtocolBufferException, UnirestException, GAWrapperException {
    final String refId = Utils.getValidReferenceId(client);

    final long emptyRangeStart = 0; // is this range actually empty?
    final long emptyRangeEnd = 100;

    final SearchReadsRequest srReq =
            SearchReadsRequest.newBuilder()
                    .setReferenceId(refId)
                    .addAllReadGroupIds(aSingle(getReadGroupId(client)))
                    .setStart(emptyRangeStart)
                    .setEnd(emptyRangeEnd)
                    .build();
    final SearchReadsResponse srResp = client.reads.searchReads(srReq);

    final List<ReadAlignment> alignments = srResp.getAlignmentsList();
    assertThat(alignments).isEmpty();
}
 
源代码9 项目: fabric-sdk-java   文件: EnvelopeDeserializer.java
static EnvelopeDeserializer newInstance(ByteString byteString, byte b) throws InvalidProtocolBufferException {
    EnvelopeDeserializer ret;
    final int type = ChannelHeader.parseFrom(Payload.parseFrom(Envelope.parseFrom(byteString).getPayload())
            .getHeader().getChannelHeader()).getType();
   /*
MESSAGE = 0;                   // Used for messages which are signed but opaque
CONFIG = 1;                    // Used for messages which express the channel config
CONFIG_UPDATE = 2;             // Used for transactions which update the channel config
ENDORSER_TRANSACTION = 3;      // Used by the SDK to submit endorser based transactions
ORDERER_TRANSACTION = 4;       // Used internally by the orderer for management
DELIVER_SEEK_INFO = 5;         // Used as the type for Envelope messages submitted to instruct the Deliver API to seek
CHAINCODE_PACKAGE = 6;         // Used for packaging chaincode artifacts for install
 */

    switch (type) {
        case 3:
            ret = new EndorserTransactionEnvDeserializer(byteString, b);
            break;
        default: //just assume base properties.
            ret = new EnvelopeDeserializer(byteString, b);
            break;
    }
    return ret;
}
 
源代码10 项目: modeldb   文件: ExperimentRunDAORdbImpl.java
@Override
public List<String> getExperimentRunIdsByProjectIds(List<String> projectIds)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query experimentRunQuery = session.createQuery(GET_EXPERIMENT_RUN_BY_PROJECT_ID_HQL);
    experimentRunQuery.setParameterList("projectIds", projectIds);
    List<ExperimentRunEntity> experimentRunEntities = experimentRunQuery.list();

    List<String> experimentRunIds = new ArrayList<>();
    for (ExperimentRunEntity experimentRunEntity : experimentRunEntities) {
      experimentRunIds.add(experimentRunEntity.getId());
    }
    return experimentRunIds;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getExperimentRunIdsByProjectIds(projectIds);
    } else {
      throw ex;
    }
  }
}
 
源代码11 项目: alcor   文件: VpcTest.java
@Test
public void serializationVerificationWithTransitRouterIps() {
    VpcState customerVpcState =
            new VpcState("dbf72700-5106-4a7a-918f-a016853911f8",
                    "99d9d709-8478-4b46-9f3f-2206b1023fd3",
                    "SuperVpc",
                    "10.0.0.0/24");
    HostInfo[] transitRouterHosts = {
            new HostInfo(OneBoxConfig.TRANSIT_ROUTER_1_HOST_ID, "transit router host1", OneBoxConfig.TRANSIT_ROUTER_1_IP, OneBoxConfig.TRANSIT_ROUTER_1_MAC),
            new HostInfo(OneBoxConfig.TRANSIT_ROUTER_2_HOST_ID, "transit router host2", OneBoxConfig.TRANSIT_ROUTER_2_IP, OneBoxConfig.TRANSIT_ROUTER_2_MAC)
    };

    final Vpc.VpcState state = GoalStateUtil.CreateGSVpcState(Common.OperationType.CREATE,
            customerVpcState,
            transitRouterHosts);

    final byte[] binaryState = state.toByteArray();

    try {
        final Vpc.VpcState deserializedObject = Vpc.VpcState.parseFrom(binaryState);

        TestUtil.AssertVpcStates(state, deserializedObject);
    } catch (InvalidProtocolBufferException bf_exp) {
        Assert.assertTrue(false);
    }
}
 
源代码12 项目: java-sdk   文件: TransactionConverter.java
private Transaction convertTimeLock(byte[] value) throws InvalidProtocolBufferException {
    byte[] array = new byte[value.length - 4];
    System.arraycopy(value, 4, array, 0, array.length);
    TimeLock timeLock = TimeLock.parseFrom(array);
    com.binance.dex.api.client.domain.broadcast.TimeLock tl = new com.binance.dex.api.client.domain.broadcast.TimeLock();
    tl.setFromAddr(Crypto.encodeAddress(hrp, timeLock.getFrom().toByteArray()));
    tl.setDescription(timeLock.getDescription());
    tl.setLockTime(Date.from(Instant.ofEpochSecond(timeLock.getLockTime())));
    List<Token> amount = timeLock.getAmountList().stream().map(token -> {
        Token msgToken = new Token();
        msgToken.setAmount(token.getAmount());
        msgToken.setDenom(token.getDenom());
        return msgToken;
    }).collect(Collectors.toList());
    tl.setAmount(amount);
    Transaction transaction = new Transaction();
    transaction.setTxType(TxType.TimeLock);
    transaction.setRealTx(tl);
    return transaction;
}
 
源代码13 项目: java-sdk   文件: TransactionConverter.java
private Transaction convertListing(byte[] value) throws InvalidProtocolBufferException {
    byte[] array = new byte[value.length - 4];
    System.arraycopy(value, 4, array, 0, array.length);
    com.binance.dex.api.proto.List listMessage = com.binance.dex.api.proto.List.parseFrom(array);

    Listing listing = new Listing();
    listing.setProposalId(listMessage.getProposalId());
    listing.setBaseAssetSymbol(listMessage.getBaseAssetSymbol());
    listing.setQuoteAssetSymbol(listMessage.getQuoteAssetSymbol());
    listing.setInitPrice(listMessage.getInitPrice());
    listing.setFromAddr(Crypto.encodeAddress(hrp, listMessage.getFrom().toByteArray()));

    Transaction transaction = new Transaction();
    transaction.setTxType(TxType.LISTING);
    transaction.setRealTx(listing);
    return transaction;

}
 
源代码14 项目: julongchain   文件: SignedData.java
public static List<SignedData> asSignedData(ProposalPackage.SignedProposal signedProposal) throws ValidateException,
        InvalidProtocolBufferException {
    ValidateUtils.isNotNull(signedProposal, "signedProposal can not be null");
    ValidateUtils.isNotNull(signedProposal.getProposalBytes(), "proposal can not be null");

    List<SignedData> result = new ArrayList<>();

    ProposalPackage.Proposal proposal = ProposalPackage.Proposal.parseFrom(signedProposal.getProposalBytes());
    Common.Header header = Common.Header.parseFrom(proposal.getHeader());
    Common.SignatureHeader signatureHeader = Common.SignatureHeader.parseFrom(header.getSignatureHeader());

    SignedData signedData = new SignedData(signedProposal.getProposalBytes().toByteArray(),
            signatureHeader.getCreator().toByteArray(), signedProposal.getSignature().toByteArray());
    result.add(signedData);

    return result;
}
 
源代码15 项目: modeldb   文件: ProjectDAORdbImpl.java
@Override
public List<Project> getProjects(String key, String value, UserInfo userInfo)
    throws InvalidProtocolBufferException {
  FindProjects findProjects =
      FindProjects.newBuilder()
          .addPredicates(
              KeyValueQuery.newBuilder()
                  .setKey(key)
                  .setValue(Value.newBuilder().setStringValue(value).build())
                  .setOperator(OperatorEnum.Operator.EQ)
                  .setValueType(ValueTypeEnum.ValueType.STRING)
                  .build())
          .build();
  ProjectPaginationDTO projectPaginationDTO =
      findProjects(findProjects, null, userInfo, ProjectVisibility.PRIVATE);
  LOGGER.debug("Projects size is {}", projectPaginationDTO.getProjects().size());
  return projectPaginationDTO.getProjects();
}
 
源代码16 项目: modeldb   文件: ExperimentDAORdbImpl.java
@Override
public Experiment updateExperimentDescription(String experimentId, String experimentDescription)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    ExperimentEntity experimentEntity = session.load(ExperimentEntity.class, experimentId);
    experimentEntity.setDescription(experimentDescription);
    long currentTimestamp = Calendar.getInstance().getTimeInMillis();
    experimentEntity.setDate_updated(currentTimestamp);
    Transaction transaction = session.beginTransaction();
    session.update(experimentEntity);
    transaction.commit();
    LOGGER.debug("Experiment description updated successfully");
    return experimentEntity.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return updateExperimentDescription(experimentId, experimentDescription);
    } else {
      throw ex;
    }
  }
}
 
源代码17 项目: grpc-java   文件: EnvoyServerProtoData.java
static Listener fromEnvoyProtoListener(io.envoyproxy.envoy.api.v2.Listener proto)
    throws InvalidProtocolBufferException {
  List<FilterChain> filterChains = new ArrayList<>(proto.getFilterChainsCount());
  for (io.envoyproxy.envoy.api.v2.listener.FilterChain filterChain :
      proto.getFilterChainsList()) {
    filterChains.add(FilterChain.fromEnvoyProtoFilterChain(filterChain));
  }
  return new Listener(
      proto.getName(),
      convertEnvoyAddressToString(proto.getAddress()),
      filterChains);
}
 
private void bindOnChainTransaction(ByteString transactionString) throws InvalidProtocolBufferException {
    mTransaction = Transaction.parseFrom(transactionString);

    String channelLabel = getString(R.string.channel) + ":";
    mChannelLabel.setText(channelLabel);
    String eventLabel = getString(R.string.event) + ":";
    mEventLabel.setText(eventLabel);
    String amountLabel = getString(R.string.amount) + ":";
    mAmountLabel.setText(amountLabel);
    String feeLabel = getString(R.string.fee) + ":";
    mFeeLabel.setText(feeLabel);
    String dateLabel = getString(R.string.date) + ":";
    mDateLabel.setText(dateLabel);
    String transactionIDLabel = getString(R.string.transactionID) + ":";
    mTransactionIDLabel.setText(transactionIDLabel);
    String addressLabel = getString(R.string.address) + ":";
    mAddressLabel.setText(addressLabel);

    mDate.setText(TimeFormatUtil.formatTimeAndDateLong(mTransaction.getTimeStamp(), getActivity()));

    mAddress.setText(mTransaction.getDestAddresses(0));
    mTransactionID.setText(mTransaction.getTxHash());

    mTransactionID.setOnClickListener(view -> new BlockExplorer().showTransaction(mTransaction.getTxHash(), getActivity()));
    mAddress.setOnClickListener(view -> new BlockExplorer().showAddress(mTransaction.getDestAddresses(0), getActivity()));
    mTransactionIDCopyButton.setOnClickListener(view -> ClipBoardUtil.copyToClipboard(getContext(), "TransactionID", mTransaction.getTxHash()));
    mAddressCopyButton.setOnClickListener(view -> ClipBoardUtil.copyToClipboard(getContext(), "Address", mTransaction.getDestAddresses(0)));

    // is internal?
    if (Wallet.getInstance().isTransactionInternal(mTransaction)) {
        bindInternal();
    } else {
        bindNormalTransaction();
    }
}
 
源代码19 项目: apicurio-registry   文件: ProtoUtil.java
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);
}
 
源代码20 项目: twister2   文件: JMDriverAgent.java
/**
 * deliver the received message to IReceiverFromDriver
 */
private void deliverMessageToReceiver(JobMasterAPI.DriverMessage message) {

  try {
    Any any = Any.parseFrom(message.getData());
    receiverFromDriver.driverMessageReceived(any);
  } catch (InvalidProtocolBufferException e) {
    LOG.log(Level.SEVERE, "Can not parse received protocol buffer message to Any", e);
  }
}
 
ProposalResponsePackage.ProposalResponsePayload getProposalResponsePayload() {
    ProposalResponsePackage.ProposalResponsePayload ret = proposalResponsePayload != null ? proposalResponsePayload.get() : null;

    if (null == ret) {
        try {
            ret = ProposalResponsePackage.ProposalResponsePayload.parseFrom(byteString);
        } catch (InvalidProtocolBufferException e) {
            throw new InvalidProtocolBufferRuntimeException(e);
        }

        proposalResponsePayload = new WeakReference<>(ret);
    }

    return ret;
}
 
源代码22 项目: curiostack   文件: TypeSpecificMarshaller.java
void mergeValue(JsonParser parser, int currentDepth, Message.Builder builder) throws IOException {
  ParseSupport.checkRecursionLimit(currentDepth);
  JsonToken json = parser.currentToken();
  if (json == null) {
    // Nested messages will already have current token set, but top-level ones will not.
    json = parser.nextToken();
  }
  if (json != JsonToken.START_OBJECT) {
    throw new InvalidProtocolBufferException(
        "Expected start of object, got: " + parser.getText());
  }
  doMerge(parser, currentDepth, builder);
  // Object end will be handled in ParseSupport.checkObjectEnd.
}
 
源代码23 项目: titus-control-plane   文件: GrpcClientErrorUtils.java
public static Status getStatus(StatusRuntimeException error) {
    if (error.getTrailers() == null) {
        return Status.newBuilder().setCode(-1).setMessage(error.getMessage()).build();
    }
    try {
        byte[] data = error.getTrailers().get(KEY_TITUS_ERROR_REPORT_BIN);
        if (data == null) {
            return Status.newBuilder().setCode(-1).setMessage(error.getMessage()).build();
        }
        return Status.parseFrom(data);
    } catch (InvalidProtocolBufferException e) {
        logger.error("Something went wrong with status parsing", e);
        throw new IllegalArgumentException(e);
    }
}
 
@Nonnull
protected DynamicMessage deserializeFromBytes(@Nonnull Descriptors.Descriptor storedDescriptor,
                                              @Nonnull byte[] serialized) {
    try {
        return DynamicMessage.parseFrom(storedDescriptor, serialized);
    } catch (InvalidProtocolBufferException ex) {
        throw new RecordSerializationException("Error reading from byte array", ex)
                .addLogInfo("recordType", storedDescriptor.getName());
    }
}
 
源代码25 项目: bazel   文件: MessageLiteCodec.java
@Override
public MessageLite deserialize(DeserializationContext unusedContext, CodedInputStream codedIn)
    throws IOException, SerializationException {
  // Don't hold on to full byte array when constructing this proto.
  codedIn.enableAliasing(false);
  try {
    MessageLite.Builder builder = builderSupplier.get();
    codedIn.readMessage(builder, ExtensionRegistryLite.getEmptyRegistry());
    return builder.build();
  } catch (InvalidProtocolBufferException e) {
    throw new SerializationException("Failed to parse proto of type " + type, e);
  } finally {
    codedIn.enableAliasing(true);
  }
}
 
源代码26 项目: modeldb   文件: ProjectDAORdbImpl.java
@Override
public Project setProjectWorkspace(String projectId, WorkspaceDTO workspaceDTO)
    throws InvalidProtocolBufferException {

  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    ProjectEntity projectEntity = session.load(ProjectEntity.class, projectId);
    List<String> roleBindingNames =
        getWorkspaceRoleBindings(
            projectEntity.getWorkspace(),
            WorkspaceType.forNumber(projectEntity.getWorkspace_type()),
            projectId,
            ProjectVisibility.forNumber(projectEntity.getProject_visibility()));
    roleService.deleteRoleBindings(roleBindingNames);
    createWorkspaceRoleBinding(
        workspaceDTO.getWorkspaceId(),
        workspaceDTO.getWorkspaceType(),
        projectId,
        ProjectVisibility.forNumber(projectEntity.getProject_visibility()));
    projectEntity.setWorkspace(workspaceDTO.getWorkspaceId());
    projectEntity.setWorkspace_type(workspaceDTO.getWorkspaceType().getNumber());
    projectEntity.setDate_updated(Calendar.getInstance().getTimeInMillis());
    Transaction transaction = session.beginTransaction();
    session.update(projectEntity);
    transaction.commit();
    LOGGER.debug("Project workspace updated successfully");
    return projectEntity.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return setProjectWorkspace(projectId, workspaceDTO);
    } else {
      throw ex;
    }
  }
}
 
源代码27 项目: fabric-sdk-java   文件: TransactionDeserializer.java
TransactionPackage.Transaction getTransaction() {
    TransactionPackage.Transaction ret = transaction != null ? transaction.get() : null;

    if (null == ret) {
        try {
            ret = TransactionPackage.Transaction.parseFrom(byteString);
        } catch (InvalidProtocolBufferException e) {
            throw new InvalidProtocolBufferRuntimeException(e);
        }

        transaction = new WeakReference<>(ret);
    }

    return ret;
}
 
源代码28 项目: distkv   文件: CommandExecutorHandler.java
public static String setPut(DistkvClient distkvClient, DistkvParsedResult parsedResult) {
  try {
    DistkvRequest request = parsedResult.getRequest();
    SetPutRequest setPutRequest = request.getRequest().unpack(SetPutRequest.class);
    distkvClient.sets().put(request.getKey(), new HashSet<>(setPutRequest.getValuesList()));
  } catch (InvalidProtocolBufferException e) {
    throw new DistkvException(e.toString());
  }

  return STATUS_OK;
}
 
源代码29 项目: swellrt   文件: AppliedDeltaUtil.java
/**
 * Inspects the given applied delta to determine the {@code HashedVersion} it
 * was applied at.
 * This may require looking at the contained {@code ProtocolWaveletDelta}.
 *
 * @param appliedDeltaBytes to inspect
 * @return hashed version the delta was applied at
 * @throws InvalidProtocolBufferException if the contained
 *         {@code ProtocolWaveletDelta} is invalid
 *         (is only inspected if the applied delta has the hashed version set)
 */
public static HashedVersion getHashedVersionAppliedAt(
    ByteStringMessage<ProtocolAppliedWaveletDelta> appliedDeltaBytes)
    throws InvalidProtocolBufferException {
  ProtocolAppliedWaveletDelta appliedDelta = appliedDeltaBytes.getMessage();
  return CoreWaveletOperationSerializer.deserialize(
      // If the delta was transformed, the version it was actually applied at is specified
      // in the top-level message, otherwise we take if from the original signed delta.
      appliedDelta.hasHashedVersionAppliedAt()
      ? appliedDelta.getHashedVersionAppliedAt()
      : ProtocolWaveletDelta.parseFrom(appliedDelta.getSignedOriginalDelta().getDelta())
            .getHashedVersion());
}
 
源代码30 项目: distkv   文件: PineTopperImpl.java
public List<DistkvTuple<String, Integer>> top(int num) {
  try {
    LinkedList<SlistEntity> result = distkvClient.slists().top(getKey(), num);
    // Covert the result type.
    List<DistkvTuple<String, Integer>> ret = new ArrayList<>(result.size());
    for (SlistEntity entity : result) {
      ret.add(new DistkvTuple<>(entity.getMember(), entity.getScore()));
    }
    return ret;
  } catch (InvalidProtocolBufferException e) {
    // TODO(qwang): Refine this exception.
    throw new RuntimeException(e);
  }
}
 
 类所在包
 同包方法