java.util.OptionalLong Java Examples

The following examples show how to use java.util.OptionalLong. 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: LockedApplication.java    From vespa with Apache License 2.0 6 votes vote down vote up
private LockedApplication(Lock lock, TenantAndApplicationId id, Instant createdAt, DeploymentSpec deploymentSpec,
                          ValidationOverrides validationOverrides,
                          Optional<IssueId> deploymentIssueId, Optional<IssueId> ownershipIssueId, Optional<User> owner,
                          OptionalInt majorVersion, ApplicationMetrics metrics, Set<PublicKey> deployKeys,
                          OptionalLong projectId, Optional<ApplicationVersion> latestVersion,
                          Map<InstanceName, Instance> instances) {
    this.lock = lock;
    this.id = id;
    this.createdAt = createdAt;
    this.deploymentSpec = deploymentSpec;
    this.validationOverrides = validationOverrides;
    this.deploymentIssueId = deploymentIssueId;
    this.ownershipIssueId = ownershipIssueId;
    this.owner = owner;
    this.majorVersion = majorVersion;
    this.metrics = metrics;
    this.deployKeys = deployKeys;
    this.projectId = projectId;
    this.latestVersion = latestVersion;
    this.instances = Map.copyOf(instances);
}
 
Example #2
Source File: TestThriftMetastoreUtil.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testStringStatsToColumnStatistics()
{
    StringColumnStatsData stringColumnStatsData = new StringColumnStatsData();
    stringColumnStatsData.setMaxColLen(100);
    stringColumnStatsData.setAvgColLen(23.333);
    stringColumnStatsData.setNumNulls(1);
    stringColumnStatsData.setNumDVs(20);
    ColumnStatisticsObj columnStatisticsObj = new ColumnStatisticsObj("my_col", STRING_TYPE_NAME, stringStats(stringColumnStatsData));
    HiveColumnStatistics actual = fromMetastoreApiColumnStatistics(columnStatisticsObj, OptionalLong.of(2));

    assertEquals(actual.getIntegerStatistics(), Optional.empty());
    assertEquals(actual.getDoubleStatistics(), Optional.empty());
    assertEquals(actual.getDecimalStatistics(), Optional.empty());
    assertEquals(actual.getDateStatistics(), Optional.empty());
    assertEquals(actual.getBooleanStatistics(), Optional.empty());
    assertEquals(actual.getMaxValueSizeInBytes(), OptionalLong.of(100));
    assertEquals(actual.getTotalSizeInBytes(), OptionalLong.of(23));
    assertEquals(actual.getNullsCount(), OptionalLong.of(1));
    assertEquals(actual.getDistinctValuesCount(), OptionalLong.of(1));
}
 
Example #3
Source File: SkipTable.java    From bifurcan with MIT License 6 votes vote down vote up
public OptionalLong floorIndex(long key) {
  Reader r = reader();
  if (key < r.key) {
    return OptionalLong.empty();
  }

  for (; ; ) {
    if (r.key > key) {
      if (r.tier == 0) {
        return OptionalLong.of(r.idx - 1);
      } else {
        r.descendPrev();
      }
    } else if (!r.hasNext() || r.key == key) {
      if (r.tier == 0) {
        return OptionalLong.of(r.idx);
      } else {
        r.descend();
      }
    } else {
      r.next();
    }
  }
}
 
Example #4
Source File: OptionalLongDslJsonConverter.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void configure(DslJson json) {
	json.registerWriter(OptionalLong.class, new JsonWriter.WriteObject<OptionalLong>() {
		@Override
		public void write(JsonWriter writer, @Nullable OptionalLong value) {
			if (value != null && value.isPresent()) NumberConverter.serialize(value.getAsLong(), writer);
			else writer.writeNull();
		}
	});
	json.registerReader(OptionalLong.class, new JsonReader.ReadObject<OptionalLong>() {
		@Override
		public OptionalLong read(JsonReader reader) throws IOException {
			return reader.wasNull() ? OptionalLong.empty() : OptionalLong.of(NumberConverter.deserializeLong(reader));
		}
	});
	json.registerDefault(OptionalLong.class, OptionalLong.empty());
}
 
