Java Code Examples for java.util.OptionalInt#isPresent()

The following examples show how to use java.util.OptionalInt#isPresent() . 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: ServiceLocator.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
/**
 * For the {@link Service} class specified, attempt to instantiate the service using the
 * {@link ServiceFactory} infrastructure.
 *
 * @param serviceClass the {@code Service} type to create
 * @param <T> the type of the {@code Service}
 *
 * @return the collection of created services; may be empty
 *
 * @throws IllegalStateException if the configured service is already registered or the configured service
 *        implements a {@code Service} subtype that is not marked with the {@link PluralService} annotation
 *        but is already registered
 */
private <T, V> Collection<ServiceFactory<? extends T>> discoverServices(ServiceMap resolved, Class<T> serviceClass) {
  @SuppressWarnings("unchecked")
  Collection<ServiceFactory<? extends T>> typedServiceFactories = stream(serviceFactories.spliterator(), false)
    .filter(f -> serviceClass.isAssignableFrom(f.getServiceType())).map(f -> (ServiceFactory<? extends T>) f)
    .filter(f -> !f.getClass().isAnnotationPresent(ServiceFactory.RequiresConfiguration.class))
    .filter(f -> !provided.contains(f.getServiceType()))
    .filter(f -> !resolved.contains(f.getServiceType()))
    .collect(toList());

  OptionalInt highestRank = typedServiceFactories.stream().mapToInt(ServiceFactory::rank).max();

  if (highestRank.isPresent()) {
    return typedServiceFactories.stream().filter(f -> highestRank.getAsInt() == f.rank()).collect(toList());
  } else {
    return emptyList();
  }
}
 
Example 2
Source File: XfBcryptExtension.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void changePassword(String user, HashedPassword password, Connection con) throws SQLException {
    OptionalInt authId = retrieveIdFromTable(user, con);
    if (authId.isPresent()) {
        final int id = authId.getAsInt();
        // Insert password in the correct table
        String sql = "UPDATE " + xfPrefix + "user_authenticate SET data=? WHERE " + col.ID + "=?;";
        try (PreparedStatement pst = con.prepareStatement(sql)) {
            String serializedHash = XfBCrypt.serializeHash(password.getHash());
            byte[] bytes = serializedHash.getBytes();
            Blob blob = con.createBlob();
            blob.setBytes(1, bytes);
            pst.setBlob(1, blob);
            pst.setInt(2, id);
            pst.executeUpdate();
        }

        // ...
        sql = "UPDATE " + xfPrefix + "user_authenticate SET scheme_class=? WHERE " + col.ID + "=?;";
        try (PreparedStatement pst = con.prepareStatement(sql)) {
            pst.setString(1, XfBCrypt.SCHEME_CLASS);
            pst.setInt(2, id);
            pst.executeUpdate();
        }
    }
}
 
Example 3
Source File: MongoQueryBuilder.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public QueryBuilder sort(final List<SortOption> sortOptions) {
    checkNotNull(sortOptions, "sort options");
    final OptionalInt thingIdEntry = IntStream.range(0, sortOptions.size())
            .filter(i -> ID_SORT_FIELD_EXPRESSION.equals(sortOptions.get(i).getSortExpression()))
            .findFirst();
    if (thingIdEntry.isPresent()) {
        this.sortOptions = sortOptions.subList(0, thingIdEntry.getAsInt() + 1);
    } else {
        final List<SortOption> options = new ArrayList<>(sortOptions.size() + DEFAULT_SORT_OPTIONS.size());
        options.addAll(sortOptions);
        options.addAll(DEFAULT_SORT_OPTIONS);
        this.sortOptions = options;
    }
    return this;
}
 
Example 4
Source File: HStore.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * @return get maximum ref count of storeFile among all compacted HStore Files for the HStore
 */
public int getMaxCompactedStoreFileRefCount() {
  OptionalInt maxCompactedStoreFileRefCount = this.storeEngine.getStoreFileManager()
    .getCompactedfiles()
    .stream()
    .filter(sf -> sf.getReader() != null)
    .filter(HStoreFile::isHFile)
    .mapToInt(HStoreFile::getRefCount)
    .max();
  return maxCompactedStoreFileRefCount.isPresent()
    ? maxCompactedStoreFileRefCount.getAsInt() : 0;
}
 
