Java Code Examples for com.google.common.base.Preconditions#checkElementIndex()

The following examples show how to use com.google.common.base.Preconditions#checkElementIndex() . 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 check out the related API usage on the sidebar.
Example 1
Source File: VoteConfirmationAuthorityAlgorithms.java    From chvote-protocol-poc with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Algorithm 7.37: GetFinalization
 *
 * @param i            the voter index
 * @param upper_bold_p the point matrix, one point per voter per candidate
 * @param upper_b      the current ballot list
 * @return this authority's part of the finalization code
 */
public FinalizationCodePart getFinalization(Integer i, List<List<Point>> upper_bold_p, Collection<BallotEntry> upper_b) {
    BigInteger p_prime = publicParameters.getPrimeField().getP_prime();
    Preconditions.checkArgument(upper_bold_p.stream().flatMap(Collection::stream)
                    .allMatch(point -> BigInteger.ZERO.compareTo(point.x) <= 0 &&
                            point.x.compareTo(p_prime) < 0 &&
                            BigInteger.ZERO.compareTo(point.y) <= 0 &&
                            point.y.compareTo(p_prime) < 0),
            "All points' coordinates must be in Z_p_prime");
    Preconditions.checkElementIndex(i, upper_bold_p.size());

    Object[] bold_p_i = upper_bold_p.get(i).toArray();
    byte[] upper_f_i = ByteArrayUtils.truncate(hash.recHash_L(bold_p_i), publicParameters.getUpper_l_f());

    BallotEntry ballotEntry = upper_b.stream().filter(b -> Objects.equals(b.getI(), i)).findFirst().orElseThrow(
            () -> new BallotNotFoundRuntimeException(String.format("Couldn't find any ballot for voter %d", i))
    );

    return new FinalizationCodePart(upper_f_i, ballotEntry.getBold_r());
}
 
Example 2
Source File: DefaultBulletinBoard.java    From chvote-protocol-poc with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<Encryption> getPreviousShuffle(int j) {
    Preconditions.checkElementIndex(j, publicParameters.getS(),
            "j needs to be within bounds");
    Preconditions.checkArgument(shuffles.containsKey(j),
            "Can't retrieve a shuffle that hasn't been inserted");
    return shuffles.get(j);
}
 
Example 3
Source File: Pow2BitArray.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the entry at the given index
 */
public int get(int index) {
    Preconditions.checkElementIndex(index, this.size);
    int bitIndex = index * this.version.bits;
    int arrayIndex = bitIndex >> 5;
    int wordOffset = bitIndex & 31;
    return this.words[arrayIndex] >>> wordOffset & this.version.maxEntryValue;
}
 
Example 4
Source File: PaddedBitArray.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int get(int index) {
    Preconditions.checkElementIndex(index, this.size);
    int arrayIndex = index / this.version.entriesPerWord;
    int offset = (index % this.version.entriesPerWord) * this.version.bits;

    return (this.words[arrayIndex] >>> offset) & this.version.maxEntryValue;
}
 
Example 5
Source File: PaddedBitArray.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void set(int index, int value) {
    Preconditions.checkElementIndex(index, this.size);
    Preconditions.checkArgument(value >= 0 && value <= this.version.maxEntryValue,
            "Max value: %s. Received value", this.version.maxEntryValue, value);
    int arrayIndex = index / this.version.entriesPerWord;
    int offset = (index % this.version.entriesPerWord) * this.version.bits;

    this.words[arrayIndex] = this.words[arrayIndex] & ~(this.version.maxEntryValue << offset) | (value & this.version.maxEntryValue) << offset;
}
 
Example 6
Source File: NibbleArray.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public void set(int index, byte value) {
    Preconditions.checkArgument(value >= 0 && value < 16, "Nibbles must have a value between 0 and 15.");
    Preconditions.checkElementIndex(index, data.length * 2);
    value &= 0xf;
    int half = index / 2;
    byte previous = data[half];
    if ((index & 1) == 0) {
        data[half] = (byte) (previous & 0xf0 | value);
    } else {
        data[half] = (byte) (previous & 0x0f | value << 4);
    }
}
 