Example #5
Source File: DefaultClientResponseTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void header() {
	HttpHeaders httpHeaders = new HttpHeaders();
	long contentLength = 42L;
	httpHeaders.setContentLength(contentLength);
	MediaType contentType = MediaType.TEXT_PLAIN;
	httpHeaders.setContentType(contentType);
	InetSocketAddress host = InetSocketAddress.createUnresolved("localhost", 80);
	httpHeaders.setHost(host);
	List<HttpRange> range = Collections.singletonList(HttpRange.createByteRange(0, 42));
	httpHeaders.setRange(range);

	when(mockResponse.getHeaders()).thenReturn(httpHeaders);

	ClientResponse.Headers headers = defaultClientResponse.headers();
	assertEquals(OptionalLong.of(contentLength), headers.contentLength());
	assertEquals(Optional.of(contentType), headers.contentType());
	assertEquals(httpHeaders, headers.asHttpHeaders());
}
 
Example #6
Source File: PeerDiscoveryController.java    From besu with Apache License 2.0 6 votes vote down vote up
/**
 * Executes the action associated with this state. Sets a "boomerang" timer to itself in case
 * the action is retryable.
 *
 * @param lastTimeout the previous timeout, or 0 if this is the first time the action is being
 *     executed.
 */
void execute(final long lastTimeout, final int retryCount) {
  action.accept(this);
  if (retryable && retryCount < MAX_RETRIES) {
    final long newTimeout = retryDelayFunction.apply(lastTimeout);
    timerId =
        OptionalLong.of(
            timerUtil.setTimer(
                newTimeout,
                () -> {
                  retryCounter.inc();
                  execute(newTimeout, retryCount + 1);
                }));
  } else {
    inflightInteractions.remove(peerId);
  }
}
 
Example #7
Source File: TestThriftMetastoreUtil.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmptyDoubleStatsToColumnStatistics()
{
    DoubleColumnStatsData emptyDoubleColumnStatsData = new DoubleColumnStatsData();
    ColumnStatisticsObj columnStatisticsObj = new ColumnStatisticsObj("my_col", DOUBLE_TYPE_NAME, doubleStats(emptyDoubleColumnStatsData));
    HiveColumnStatistics actual = fromMetastoreApiColumnStatistics(columnStatisticsObj, OptionalLong.empty());

    assertEquals(actual.getIntegerStatistics(), Optional.empty());
    assertEquals(actual.getDoubleStatistics(), Optional.of(new DoubleStatistics(OptionalDouble.empty(), OptionalDouble.empty())));
    assertEquals(actual.getDecimalStatistics(), Optional.empty());
    assertEquals(actual.getDateStatistics(), Optional.empty());
    assertEquals(actual.getBooleanStatistics(), Optional.empty());
    assertEquals(actual.getMaxValueSizeInBytes(), OptionalLong.empty());
    assertEquals(actual.getTotalSizeInBytes(), OptionalLong.empty());
    assertEquals(actual.getNullsCount(), OptionalLong.empty());
    assertEquals(actual.getDistinctValuesCount(), OptionalLong.empty());
}
 
Example #8
Source File: ConfigExtension.java    From smallrye-config with Apache License 2.0 6 votes vote down vote up
private static boolean isClassHandledByConfigProducer(Type requiredType) {
    return requiredType == String.class
            || requiredType == Boolean.class
            || requiredType == Boolean.TYPE
            || requiredType == Integer.class
            || requiredType == Integer.TYPE
            || requiredType == Long.class
            || requiredType == Long.TYPE
            || requiredType == Float.class
            || requiredType == Float.TYPE
            || requiredType == Double.class
            || requiredType == Double.TYPE
            || requiredType == Short.class
            || requiredType == Short.TYPE
            || requiredType == Byte.class
            || requiredType == Byte.TYPE
            || requiredType == Character.class
            || requiredType == Character.TYPE
            || requiredType == OptionalInt.class
            || requiredType == OptionalLong.class
            || requiredType == OptionalDouble.class
            || requiredType == Supplier.class
            || requiredType == ConfigValue.class;
}
 