Example 5
Source File: LoadBalanceSession.java    From nifi with Apache License 2.0 5 votes vote down vote up
private boolean confirmTransactionComplete() throws IOException {
    logger.debug("Confirming Transaction Complete for Peer {}", peerDescription);

    final OptionalInt transactionResponse = channel.read();
    if (!transactionResponse.isPresent()) {
        if (System.currentTimeMillis() > readTimeout) {
            throw new SocketTimeoutException("Timed out waiting for Peer " + peerDescription + " to confirm the transaction is complete");
        }

        return false;
    }

    final int response = transactionResponse.getAsInt();
    if (response < 0) {
        throw new EOFException("Confirmed checksum when writing data to Peer " + peerDescription + " but encountered End-of-File when expecting a Transaction Complete confirmation");
    }

    if (response == ABORT_TRANSACTION) {
        throw new TransactionAbortedException("Confirmed checksum when writing data to Peer " + peerDescription + " but Peer aborted transaction instead of completing it");
    }
    if (response != CONFIRM_COMPLETE_TRANSACTION) {
        throw new IOException("Expected a CONFIRM_COMPLETE_TRANSACTION response from Peer " + peerDescription + " but received a value of " + response);
    }

    complete = true;
    logger.debug("Successfully completed Transaction to send {} FlowFiles to Peer {} for Connection {}", flowFilesSent.size(), peerDescription, connectionId);

    return true;
}
 
Example 6
Source File: DoctorReportHelper.java    From buck with Apache License 2.0 5 votes vote down vote up
private String printBuildTime(OptionalInt buildTimeMs) {
  if (!buildTimeMs.isPresent()) {
    return "Unknown";
  }
  long buildTimeSecs = TimeUnit.MILLISECONDS.toSeconds(buildTimeMs.getAsInt());
  long mins = buildTimeSecs / 60;
  long secs = buildTimeSecs % 60;
  return mins == 0 ? String.format("%ds", secs) : String.format("%dm %ds", mins, secs);
}
 
Example 7
Source File: OptionalIntAttributeConverter.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public AttributeValue transformFrom(OptionalInt input) {
    if (input.isPresent()) {
        return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build();
    } else {
        return AttributeValues.nullAttributeValue();
    }
}
 
Example 8
Source File: OptionalIntWithSentinel.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Encoding.Of
static int initFrom(OptionalInt optional) {
  if (optional.isPresent()) {
    return safeValue(optional.getAsInt());
  }
  return SENTINEL_VALUE;
}
 
Example 9
Source File: LoadBalanceSession.java    From nifi with Apache License 2.0 5 votes vote down vote up
private boolean receiveProtocolVersionAcknowledgment() throws IOException {
    logger.debug("Confirming Transaction Complete for Peer {}", peerDescription);

    final OptionalInt ackResponse = channel.read();
    if (!ackResponse.isPresent()) {
        if (System.currentTimeMillis() > readTimeout) {
            throw new SocketTimeoutException("Timed out waiting for Peer " + peerDescription + " to acknowledge Protocol Version");
        }

        return false;
    }

    final int response = ackResponse.getAsInt();
    if (response < 0) {
        throw new EOFException("Encounter End-of-File with Peer " + peerDescription + " when expecting a Protocol Version Acknowledgment");
    }

    if (response == VERSION_ACCEPTED) {
        logger.debug("Peer {} accepted Protocol Version {}", peerDescription, protocolVersion);
        phase = TransactionPhase.SEND_CONNECTION_ID;
        return true;
    }

    if (response == REQEUST_DIFFERENT_VERSION) {
        logger.debug("Recommended using Protocol Version of {} with Peer {} but received REQUEST_DIFFERENT_VERSION response", protocolVersion, peerDescription);
        readTimeout = System.currentTimeMillis() + timeoutMillis;
        phase = TransactionPhase.RECEIVE_RECOMMENDED_PROTOCOL_VERSION;
        return true;
    }

    throw new IOException("Failed to negotiate Protocol Version with Peer " + peerDescription + ". Recommended version " + protocolVersion + " but instead of an ACCEPT or REJECT " +
            "response got back a response of " + response);
}
 
