Java Code Examples for java.util.OptionalInt#getAsInt()
The following examples show how to use
java.util.OptionalInt#getAsInt() .
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: TestBuckConfig.java From buck with Apache License 2.0 | 6 votes |
/** * @return the number of threads Buck should use for testing. This will use the test.threads * setting if it exists. Otherwise, this will use the build parallelization settings if not * configured. */ @Lazy public int getNumTestThreads() { OptionalInt numTestThreads = getDelegate().getInteger(TEST_SECTION_HEADER, "threads"); if (numTestThreads.isPresent()) { int num = numTestThreads.getAsInt(); if (num <= 0) { throw new HumanReadableException( "test.threads must be greater than zero (was " + num + ")"); } return num; } double ratio = getDelegate().getFloat(TEST_SECTION_HEADER, "thread_utilization_ratio").orElse(1.0F); if (ratio <= 0.0F) { throw new HumanReadableException( "thread_utilization_ratio must be greater than zero (was " + ratio + ")"); } return (int) Math.ceil(ratio * getDelegate().getView(BuildBuckConfig.class).getNumThreads()); }
Example 2
Source File: RawHttpHeaders.java From rawhttp with Apache License 2.0 | 6 votes |
/** * Include the given header in this builder. * * @param headerName header name * @param value header value * @return this */ public Builder with(String headerName, String value) { char[] upperCaseHeaderNameChars = new char[headerName.length()]; char[] headerNameChars = headerName.toCharArray(); for (int i = 0; i < headerNameChars.length; i++) { char c = headerNameChars[i]; if (validateHeaders && !FieldValues.isAllowedInTokens(c)) { throw new InvalidHttpHeader("Invalid header name (contains illegal character at index " + i + ")"); } upperCaseHeaderNameChars[i] = toUppercaseAscii(c); } final String upperCaseHeaderName = new String(upperCaseHeaderNameChars); if (validateHeaders) { OptionalInt illegalIndex = FieldValues.indexOfNotAllowedInHeaderValue(value); if (illegalIndex.isPresent()) { throw new InvalidHttpHeader("Invalid header value (contains illegal character at index " + illegalIndex.getAsInt() + ")"); } } headersByCapitalizedName.computeIfAbsent(upperCaseHeaderName, (ignore) -> new Header(new ArrayList<>(2))).values.add(value); headerNames.add(headerName); return this; }
Example 3
Source File: FreeIpaTestDto.java From cloudbreak with Apache License 2.0 | 6 votes |
private FreeIpaTestDto withInstanceGroupsEntity(Collection<InstanceGroupTestDto> instanceGroups, OptionalInt instanceGroupCount, OptionalInt instanceCountByGroup) { List<InstanceGroupRequest> instanceGroupRequests = instanceGroups.stream() .filter(instanceGroupTestDto -> "master".equals(instanceGroupTestDto.getRequest().getName())) .limit(1) .map(InstanceGroupTestDto::getRequest) .map(mapInstanceGroupRequest(instanceCountByGroup)) .collect(Collectors.toList()); if (instanceGroupCount.isPresent() && instanceGroupRequests.size() == 1) { InstanceGroupRequest reqToCopyDataFrom = instanceGroupRequests.get(0); instanceGroupRequests.clear(); for (int i = 0; i < instanceGroupCount.getAsInt(); ++i) { InstanceGroupRequest req = new InstanceGroupRequest(); req.setNodeCount(reqToCopyDataFrom.getNodeCount()); req.setName(reqToCopyDataFrom.getName() + i); req.setType(reqToCopyDataFrom.getType()); req.setInstanceTemplateRequest(reqToCopyDataFrom.getInstanceTemplate()); req.setSecurityGroup(reqToCopyDataFrom.getSecurityGroup()); instanceGroupRequests.add(req); } } getRequest().setInstanceGroups(instanceGroupRequests); return this; }
Example 4
Source File: TrivaGame.java From levelup-java-exercises with Apache License 2.0 | 5 votes |
/** * Method should generate random number based total number of questions * * @param numberOfQuestions * @return */ public static int getRandomQuestionNumber(int numberOfQuestions) { Random random = new Random(); OptionalInt questionNumber = random.ints(1, numberOfQuestions) .findFirst(); return questionNumber.getAsInt(); }
Example 5
Source File: DistributeShapes.java From latexdraw with GNU General Public License v3.0 | 5 votes |
/** * Distributes using bottom/top/left/right reference. */ private void distributeNotEq() { final List<ViewShape<?>> sortedSh = new ArrayList<>(); final List<Double> centres = new ArrayList<>(); for(final ViewShape<?> view : views) { final double x = switch(distribution) { case HORIZ_LEFT -> view.getBoundsInLocal().getMinX(); case HORIZ_MID -> (view.getBoundsInLocal().getMinX() + view.getBoundsInLocal().getMaxX()) / 2d; case HORIZ_RIGHT -> view.getBoundsInLocal().getMaxX(); case VERT_BOT -> view.getBoundsInLocal().getMaxY(); case VERT_MID -> (view.getBoundsInLocal().getMinY() + view.getBoundsInLocal().getMaxY()) / 2d; case VERT_TOP -> view.getBoundsInLocal().getMinY(); default -> 0; }; final OptionalInt res = IntStream.range(0, centres.size()).filter(index -> x < centres.get(index)).findFirst(); if(res.isPresent()) { final int i = res.getAsInt(); sortedSh.add(i, view); centres.add(i, x); }else { sortedSh.add(view); centres.add(x); } } final double gap = (centres.get(centres.size() - 1) - centres.get(0)) / (views.size() - 1); if(Distribution.isVertical(distribution)) { IntStream.range(1, sortedSh.size() - 1).forEach(i -> ((Shape) sortedSh.get(i).getUserData()). translate(0d, centres.get(0) + i * gap - centres.get(i))); }else { IntStream.range(1, sortedSh.size() - 1).forEach(i -> ((Shape) sortedSh.get(i).getUserData()). translate(centres.get(0) + i * gap - centres.get(i), 0d)); } }
Example 6
Source File: DetermineCommonAncestorTask.java From besu with Apache License 2.0 | 5 votes |
private CompletableFuture<Void> processHeaders( final AbstractPeerTask.PeerTaskResult<List<BlockHeader>> headersResult) { initialQuery = false; final List<BlockHeader> headers = headersResult.getResult(); if (headers.isEmpty()) { // Nothing to do return CompletableFuture.completedFuture(null); } final OptionalInt maybeAncestorNumber = BlockchainUtil.findHighestKnownBlockIndex(protocolContext.getBlockchain(), headers, false); // Means the insertion point is in the next header request. if (!maybeAncestorNumber.isPresent()) { maximumPossibleCommonAncestorNumber = headers.get(headers.size() - 1).getNumber() - 1L; return CompletableFuture.completedFuture(null); } final int ancestorNumber = maybeAncestorNumber.getAsInt(); commonAncestorCandidate = headers.get(ancestorNumber); if (ancestorNumber - 1 >= 0) { maximumPossibleCommonAncestorNumber = headers.get(ancestorNumber - 1).getNumber() - 1L; } minimumPossibleCommonAncestorNumber = headers.get(ancestorNumber).getNumber(); return CompletableFuture.completedFuture(null); }
Example 7
Source File: SearchCluster.java From vespa with Apache License 2.0 | 5 votes |
/** * Calculate whether a subset of nodes in a group has enough coverage */ public boolean isPartialGroupCoverageSufficient(OptionalInt knownGroupId, List<Node> nodes) { if (orderedGroups().size() == 1) { boolean sufficient = nodes.size() >= groupSize() - dispatchConfig.maxNodesDownPerGroup(); return sufficient; } if (knownGroupId.isEmpty()) { return false; } int groupId = knownGroupId.getAsInt(); Group group = groups().get(groupId); if (group == null) { return false; } int nodesInGroup = group.nodes().size(); long sumOfActiveDocuments = 0; int otherGroups = 0; for (Group g : orderedGroups()) { if (g.id() != groupId) { sumOfActiveDocuments += g.getActiveDocuments(); otherGroups++; } } long activeDocuments = 0; for (Node n : nodes) { activeDocuments += n.getActiveDocuments(); } long averageDocumentsInOtherGroups = sumOfActiveDocuments / otherGroups; return isGroupCoverageSufficient(nodes.size(), nodesInGroup, activeDocuments, averageDocumentsInOtherGroups); }
Example 8
Source File: DoctorReportHelper.java From buck with Apache License 2.0 | 5 votes |
private String prettyPrintExitCode(OptionalInt exitCode) { String result = "Exit code: " + (exitCode.isPresent() ? Integer.toString(exitCode.getAsInt()) : "Unknown"); if (exitCode.isPresent() && console.getAnsi().isAnsiTerminal()) { if (exitCode.getAsInt() == 0) { return console.getAnsi().asGreenText(result); } else { return console.getAnsi().asRedText(result); } } return result; }
Example 9
Source File: HStore.java From hbase with Apache License 2.0 | 5 votes |
/** * @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 10
Source File: LoadBalanceSession.java From nifi with Apache License 2.0 | 5 votes |
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 11
Source File: BasicInt.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 4 votes |
@Test(expectedExceptions=NoSuchElementException.class) public void testEmptyGet() { OptionalInt empty = OptionalInt.empty(); int got = empty.getAsInt(); }
Example 12
Source File: BasicInt.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
@Test(expectedExceptions=NoSuchElementException.class) public void testEmptyGet() { OptionalInt empty = OptionalInt.empty(); int got = empty.getAsInt(); }
Example 13
Source File: BasicInt.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
@Test(expectedExceptions=NoSuchElementException.class) public void testEmptyGet() { OptionalInt empty = OptionalInt.empty(); int got = empty.getAsInt(); }
Example 14
Source File: BasicInt.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
@Test(expectedExceptions=NoSuchElementException.class) public void testEmptyGet() { OptionalInt empty = OptionalInt.empty(); int got = empty.getAsInt(); }
Example 15
Source File: BasicInt.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 4 votes |
@Test(expectedExceptions=NoSuchElementException.class) public void testEmptyGet() { OptionalInt empty = OptionalInt.empty(); int got = empty.getAsInt(); }
Example 16
Source File: BGPOpenMessageParser.java From bgpcep with Eclipse Public License 1.0 | 4 votes |
private List<BgpParameters> parseParameters(final ByteBuf buffer, final int length) throws BGPDocumentedException { if (length == 0) { return ImmutableList.of(); } if (LOG.isTraceEnabled()) { LOG.trace("Started parsing of BGP parameter: {} length {}", ByteBufUtil.hexDump(buffer), length); } final int realLength; final OptionalInt extendedLength = extractExtendedLength(buffer, length); if (extendedLength.isPresent()) { realLength = extendedLength.getAsInt(); if (realLength < Values.UNSIGNED_BYTE_MAX_VALUE) { LOG.debug("Peer used Extended Optional Parameters Length to encode length {}", realLength); } } else { realLength = length; } // We have determined the real length, we can trim the buffer now if (buffer.readableBytes() > realLength) { buffer.writerIndex(buffer.readerIndex() + realLength); LOG.trace("Truncated BGP parameter buffer to length {}: {}", realLength, ByteBufUtil.hexDump(buffer)); } final int lengthSize = extendedLength.isPresent() ? 1 : 2; final List<BgpParameters> params = new ArrayList<>(); while (buffer.isReadable()) { final int paramType = buffer.readUnsignedByte(); final Optional<ParameterParser> parser = reg.findParser(paramType); if (!parser.isPresent()) { throw new BGPDocumentedException("Parameter " + paramType + " not supported", BGPError.OPT_PARAM_NOT_SUPPORTED); } if (buffer.readableBytes() <= lengthSize) { throw new BGPDocumentedException("Malformed parameter encountered (" + buffer.readableBytes() + " bytes left)", BGPError.UNSPECIFIC_OPEN_ERROR); } final int paramLength = extendedLength.isPresent() ? buffer.readUnsignedShort() : buffer.readUnsignedByte(); final ByteBuf paramBody = buffer.readSlice(paramLength); final BgpParameters param; try { param = parser.get().parseParameter(paramBody); } catch (final BGPParsingException e) { throw new BGPDocumentedException("Optional parameter not parsed", BGPError.UNSPECIFIC_OPEN_ERROR, e); } params.add(verifyNotNull(param)); } LOG.trace("Parsed BGP parameters: {}", params); return params; }
Example 17
Source File: Bank.java From luna with MIT License | 4 votes |
/** * Withdraws an item from the bank. * * @param bankIndex The index of the item to withdraw. * @param amount The amount to withdraw. * @return {@code true} if successful. */ public boolean withdraw(int bankIndex, int amount) { // Return if item doesn't exist or invalid amount. Item item = get(bankIndex); if (item == null || amount < 1) { return false; } // No free spaces in inventory. int remaining = inventory.computeRemainingSize(); if (remaining < 1) { inventory.fireCapacityExceededEvent(); return false; } // Get correct item identifier and amount to withdraw. int id = item.getId(); int existingAmount = item.getAmount(); amount = amount > existingAmount ? existingAmount : amount; if (withdrawAsNote) { OptionalInt notedId = item.getItemDef().getNotedId(); if (notedId.isPresent()) { id = notedId.getAsInt(); } else { player.sendMessage("This item cannot be withdrawn as a note."); } } // For non-stackable items, make the amount equal to free slots left if necessary. ItemDefinition withdrawItemDef = ItemDefinition.ALL.retrieve(id); if (!withdrawItemDef.isStackable()) { amount = amount > remaining ? remaining : amount; } // Withdraw the item. item = item.withAmount(amount); if (remove(item)) { Item withdrawItem = new Item(id, amount); return inventory.add(withdrawItem); } return false; }
Example 18
Source File: RaptorMetadata.java From presto with Apache License 2.0 | 4 votes |
private Optional<DistributionInfo> getOrCreateDistribution(Map<String, RaptorColumnHandle> columnHandleMap, Map<String, Object> properties) { OptionalInt bucketCount = getBucketCount(properties); List<RaptorColumnHandle> bucketColumnHandles = getBucketColumnHandles(getBucketColumns(properties), columnHandleMap); if (bucketCount.isPresent() && bucketColumnHandles.isEmpty()) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("Must specify '%s' along with '%s'", BUCKETED_ON_PROPERTY, BUCKET_COUNT_PROPERTY)); } if (bucketCount.isEmpty() && !bucketColumnHandles.isEmpty()) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("Must specify '%s' along with '%s'", BUCKET_COUNT_PROPERTY, BUCKETED_ON_PROPERTY)); } ImmutableList.Builder<Type> bucketColumnTypes = ImmutableList.builder(); for (RaptorColumnHandle column : bucketColumnHandles) { validateBucketType(column.getColumnType()); bucketColumnTypes.add(column.getColumnType()); } long distributionId; String distributionName = getDistributionName(properties); if (distributionName != null) { if (bucketColumnHandles.isEmpty()) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("Must specify '%s' along with '%s'", BUCKETED_ON_PROPERTY, DISTRIBUTION_NAME_PROPERTY)); } Distribution distribution = dao.getDistribution(distributionName); if (distribution == null) { if (bucketCount.isEmpty()) { throw new PrestoException(INVALID_TABLE_PROPERTY, "Distribution does not exist and bucket count is not specified"); } distribution = getOrCreateDistribution(distributionName, bucketColumnTypes.build(), bucketCount.getAsInt()); } distributionId = distribution.getId(); if (bucketCount.isPresent() && (distribution.getBucketCount() != bucketCount.getAsInt())) { throw new PrestoException(INVALID_TABLE_PROPERTY, "Bucket count must match distribution"); } if (!distribution.getColumnTypes().equals(bucketColumnTypes.build())) { throw new PrestoException(INVALID_TABLE_PROPERTY, "Bucket column types must match distribution"); } } else if (bucketCount.isPresent()) { String types = Distribution.serializeColumnTypes(bucketColumnTypes.build()); distributionId = dao.insertDistribution(null, types, bucketCount.getAsInt()); } else { return Optional.empty(); } shardManager.createBuckets(distributionId, bucketCount.getAsInt()); return Optional.of(new DistributionInfo(distributionId, bucketCount.getAsInt(), bucketColumnHandles)); }
Example 19
Source File: FixedSourcePartitionedScheduler.java From presto with Apache License 2.0 | 4 votes |
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 20
Source File: OptionalUtils.java From luna with MIT License | 2 votes |
/** * Determines if the optional's value is equal to {@code value}. * * @param optional The optional. * @param value The value to compare. * @return {@code true} if the two values are equal. */ public static boolean matches(OptionalInt optional, int value) { return optional.isPresent() && optional.getAsInt() == value; }