Example #9
Source File: TestDatabaseShardManager.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testShardPruningNoStats()
{
    ShardInfo shard = shardInfo(UUID.randomUUID(), "node");
    List<ShardInfo> shards = ImmutableList.of(shard);

    long tableId = createTable("test");
    List<ColumnInfo> columns = ImmutableList.of(new ColumnInfo(1, BIGINT));
    RaptorColumnHandle c1 = new RaptorColumnHandle("c1", 1, BIGINT);

    shardManager.createTable(tableId, columns, false, OptionalLong.empty());

    long transactionId = shardManager.beginTransaction();
    shardManager.commitShards(transactionId, tableId, columns, shards, Optional.empty(), 0);

    shardAssertion(tableId).expected(shards);
    shardAssertion(tableId).equal(c1, BIGINT, 3L).expected(shards);
}
 
Example #10
Source File: ExpireAfterVarTest.java    From caffeine with Apache License 2.0 6 votes vote down vote up
@CacheSpec(implementation = Implementation.Caffeine,
    population = Population.FULL, expiry = CacheExpiry.MOCKITO)
@Test(dataProvider = "caches", expectedExceptions = ExpirationException.class)
public void put_update_expiryFails(Cache<Integer, Integer> cache, CacheContext context,
    VarExpiration<Integer, Integer> expireVariably) {
  OptionalLong duration = expireVariably.getExpiresAfter(context.firstKey(), NANOSECONDS);
  try {
    context.ticker().advance(1, TimeUnit.HOURS);
    when(context.expiry().expireAfterUpdate(any(), any(), anyLong(), anyLong()))
        .thenThrow(ExpirationException.class);
    cache.put(context.firstKey(), context.absentValue());
  } finally {
    context.ticker().advance(-1, TimeUnit.HOURS);
    assertThat(cache.asMap(), equalTo(context.original()));
    assertThat(expireVariably.getExpiresAfter(context.firstKey(), NANOSECONDS), is(duration));
  }
}
 
Example #11
Source File: KeyLock.java    From atomix with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to lock the key.
 *
 * @return a future to be completed once the lock attempt is complete
 */
CompletableFuture<OptionalLong> tryLock() {
  // If the proxy is currently disconnected from the cluster, we can just fail the lock attempt here.
  PrimitiveState state = client.getPartition(partitionId).getState();
  if (state != PrimitiveState.CONNECTED) {
    return CompletableFuture.completedFuture(OptionalLong.empty());
  }

  // Create and register a new attempt and invoke the LOCK operation on teh replicated state machine with
  // a 0 timeout. The timeout will cause the state machine to immediately reject the request if the lock is
  // already owned by another process.
  LockFuture future = new LockFuture();
  client.acceptOn(partitionId, service -> service.lock(key, future.id(), 0)).whenComplete((result, error) -> {
    if (error != null) {
      future.completeExceptionally(error);
    }
  });
  return future.thenApply(v -> v != null ? OptionalLong.of(v) : OptionalLong.empty());
}
 
Example #12
Source File: PinotQueryBuilder.java    From presto with Apache License 2.0 5 votes vote down vote up
public static String generatePql(PinotTableHandle tableHandle, List<PinotColumnHandle> columnHandles, Optional<String> tableNameSuffix, Optional<String> timePredicate)
{
    requireNonNull(tableHandle, "tableHandle is null");
    StringBuilder pqlBuilder = new StringBuilder();
    List<String> columnNames;
    if (columnHandles.isEmpty()) {
        // This occurs when the query is SELECT COUNT(*) FROM pinotTable ...
        columnNames = ImmutableList.of("*");
    }
    else {
        columnNames = columnHandles.stream()
                .map(PinotColumnHandle::getColumnName)
                .collect(toImmutableList());
    }

    pqlBuilder.append("SELECT ");
    pqlBuilder.append(String.join(", ", columnNames))
            .append(" FROM ")
            .append(getTableName(tableHandle, tableNameSuffix))
            .append(" ");
    generateFilterPql(pqlBuilder, tableHandle, timePredicate, columnHandles);
    OptionalLong limit = tableHandle.getLimit();
    if (limit.isPresent()) {
        pqlBuilder.append(" LIMIT ")
                .append(limit.getAsLong());
    }
    else {
        pqlBuilder.append(" LIMIT ")
                .append(Integer.MAX_VALUE);
    }
    return pqlBuilder.toString();
}
 