Example 10
Source File: LoadBalanceSession.java    From nifi with Apache License 2.0 5 votes vote down vote up
private boolean receiveSpaceAvailableResponse() throws IOException {
    logger.debug("Receiving response from Peer {} to determine whether or not space is available in queue {}", peerDescription, connectionId);

    final OptionalInt spaceAvailableResponse = channel.read();
    if (!spaceAvailableResponse.isPresent()) {
        if (System.currentTimeMillis() > readTimeout) {
            throw new SocketTimeoutException("Timed out waiting for Peer " + peerDescription + " to verify whether or not space is available for Connection " + connectionId);
        }

        return false;
    }

    final int response = spaceAvailableResponse.getAsInt();
    if (response < 0) {
        throw new EOFException("Encountered End-of-File when trying to verify with Peer " + peerDescription + " whether or not space is available in Connection " + connectionId);
    }

    if (response == SPACE_AVAILABLE) {
        logger.debug("Peer {} has confirmed that space is available in Connection {}", peerDescription, connectionId);
        phase = TransactionPhase.GET_NEXT_FLOWFILE;
    } else if (response == QUEUE_FULL) {
        logger.debug("Peer {} has confirmed that the queue is full for Connection {}", peerDescription, connectionId);
        phase = TransactionPhase.RECOMMEND_PROTOCOL_VERSION;
        checksum.reset(); // We are restarting the session entirely so we need to reset our checksum
        complete = true; // consider complete because there's nothing else that we can do in this session. Allow client to move on to a different session.
        partition.penalize(1000L);
    } else {
        throw new TransactionAbortedException("After requesting to know whether or not Peer " + peerDescription + " has space available in Connection " + connectionId
            + ", received unexpected response of " + response + ". Aborting transaction.");
    }

    return true;
}
 
Example 11
Source File: BuckGlobalStateFactory.java    From buck with Apache License 2.0 5 votes vote down vote up
private static Optional<WebServer> createWebServer(
    BuckConfig config, ProjectFilesystem filesystem, Clock clock) {
  OptionalInt port = getValidWebServerPort(config);
  if (!port.isPresent()) {
    return Optional.empty();
  }
  return Optional.of(new WebServer(port.getAsInt(), filesystem, clock));
}
 
Example 12
Source File: EnodeURL.java    From besu with Apache License 2.0 5 votes vote down vote up
public URI toURI() {
  final String uri =
      String.format(
          "enode://%s@%s:%d",
          nodeId.toUnprefixedHexString(),
          InetAddresses.toUriString(ip),
          getListeningPortOrZero());
  final OptionalInt discPort = getDiscPortQueryParam();
  if (discPort.isPresent()) {
    return URI.create(uri + String.format("?discport=%d", discPort.getAsInt()));
  } else {
    return URI.create(uri);
  }
}
 
Example 13
Source File: WeightCache.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
protected @NonNull OptionalInt supply() {
    boolean seen = false;
    int best = 0;
    for (Node n : this.group.getOwnNodes(QueryOptionsImpl.DEFAULT_NON_CONTEXTUAL)) {
        if (n instanceof WeightNode) {
            WeightNode weightNode = (WeightNode) n;
            int value = weightNode.getWeight();

            if (!seen || value > best) {
                seen = true;
                best = value;
            }
        }
    }

    OptionalInt weight = seen ? OptionalInt.of(best) : OptionalInt.empty();

    if (!weight.isPresent()) {
        Map<String, Integer> configWeights = this.group.getPlugin().getConfiguration().get(ConfigKeys.GROUP_WEIGHTS);
        Integer w = configWeights.get(this.group.getObjectName().toLowerCase());
        if (w != null) {
            weight = OptionalInt.of(w);
        }
    }

    return weight;
}
 