Example 7
Source File: NibbleArray.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public byte get(int index) {
    Preconditions.checkElementIndex(index, data.length * 2);
    byte val = data[index / 2];
    if ((index & 1) == 0) {
        return (byte) (val & 0x0f);
    } else {
        return (byte) ((val & 0xf0) >>> 4);
    }
}
 
Example 8
Source File: DecryptionAuthorityAlgorithms.java    From chvote-protocol-poc with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Algorithms 7.47: checkShuffleProofs
 *
 * @param bold_pi   the shuffle proofs generated by the authorities
 * @param e_0       the original encryption
 * @param bold_E    the vector of the re-encryption lists, per authority
 * @param publicKey the public key
 * @param j         the index of this authority
 * @return true if all the proofs generated by the other authorities are valid, false otherwise
 */
public boolean checkShuffleProofs(List<ShuffleProof> bold_pi, List<Encryption> e_0,
                                  List<List<Encryption>> bold_E, EncryptionPublicKey publicKey, int j) {
    int s = publicParameters.getS();
    int N = e_0.size();
    Preconditions.checkArgument(bold_pi.size() == s,
            "there should be as many proofs as there are authorities");
    Preconditions.checkArgument(bold_E.size() == s,
            "there should be as many lists of re-encryptions as there are authorities");
    Preconditions.checkArgument(bold_E.stream().map(List::size).allMatch(l -> l == N),
            "every re-encryption list should have length N");
    Preconditions.checkElementIndex(j, s,
            "The index of the authority should be valid with respect to the number of authorities");

    // insert e_0 at index 0, thus offsetting all indices for bold_E by 1
    List<List<Encryption>> tmp_bold_e = new ArrayList<>();
    tmp_bold_e.add(0, e_0);
    tmp_bold_e.addAll(bold_E);
    for (int i = 0; i < s; i++) {
        if (i != j) {
            if (!checkShuffleProof(
                    bold_pi.get(i), tmp_bold_e.get(i), tmp_bold_e.get(i + 1), publicKey)) {
                return false;
            }
        }
    }
    return true;
}
 
Example 9
Source File: VoteCastingAuthorityAlgorithms.java    From chvote-protocol-poc with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Algorithm 7.22: CheckBallot
 *
 * @param i          the voter index
 * @param alpha      the submitted ballot, including the oblivious transfer query
 * @param pk         the encryption public key
 * @param bold_x_hat the vector of public voter credentials
 * @param upper_b    the current ballot list
 * @return true if the ballot was valid
 */
public boolean checkBallot(Integer i, BallotAndQuery alpha, EncryptionPublicKey pk,
                           List<BigInteger> bold_x_hat, Collection<BallotEntry> upper_b) {
    Preconditions.checkNotNull(i);
    Preconditions.checkNotNull(alpha);
    List<BigInteger> bold_a = alpha.getBold_a();
    Preconditions.checkNotNull(bold_a);
    Preconditions.checkArgument(bold_a.stream().allMatch(generalAlgorithms::isMember),
            "All of the a_j's must be members of G_q");
    Preconditions.checkArgument(generalAlgorithms.isMember(alpha.getB()),
            "b must be a member of G_q");

    int numberOfSelections = bold_a.size();
    Preconditions.checkArgument(numberOfSelections > 0);
    Voter voter = electionSet.getVoters().get(i);
    int k_i = electionSet.getElections().stream().filter(e -> electionSet.isEligible(voter, e))
            .mapToInt(Election::getNumberOfSelections).sum();
    Preconditions.checkArgument(numberOfSelections == k_i,
            "A voter may not submit more than his allowed number of selections");
    Preconditions.checkNotNull(pk);
    Preconditions.checkNotNull(bold_x_hat);
    Preconditions.checkElementIndex(i, bold_x_hat.size());
    Preconditions.checkNotNull(upper_b);

    BigInteger p = publicParameters.getEncryptionGroup().getP();
    BigInteger x_hat_i = bold_x_hat.get(i);
    if (!hasBallot(i, upper_b) && alpha.getX_hat().compareTo(x_hat_i) == 0) {
        BigInteger a = bold_a.stream().reduce(BigInteger::multiply)
                .orElse(ONE)
                .mod(p);
        return checkBallotProof(alpha.getPi(), alpha.getX_hat(), a, alpha.getB(), pk);
    }
    return false;
}
 