Example #13
Source File: TestDatabaseShardManager.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test
public void testAssignShard()
{
    long tableId = createTable("test");
    UUID shard = UUID.randomUUID();
    List<ShardInfo> shardNodes = ImmutableList.of(shardInfo(shard, "node1"));
    List<ColumnInfo> columns = ImmutableList.of(new ColumnInfo(1, BIGINT));

    shardManager.createTable(tableId, columns, false, OptionalLong.empty());

    long transactionId = shardManager.beginTransaction();
    shardManager.commitShards(transactionId, tableId, columns, shardNodes, Optional.empty(), 0);

    ShardNodes actual = getOnlyElement(getShardNodes(tableId, TupleDomain.all()));
    assertEquals(actual, new ShardNodes(shard, ImmutableSet.of("node1")));

    try {
        shardManager.replaceShardAssignment(tableId, shard, "node2", true);
        fail("expected exception");
    }
    catch (PrestoException e) {
        assertEquals(e.getErrorCode(), SERVER_STARTING_UP.toErrorCode());
    }

    // replace shard assignment to another node
    shardManager.replaceShardAssignment(tableId, shard, "node2", false);

    actual = getOnlyElement(getShardNodes(tableId, TupleDomain.all()));
    assertEquals(actual, new ShardNodes(shard, ImmutableSet.of("node2")));

    // replacing shard assignment should be idempotent
    shardManager.replaceShardAssignment(tableId, shard, "node2", false);

    actual = getOnlyElement(getShardNodes(tableId, TupleDomain.all()));
    assertEquals(actual, new ShardNodes(shard, ImmutableSet.of("node2")));
}
 
Example #14
Source File: ISortedSet.java    From bifurcan with MIT License 5 votes vote down vote up
@Override
default OptionalLong indexOf(V element) {
  OptionalLong idx = floorIndex(element);
  return idx.isPresent() && comparator().compare(nth(idx.getAsLong()), element) == 0
      ? idx
      : OptionalLong.empty();
}
 
Example #15
Source File: SqlStandardAccessControlMetadata.java    From presto with Apache License 2.0 5 votes vote down vote up
private Set<RoleGrant> getRoleGrantsByGrantees(Set<String> grantees, OptionalLong limit)
{
    ImmutableSet.Builder<RoleGrant> roleGrants = ImmutableSet.builder();
    int count = 0;
    for (String grantee : grantees) {
        for (PrincipalType type : new PrincipalType[] {USER, ROLE}) {
            if (limit.isPresent() && count >= limit.getAsLong()) {
                return roleGrants.build();
            }
            for (RoleGrant grant : metastore.listRoleGrants(new HivePrincipal(type, grantee))) {
                // Filter out the "public" role since it is not explicitly granted in Hive.
                if (PUBLIC_ROLE_NAME.equals(grant.getRoleName())) {
                    continue;
                }
                count++;
                roleGrants.add(grant);
            }
        }
    }
    return roleGrants.build();
}
 
Example #16
Source File: JsonUtilTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void getLong_validValue() {
  final ObjectNode node = mapper.createObjectNode();
  node.put("test", Long.MAX_VALUE);
  final OptionalLong result = JsonUtil.getLong(node, "test");
  assertThat(result).hasValue(Long.MAX_VALUE);
}
 
Example #17
Source File: TestSaveSpaceUsageToFile.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Test
public void doesNotLoadIfTimeMissing() throws IOException {
  saveToFile(Long.toString(VALID_USAGE_SOURCE.getUsedSpace()));
  SpaceUsagePersistence subject = new SaveSpaceUsageToFile(file, LONG_EXPIRY);

  OptionalLong savedValue = subject.load();

  assertFalse(savedValue.isPresent());
}
 