Example 14
Source File: PermissionHolder.java    From LuckPerms with MIT License 5 votes vote down vote up
public MetaAccumulator accumulateMeta(MetaAccumulator accumulator, QueryOptions queryOptions) {
    InheritanceGraph graph = this.plugin.getInheritanceGraphFactory().getGraph(queryOptions);
    for (PermissionHolder holder : graph.traverse(this)) {
        // accumulate nodes
        for (DataType dataType : holder.queryOrder(queryOptions)) {
            holder.getData(dataType).forEach(queryOptions, node -> {
                if (node.getValue() && NodeType.META_OR_CHAT_META.matches(node)) {
                    accumulator.accumulateNode(node);
                }
            });
        }

        // accumulate weight
        OptionalInt w = holder.getWeight();
        if (w.isPresent()) {
            accumulator.accumulateWeight(w.getAsInt());
        }
    }

    // accumulate primary group
    if (this instanceof User) {
        String primaryGroup = ((User) this).getPrimaryGroup().calculateValue(queryOptions);
        accumulator.setPrimaryGroup(primaryGroup);
    }

    accumulator.complete();
    return accumulator;
}
 
Example 15
Source File: OptionalUtils.java    From dalesbred with MIT License 4 votes vote down vote up
private static @Nullable Object unwrap(@NotNull OptionalInt o) {
    return o.isPresent() ? o.getAsInt() : null;
}
 
Example 16
Source File: FixedSourcePartitionedScheduler.java    From presto with Apache License 2.0 4 votes vote down vote up
public FixedSourcePartitionedScheduler(
        SqlStageExecution stage,
        Map<PlanNodeId, SplitSource> splitSources,
        StageExecutionDescriptor stageExecutionDescriptor,
        List<PlanNodeId> schedulingOrder,
        List<InternalNode> nodes,
        BucketNodeMap bucketNodeMap,
        int splitBatchSize,
        OptionalInt concurrentLifespansPerTask,
        NodeSelector nodeSelector,
        List<ConnectorPartitionHandle> partitionHandles)
{
    requireNonNull(stage, "stage is null");
    requireNonNull(splitSources, "splitSources is null");
    requireNonNull(bucketNodeMap, "bucketNodeMap is null");
    checkArgument(!requireNonNull(nodes, "nodes is null").isEmpty(), "nodes is empty");
    requireNonNull(partitionHandles, "partitionHandles is null");

    this.stage = stage;
    this.nodes = ImmutableList.copyOf(nodes);
    this.partitionHandles = ImmutableList.copyOf(partitionHandles);

    checkArgument(splitSources.keySet().equals(ImmutableSet.copyOf(schedulingOrder)));

    BucketedSplitPlacementPolicy splitPlacementPolicy = new BucketedSplitPlacementPolicy(nodeSelector, nodes, bucketNodeMap, stage::getAllTasks);

    ArrayList<SourceScheduler> sourceSchedulers = new ArrayList<>();
    checkArgument(
            partitionHandles.equals(ImmutableList.of(NOT_PARTITIONED)) != stageExecutionDescriptor.isStageGroupedExecution(),
            "PartitionHandles should be [NOT_PARTITIONED] if and only if all scan nodes use ungrouped execution strategy");
    int nodeCount = nodes.size();
    int concurrentLifespans;
    if (concurrentLifespansPerTask.isPresent() && concurrentLifespansPerTask.getAsInt() * nodeCount <= partitionHandles.size()) {
        concurrentLifespans = concurrentLifespansPerTask.getAsInt() * nodeCount;
    }
    else {
        concurrentLifespans = partitionHandles.size();
    }

    boolean firstPlanNode = true;
    Optional<LifespanScheduler> groupedLifespanScheduler = Optional.empty();
    for (PlanNodeId planNodeId : schedulingOrder) {
        SplitSource splitSource = splitSources.get(planNodeId);
        boolean groupedExecutionForScanNode = stageExecutionDescriptor.isScanGroupedExecution(planNodeId);
        SourceScheduler sourceScheduler = newSourcePartitionedSchedulerAsSourceScheduler(
                stage,
                planNodeId,
                splitSource,
                splitPlacementPolicy,
                Math.max(splitBatchSize / concurrentLifespans, 1),
                groupedExecutionForScanNode);

        if (stageExecutionDescriptor.isStageGroupedExecution() && !groupedExecutionForScanNode) {
            sourceScheduler = new AsGroupedSourceScheduler(sourceScheduler);
        }
        sourceSchedulers.add(sourceScheduler);

        if (firstPlanNode) {
            firstPlanNode = false;
            if (!stageExecutionDescriptor.isStageGroupedExecution()) {
                sourceScheduler.startLifespan(Lifespan.taskWide(), NOT_PARTITIONED);
                sourceScheduler.noMoreLifespans();
            }
            else {
                LifespanScheduler lifespanScheduler;
                if (bucketNodeMap.isDynamic()) {
                    // Callee of the constructor guarantees dynamic bucket node map will only be
                    // used when the stage has no remote source.
                    //
                    // When the stage has no remote source, any scan is grouped execution guarantees
                    // all scan is grouped execution.
                    lifespanScheduler = new DynamicLifespanScheduler(bucketNodeMap, nodes, partitionHandles, concurrentLifespansPerTask);
                }
                else {
                    lifespanScheduler = new FixedLifespanScheduler(bucketNodeMap, partitionHandles, concurrentLifespansPerTask);
                }

                // Schedule the first few lifespans
                lifespanScheduler.scheduleInitial(sourceScheduler);
                // Schedule new lifespans for finished ones
                stage.addCompletedDriverGroupsChangedListener(lifespanScheduler::onLifespanFinished);
                groupedLifespanScheduler = Optional.of(lifespanScheduler);
            }
        }
    }
    this.groupedLifespanScheduler = groupedLifespanScheduler;
    this.sourceSchedulers = sourceSchedulers;
}
 