Example 10
Source File: DefaultBulletinBoard.java    From chvote-protocol-poc with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void publishPartialDecryptionAndProof(int j, List<BigInteger> partialDecryption, DecryptionProof proof) {
    Preconditions.checkElementIndex(j, publicParameters.getS(),
            "j needs to be within bounds");
    Preconditions.checkState(shuffles.size() == publicParameters.getS(),
            "The decryptions may only start when all the shuffles have been published");
    Preconditions.checkState(shuffleProofs.size() == publicParameters.getS(),
            "The decryptions may only start when all the shuffles proofs have been published");
    Preconditions.checkArgument(!partialDecryptions.containsKey(j),
            "Partial decryptions may not be updated");
    Preconditions.checkArgument(!decryptionProofs.containsKey(j),
            "Partial decryptions proofs may not be updated");
    partialDecryptions.put(j, partialDecryption);
    decryptionProofs.put(j, proof);
}
 
Example 11
Source File: DefaultBulletinBoard.java    From chvote-protocol-poc with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void publishPublicCredentials(int j, List<Point> publicCredentials) {
    Preconditions.checkState(publicParameters != null,
            "The public parameters need to have been defined first");
    Preconditions.checkElementIndex(j, publicParameters.getS(),
            "The index j should be lower than the number of authorities");
    publicCredentialsParts.put(j, publicCredentials);
}
 
Example 12
Source File: DefaultBulletinBoard.java    From chvote-protocol-poc with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void publishKeyPart(int j, EncryptionPublicKey publicKey) {
    Preconditions.checkState(publicParameters != null,
            "The public parameters need to have been defined first");
    Preconditions.checkElementIndex(j, publicParameters.getS(),
            "The index j should be lower than the number of authorities");
    publicKeyParts.put(j, publicKey);
}
 
Example 13
Source File: InstanceGroupScenarioBuilder.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public InstanceGroupScenarioBuilder any(Consumer<InstanceScenarioBuilder> transformer) {
    checkIsKnown();
    ArrayList<AgentInstance> instancesList = new ArrayList<>(instances.values());
    Preconditions.checkElementIndex(0, instancesList.size(), "At least one agent instance available");
    Collections.shuffle(instancesList);
    transformer.accept(new InstanceScenarioBuilder(titusStackResource, instancesList.get(0)));
    return this;
}
 
Example 14
Source File: InstanceGroupScenarioBuilder.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public InstanceGroupScenarioBuilder all(Consumer<InstanceScenarioBuilder> transformer) {
    checkIsKnown();
    Preconditions.checkElementIndex(0, instances.values().size(), "At least one agent instance available");
    instances.values().forEach(instance ->
            transformer.accept(new InstanceScenarioBuilder(titusStackResource, instance))
    );
    return this;
}
 
Example 15
Source File: TestDatabase.java    From BungeeChat2 with GNU General Public License v3.0 5 votes vote down vote up
@SneakyThrows(ManagedProcessException.class)
@SuppressFBWarnings( // TODO: Remove when fixed in SpotBugs
    value = "RV_RETURN_VALUE_IGNORED",
    justification = "Return values can be safely ignored as they are for chaining only.")
public static void startDatabase() {
  final int limit = 100;
  int count = 0;
  String actualBaseDir;
  String actualDataDir;

  do {
    actualBaseDir = baseDir + count;
  } while ((++count < limit) && (new File(actualBaseDir)).exists());

  Preconditions.checkElementIndex(count, limit, "count must be less than " + limit);

  actualDataDir = actualBaseDir + "/data";
  final DBConfiguration config =
      DBConfigurationBuilder.newBuilder()
          .setPort(0)
          .setSocket(localhost)
          .setBaseDir(actualBaseDir)
          .setDataDir(actualDataDir)
          .build();
  databaseInstance = DB.newEmbeddedDB(config);
  databaseInstance.start();

  port = databaseInstance.getConfiguration().getPort();
  host = localhost + ':' + port;

  databaseInstance.createDB("test");
}
 