Example #18
Source File: WriteResult.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Total number of changes occurred after a write operation. Sum of existing counts
 * if they're all defined, otherwise return {@link OptionalLong#empty()}.
 */
default OptionalLong totalCount() {
  if (insertedCount().isPresent() && deletedCount().isPresent() && updatedCount().isPresent()) {
    long value = insertedCount().getAsLong() + deletedCount().getAsLong() + updatedCount().getAsLong();
    return OptionalLong.of(value);
  }

  return OptionalLong.empty();
}
 
Example #19
Source File: DefaultServerRequestTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void header() {
	HttpHeaders httpHeaders = new HttpHeaders();
	List<MediaType> accept =
			Collections.singletonList(MediaType.APPLICATION_JSON);
	httpHeaders.setAccept(accept);
	List<Charset> acceptCharset = Collections.singletonList(UTF_8);
	httpHeaders.setAcceptCharset(acceptCharset);
	long contentLength = 42L;
	httpHeaders.setContentLength(contentLength);
	MediaType contentType = MediaType.TEXT_PLAIN;
	httpHeaders.setContentType(contentType);
	InetSocketAddress host = InetSocketAddress.createUnresolved("localhost", 80);
	httpHeaders.setHost(host);
	List<HttpRange> range = Collections.singletonList(HttpRange.createByteRange(0, 42));
	httpHeaders.setRange(range);

	MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/");
	httpHeaders.forEach(servletRequest::addHeader);
	servletRequest.setContentType(MediaType.TEXT_PLAIN_VALUE);

	DefaultServerRequest request = new DefaultServerRequest(servletRequest,
			this.messageConverters);

	ServerRequest.Headers headers = request.headers();
	assertEquals(accept, headers.accept());
	assertEquals(acceptCharset, headers.acceptCharset());
	assertEquals(OptionalLong.of(contentLength), headers.contentLength());
	assertEquals(Optional.of(contentType), headers.contentType());
	assertEquals(httpHeaders, headers.asHttpHeaders());
}
 
Example #20
Source File: ApplicationSerializer.java    From vespa with Apache License 2.0 5 votes vote down vote up
private ApplicationVersion applicationVersionFromSlime(Inspector object) {
    if ( ! object.valid()) return ApplicationVersion.unknown;
    OptionalLong applicationBuildNumber = Serializers.optionalLong(object.field(applicationBuildNumberField));
    if (applicationBuildNumber.isEmpty())
        return ApplicationVersion.unknown;

    Optional<SourceRevision> sourceRevision = sourceRevisionFromSlime(object.field(sourceRevisionField));
    Optional<String> authorEmail = Serializers.optionalString(object.field(authorEmailField));
    Optional<Version> compileVersion = Serializers.optionalString(object.field(compileVersionField)).map(Version::fromString);
    Optional<Instant> buildTime = Serializers.optionalInstant(object.field(buildTimeField));
    Optional<String> sourceUrl = Serializers.optionalString(object.field(sourceUrlField));
    Optional<String> commit = Serializers.optionalString(object.field(commitField));

    return new ApplicationVersion(sourceRevision, applicationBuildNumber, authorEmail, compileVersion, buildTime, sourceUrl, commit);
}
 
Example #21
Source File: OptionalNumericalTypesTestCase.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testOptionalLongWithAbsentProperty() {
    try {
        config.getValue("my.long.not.found", Long.class);
        fail("must throw a NoSuchMethodException");
    } catch (NoSuchElementException e) {
    }

    assertFalse(config.getOptionalValue("my.long.not.found", Long.class).isPresent());

    assertFalse(config.getValue("my.long.not.found", OptionalLong.class).isPresent());

    assertTrue(config.getOptionalValue("my.long.not.found", OptionalLong.class).isPresent());
}
 