Example 17
Source File: RecordServiceImpl.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
@Override
public boolean forwardEntry(final Record source, final Record.Builder builder, final String sourceColumn,
        final Schema.Entry entry) {
    switch (entry.getType()) {
    case INT:
        final OptionalInt optionalInt = source.getOptionalInt(sourceColumn);
        optionalInt.ifPresent(v -> builder.withInt(entry, v));
        return optionalInt.isPresent();
    case LONG:
        final OptionalLong optionalLong = source.getOptionalLong(sourceColumn);
        optionalLong.ifPresent(v -> builder.withLong(entry, v));
        return optionalLong.isPresent();
    case FLOAT:
        final OptionalDouble optionalFloat = source.getOptionalFloat(sourceColumn);
        optionalFloat.ifPresent(v -> builder.withFloat(entry, (float) v));
        return optionalFloat.isPresent();
    case DOUBLE:
        final OptionalDouble optionalDouble = source.getOptionalDouble(sourceColumn);
        optionalDouble.ifPresent(v -> builder.withDouble(entry, v));
        return optionalDouble.isPresent();
    case BOOLEAN:
        final Optional<Boolean> optionalBoolean = source.getOptionalBoolean(sourceColumn);
        optionalBoolean.ifPresent(v -> builder.withBoolean(entry, v));
        return optionalBoolean.isPresent();
    case STRING:
        final Optional<String> optionalString = source.getOptionalString(sourceColumn);
        optionalString.ifPresent(v -> builder.withString(entry, v));
        return optionalString.isPresent();
    case DATETIME:
        final Optional<ZonedDateTime> optionalDateTime = source.getOptionalDateTime(sourceColumn);
        optionalDateTime.ifPresent(v -> builder.withDateTime(entry, v));
        return optionalDateTime.isPresent();
    case BYTES:
        final Optional<byte[]> optionalBytes = source.getOptionalBytes(sourceColumn);
        optionalBytes.ifPresent(v -> builder.withBytes(entry, v));
        return optionalBytes.isPresent();
    case RECORD:
        final Optional<Record> optionalRecord = source.getOptionalRecord(sourceColumn);
        optionalRecord.ifPresent(v -> builder.withRecord(entry, v));
        return optionalRecord.isPresent();
    case ARRAY:
        final Optional<Collection<Object>> optionalArray = source.getOptionalArray(Object.class, sourceColumn);
        optionalArray.ifPresent(v -> builder.withArray(entry, v));
        return optionalArray.isPresent();
    default:
        throw new IllegalStateException("Unsupported entry type: " + entry);
    }
}
 