Example 16
Source File: MaterializedRow.java    From presto with Apache License 2.0 4 votes vote down vote up
public Object getField(int field)
{
    Preconditions.checkElementIndex(field, values.size());
    return processField(values.get(field));
}
 
Example 17
Source File: RelMdColumnOrigins.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unused") // Called through reflection
public Set<RelColumnOrigin> getColumnOrigins(LogicalWindow window, RelMetadataQuery mq, int iOutputColumn) {
  final RelNode inputRel = window.getInput();
  final int numFieldsInInput = inputRel.getRowType().getFieldCount();
  if (iOutputColumn < numFieldsInInput) {
    return mq.getColumnOrigins(inputRel, iOutputColumn);
  }

  if (iOutputColumn >= window.getRowType().getFieldCount()) {
    return Collections.emptySet();
  }

  int startGroupIdx = iOutputColumn - numFieldsInInput;
  int curentIdx = 0;
  Group finalGroup = null;
  for (Group group : window.groups) {
    curentIdx += group.aggCalls.size();
    if (curentIdx > startGroupIdx) {
      // this is the group
      finalGroup = group;
      break;
    }
  }
  Preconditions.checkNotNull(finalGroup);
  // calculating index of the aggCall within a group
  // currentIdx = through idx within groups/aggCalls (max currentIdx = sum(groups size * aggCals_per_group) )
  // since currentIdx at this moment points to the end of the group substracting aggCals_per_group
  // to get to the beginning of the group and have startGroupIdx substract the diff
  final int aggCalIdx = startGroupIdx - (curentIdx - finalGroup.aggCalls.size());
  Preconditions.checkElementIndex(aggCalIdx, finalGroup.aggCalls.size());

  final Set<RelColumnOrigin> set = new HashSet<>();
  // Add aggregation column references
  final RexWinAggCall aggCall = finalGroup.aggCalls.get(aggCalIdx);
  for (RexNode operand : aggCall.operands) {
    if (operand instanceof RexInputRef) {
      final RexInputRef opInputRef = (RexInputRef) operand;
      if (opInputRef.getIndex() < numFieldsInInput) {
        Set<RelColumnOrigin> inputSet =
          mq.getColumnOrigins(inputRel, opInputRef.getIndex());
        inputSet = createDerivedColumnOrigins(inputSet);
        if (inputSet != null) {
          set.addAll(inputSet);
        }
      }
    }
  }

  return set;
}
 
Example 18
Source File: PropertyEnum.java    From Cleanstone with MIT License 4 votes vote down vote up
@Override
public E deserialize(int serializedValue) {
    Preconditions.checkElementIndex(serializedValue, enumClass.getEnumConstants().length);
    return enumClass.getEnumConstants()[serializedValue];
}
 
Example 19
Source File: SpriteMap.java    From GregTech with GNU Lesser General Public License v3.0 4 votes vote down vote up
public TextureArea getSprite(int x, int y) {
    Preconditions.checkElementIndex(x, spritesPerRow, "Invalid sprite x!");
    Preconditions.checkElementIndex(y, spritesPerRow, "Invalid sprite y!");
    double spriteUnit = 1 / (spritesPerRow * 1.0);
    return new TextureArea(imageLocation, spriteUnit * x, spriteUnit * y, spriteUnit, spriteUnit);
}
 
Example 20
Source File: ServerEndpoints.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
public ServerEndpoints(HttpEndpoint endpoints[], int initialEndpoint) {
    this.endpoints = Lists.newArrayList(endpoints);

    Preconditions.checkElementIndex(initialEndpoint, endpoints.length);
    currentEndpoint = initialEndpoint;
}