Example #22
Source File: TestMetastoreHiveStatisticsProvider.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTableStatisticsUnpartitioned()
{
    PartitionStatistics statistics = PartitionStatistics.builder()
            .setBasicStatistics(new HiveBasicStatistics(OptionalLong.empty(), OptionalLong.of(1000), OptionalLong.empty(), OptionalLong.empty()))
            .setColumnStatistics(ImmutableMap.of(COLUMN, createIntegerColumnStatistics(OptionalLong.of(-100), OptionalLong.of(100), OptionalLong.of(500), OptionalLong.of(300))))
            .build();
    MetastoreHiveStatisticsProvider statisticsProvider = new MetastoreHiveStatisticsProvider((session, table, hivePartitions) -> ImmutableMap.of(UNPARTITIONED_ID, statistics));

    HiveColumnHandle columnHandle = createBaseColumn(COLUMN, 2, HIVE_LONG, BIGINT, REGULAR, Optional.empty());

    TableStatistics expected = TableStatistics.builder()
            .setRowCount(Estimate.of(1000))
            .setColumnStatistics(
                    columnHandle,
                    ColumnStatistics.builder()
                            .setRange(new DoubleRange(-100, 100))
                            .setNullsFraction(Estimate.of(0.5))
                            .setDistinctValuesCount(Estimate.of(300))
                            .build())
            .build();
    assertEquals(
            statisticsProvider.getTableStatistics(
                    SESSION,
                    TABLE,
                    ImmutableMap.of(COLUMN, columnHandle),
                    ImmutableMap.of(COLUMN, BIGINT),
                    ImmutableList.of(new HivePartition(TABLE))),
            expected);
}
 
Example #23
Source File: ProtocolScheduleBuilder.java    From besu with Apache License 2.0 5 votes vote down vote up
private long validateForkOrder(
    final String forkName, final OptionalLong thisForkBlock, final long lastForkBlock) {
  final long referenceForkBlock = thisForkBlock.orElse(lastForkBlock);
  if (lastForkBlock > referenceForkBlock) {
    throw new RuntimeException(
        String.format(
            "Genesis Config Error: '%s' is scheduled for block %d but it must be on or after block %d.",
            forkName, thisForkBlock.getAsLong(), lastForkBlock));
  }
  return referenceForkBlock;
}
 
Example #24
Source File: BasicLong.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test(groups = "unit")
    public void testPresent() {
    OptionalLong empty = OptionalLong.empty();
    OptionalLong present = OptionalLong.of(1L);

    // present
    assertTrue(present.equals(present));
    assertFalse(present.equals(OptionalLong.of(0L)));
    assertTrue(present.equals(OptionalLong.of(1L)));
    assertFalse(present.equals(empty));
    assertTrue(Long.hashCode(1) == present.hashCode());
    assertFalse(present.toString().isEmpty());
    assertTrue(-1 != present.toString().indexOf(Long.toString(present.getAsLong()).toString()));
    assertEquals(1L, present.getAsLong());
    try {
        present.ifPresent(v -> { throw new ObscureException(); });
        fail();
    } catch(ObscureException expected) {

    }
    assertEquals(1, present.orElse(2));
    assertEquals(1, present.orElseGet(null));
    assertEquals(1, present.orElseGet(()-> 2));
    assertEquals(1, present.orElseGet(()-> 3));
    assertEquals(1, present.<RuntimeException>orElseThrow(null));
    assertEquals(1, present.<RuntimeException>orElseThrow(ObscureException::new));
}
 
Example #25
Source File: JsonUtil.java    From besu with Apache License 2.0 5 votes vote down vote up
public static OptionalLong getLong(final ObjectNode json, final String key) {
  return getValue(json, key)
      .filter(jsonNode -> validateType(jsonNode, JsonNodeType.NUMBER))
      .filter(JsonUtil::validateLong)
      .map(JsonNode::asLong)
      .map(OptionalLong::of)
      .orElse(OptionalLong.empty());
}
 
Example #26
Source File: SqlStandardAccessControlMetadata.java    From presto with Apache License 2.0 5 votes vote down vote up
private Set<RoleGrant> getRoleGrantsByRoles(Set<String> roles, OptionalLong limit)
{
    ImmutableSet.Builder<RoleGrant> roleGrants = ImmutableSet.builder();
    int count = 0;
    for (String role : roles) {
        if (limit.isPresent() && count >= limit.getAsLong()) {
            break;
        }
        for (RoleGrant grant : metastore.listGrantedPrincipals(role)) {
            count++;
            roleGrants.add(grant);
        }
    }
    return roleGrants.build();
}
 