Example 18
Source File: HiveMetadata.java    From presto with Apache License 2.0 4 votes vote down vote up
@Override
public Optional<ConnectorPartitioningHandle> getCommonPartitioningHandle(ConnectorSession session, ConnectorPartitioningHandle left, ConnectorPartitioningHandle right)
{
    HivePartitioningHandle leftHandle = (HivePartitioningHandle) left;
    HivePartitioningHandle rightHandle = (HivePartitioningHandle) right;

    if (!leftHandle.getHiveTypes().equals(rightHandle.getHiveTypes())) {
        return Optional.empty();
    }
    if (leftHandle.getBucketingVersion() != rightHandle.getBucketingVersion()) {
        return Optional.empty();
    }
    if (leftHandle.getBucketCount() == rightHandle.getBucketCount()) {
        return Optional.of(leftHandle);
    }
    if (!isOptimizedMismatchedBucketCount(session)) {
        return Optional.empty();
    }

    int largerBucketCount = Math.max(leftHandle.getBucketCount(), rightHandle.getBucketCount());
    int smallerBucketCount = Math.min(leftHandle.getBucketCount(), rightHandle.getBucketCount());
    if (largerBucketCount % smallerBucketCount != 0) {
        // must be evenly divisible
        return Optional.empty();
    }
    if (Integer.bitCount(largerBucketCount / smallerBucketCount) != 1) {
        // ratio must be power of two
        return Optional.empty();
    }

    OptionalInt maxCompatibleBucketCount = min(leftHandle.getMaxCompatibleBucketCount(), rightHandle.getMaxCompatibleBucketCount());
    if (maxCompatibleBucketCount.isPresent() && maxCompatibleBucketCount.getAsInt() < smallerBucketCount) {
        // maxCompatibleBucketCount must be larger than or equal to smallerBucketCount
        // because the current code uses the smallerBucketCount as the common partitioning handle.
        return Optional.empty();
    }

    return Optional.of(new HivePartitioningHandle(
            leftHandle.getBucketingVersion(), // same as rightHandle.getBucketingVersion()
            smallerBucketCount,
            leftHandle.getHiveTypes(),
            maxCompatibleBucketCount));
}
 
Example 19
Source File: BroadcastRadioService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Finds next available index for newly loaded modules.
 */
private static int getNextId(@NonNull List<RadioManager.ModuleProperties> modules) {
    OptionalInt max = modules.stream().mapToInt(RadioManager.ModuleProperties::getId).max();
    return max.isPresent() ? max.getAsInt() + 1 : 0;
}
 
Example 20
Source File: PluginDefaultGroovyMethods.java    From groovy with Apache License 2.0 3 votes vote down vote up
/**
 * If a value is present in the {@code OptionalInt}, returns an {@code Optional}
 * consisting of the result of applying the given function to the value or else empty.
 * <pre class="groovyTestCase">
 * assert !OptionalInt.empty().mapToObj(x -&gt; new Object()).isPresent()
 * assert  OptionalInt.of(1234).mapToObj(x -&gt; new Object()).isPresent()
 * assert !OptionalInt.of(1234).mapToObj(x -&gt; null).isPresent()
 * assert  OptionalInt.of(1234).mapToObj(Integer::toString).get() == '1234'
 * </pre>
 *
 * @since 3.0.0
 */
public static <T> Optional<T> mapToObj(final OptionalInt self, final IntFunction<? extends T> mapper) {
    if (!self.isPresent()) {
        return Optional.empty();
    }
    return Optional.ofNullable(mapper.apply(self.getAsInt()));
}