Java Code Examples for com.google.protobuf.InvalidProtocolBufferException

The following examples show how to use com.google.protobuf.InvalidProtocolBufferException. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: google-ads-java   Source File: AbstractErrorUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 2
Source Project: modeldb   Source File: DatasetVersionDAORdbImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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;
    }
  }
}
 
Example 3
Source Project: fdb-record-layer   Source File: RecordCursor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 4
/**
 * 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);
    }
}
 
Example 5
@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));
}
 
Example 6
@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);
  }
}
 
Example 7
Source Project: api-compiler   Source File: TextFormatForTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 8
Source Project: compliance   Source File: ReadsSearchIT.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 9
Source Project: fabric-sdk-java   Source File: EnvelopeDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 10
Source Project: modeldb   Source File: ExperimentRunDAORdbImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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;
    }
  }
}
 
Example 11
Source Project: alcor   Source File: VpcTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 12
Source Project: java-sdk   Source File: TransactionConverter.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 13
Source Project: java-sdk   Source File: TransactionConverter.java    License: Apache License 2.0 6 votes vote down vote up
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;

}
 
Example 14
Source Project: julongchain   Source File: SignedData.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 15
Source Project: modeldb   Source File: ProjectDAORdbImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 16
Source Project: modeldb   Source File: ExperimentDAORdbImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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;
    }
  }
}
 
Example 17
Source Project: grpc-java   Source File: EnvoyServerProtoData.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 18
Source Project: zap-android   Source File: OnChainTransactionDetailBSDFragment.java    License: MIT License 5 votes vote down vote up
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();
    }
}
 
Example 19
Source Project: apicurio-registry   Source File: ProtoUtil.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 20
Source Project: twister2   Source File: JMDriverAgent.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 21
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;
}
 
Example 22
Source Project: curiostack   Source File: TypeSpecificMarshaller.java    License: MIT License 5 votes vote down vote up
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.
}
 
Example 23
Source Project: titus-control-plane   Source File: GrpcClientErrorUtils.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 24
@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());
    }
}
 
Example 25
Source Project: bazel   Source File: MessageLiteCodec.java    License: Apache License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example 26
Source Project: modeldb   Source File: ProjectDAORdbImpl.java    License: Apache License 2.0 5 votes vote down vote up
@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;
    }
  }
}
 
Example 27
Source Project: fabric-sdk-java   Source File: TransactionDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 28
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;
}
 
Example 29
Source Project: swellrt   Source File: AppliedDeltaUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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());
}
 
Example 30
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);
  }
}