Example #27
Source File: OptionalMatchers.java    From java-8-matchers with MIT License 5 votes vote down vote up
/**
 * Matches an empty OptionalLong.
 */
public static Matcher<OptionalLong> emptyLong() {
    return new TypeSafeMatcher<OptionalLong>() {
        @Override
        protected boolean matchesSafely(OptionalLong item) {
            return !item.isPresent();
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("An empty OptionalLong");
        }
    };
}
 
Example #28
Source File: CountingMockConnector.java    From presto with Apache License 2.0 5 votes vote down vote up
public void incrementListRoleGrants(Optional<Set<String>> roles, Optional<Set<String>> grantees, OptionalLong limit)
{
    listRowGrantsCallsCounter.incrementAndGet();
    roles.ifPresent(x -> rolesPushedCounter.incrementAndGet());
    grantees.ifPresent(x -> granteesPushedCounter.incrementAndGet());
    limit.ifPresent(x -> limitPushedCounter.incrementAndGet());
}
 
Example #29
Source File: MetastoreHiveStatisticsProvider.java    From presto with Apache License 2.0 5 votes vote down vote up
private static OptionalDouble getPartitionRowCount(String partitionName, Map<String, PartitionStatistics> statistics)
{
    PartitionStatistics partitionStatistics = statistics.get(partitionName);
    if (partitionStatistics == null) {
        return OptionalDouble.empty();
    }
    OptionalLong rowCount = partitionStatistics.getBasicStatistics().getRowCount();
    if (rowCount.isPresent()) {
        verify(rowCount.getAsLong() >= 0, "rowCount must be greater than or equal to zero");
        return OptionalDouble.of(rowCount.getAsLong());
    }
    return OptionalDouble.empty();
}
 
Example #30
Source File: EBMLParserTest.java    From amazon-kinesis-video-streams-parser-library with Apache License 2.0 5 votes vote down vote up
@Test
public void unknownElementsTest() throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte [] EBML_element_rawbytes = writeElement(EBML_id_bytes, UNKNOWN_LENGTH, outputStream);
    byte [] EBMLVersion_element_rawbytes = writeElement(EBMLVersion_id_bytes, wrapByte(0x83), outputStream);
    byte [] EBMLVersion_data_bytes = new byte[] {0x1, 0x4, 0xD};

    outputStream.write(EBMLVersion_data_bytes);

    //unknown elements
    byte [] COLOUR_element_rawbytes = writeElement(COLOUR_id_bytes, wrapByte(0x85),outputStream);
    byte [] MATRIX_COEFFICIENT_element_rawbytes = writeElement(MATRIX_COEFFICIENTS_id_bytes, wrapByte(0x82), outputStream);
    byte [] MATRIX_COEFFICIENT_data_bytes = new byte [] {0x1, 0x2};

    outputStream.write(MATRIX_COEFFICIENT_data_bytes);

    outputStream.write(EBML_ZERO_LENGTH_RAWBYTES);

    parserCallback.setCheckExpectedCallbacks(true);
    parserCallback.expectCallback(createExpectedCallbackForStartOfEBMLUnknownLength(EBML_element_rawbytes));

    addExpectedCallbacksForBaseElement(TestEBMLTypeInfoProvider.EBMLVersion,
            EBMLVersion_element_rawbytes,
            EBMLVersion_data_bytes,
            1,
            1).expectCallback(createExpectedCallbackForEndEBML(0))
            .expectCallback(TestEBMLParserCallback.CallbackDescription.builder()
                    .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START)
                    .elementCount(3)
                    .typeInfo(TestEBMLTypeInfoProvider.EBML)
                    .numBytes(OptionalLong.of(0))
                    .bytes(EBML_ZERO_LENGTH_RAWBYTES)
                    .build())
            .expectCallback(createExpectedCallbackForEndEBML(3));

    testRawBytesMatch = false;
    callParser(outputStream, 1);
}