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

The following examples show how to use java.util.OptionalInt#empty() . 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: SystemSessionProperties.java    From presto with Apache License 2.0 5 votes vote down vote up
public static OptionalInt getMaxDriversPerTask(Session session)
{
    Integer value = session.getSystemProperty(MAX_DRIVERS_PER_TASK, Integer.class);
    if (value == null) {
        return OptionalInt.empty();
    }
    return OptionalInt.of(value);
}
 
Example 2
Source File: BasicInt.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test(groups = "unit")
    public void testPresent() {
    OptionalInt empty = OptionalInt.empty();
    OptionalInt present = OptionalInt.of(1);

    // present
    assertTrue(present.equals(present));
    assertFalse(present.equals(OptionalInt.of(0)));
    assertTrue(present.equals(OptionalInt.of(1)));
    assertFalse(present.equals(empty));
    assertTrue(Integer.hashCode(1) == present.hashCode());
    assertFalse(present.toString().isEmpty());
    assertTrue(-1 != present.toString().indexOf(Integer.toString(present.getAsInt()).toString()));
    assertEquals(1, present.getAsInt());
    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 3
Source File: RaptorSplit.java    From presto with Apache License 2.0 5 votes vote down vote up
public RaptorSplit(
        UUID shardUuid,
        List<HostAddress> addresses,
        OptionalLong transactionId)
{
    this(ImmutableSet.of(shardUuid), OptionalInt.empty(), addresses, transactionId);
}
 
Example 4
Source File: AutoValueOrOneOfProcessor.java    From auto with Apache License 2.0 5 votes vote down vote up
private static OptionalInt nullableAnnotationIndex(List<? extends AnnotationMirror> annotations) {
  for (int i = 0; i < annotations.size(); i++) {
    if (isNullable(annotations.get(i))) {
      return OptionalInt.of(i);
    }
  }
  return OptionalInt.empty();
}
 
Example 5
Source File: ExtraRuntimeOptions.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
private static OptionalInt maybeInt(String name) {
    var value = getValue(name);
    if (value == null) return OptionalInt.empty();
    try {
        return OptionalInt.of(Integer.parseInt(value));
    } catch (NumberFormatException e) {
        return OptionalInt.empty();
    }
}
 
Example 6
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 7
Source File: WarpDb.java    From warpdb with Apache License 2.0 5 votes vote down vote up
public OptionalInt queryForInt(String sql, Object... args) {
	log.debug("SQL: " + sql);
	Number number = jdbcTemplate.query(sql, args, NUMBER_RESULT_SET);
	if (number == null) {
		return OptionalInt.empty();
	}
	return OptionalInt.of(number.intValue());
}
 
Example 8
Source File: BuildLogHelper.java    From buck with Apache License 2.0 4 votes vote down vote up
private BuildLogEntry newBuildLogEntry(Path logFile) throws IOException {

    Optional<Path> machineReadableLogFile =
        Optional.of(logFile.resolveSibling(BuckConstant.BUCK_MACHINE_LOG_FILE_NAME))
            .filter(path -> projectFilesystem.isFile(path));

    Optional<Integer> exitCode =
        machineReadableLogFile.flatMap(
            machineFile -> readObjectFieldFromLog(machineFile, PREFIX_EXIT_CODE, "exitCode"));

    Optional<InvocationInfo> invocationInfo =
        machineReadableLogFile.flatMap(
            machineLogFile ->
                readObjectFromLog(
                    machineLogFile,
                    PREFIX_INVOCATION_INFO,
                    new TypeReference<InvocationInfo>() {}));

    Optional<List<String>> commandArgs =
        invocationInfo.flatMap(iInfo -> Optional.ofNullable(iInfo.getUnexpandedCommandArgs()));
    Optional<List<String>> expandedCommandArgs =
        invocationInfo.flatMap(iInfo -> Optional.ofNullable(iInfo.getCommandArgs()));

    Optional<BuildId> buildId =
        machineReadableLogFile.map(
            machineLogFile ->
                invocationInfo.map(InvocationInfo::getBuildId).orElse(new BuildId("unknown")));

    Optional<Long> startTimestampMs = invocationInfo.map(InvocationInfo::getTimestampMillis);

    Optional<Long> finishTimestampMs =
        machineReadableLogFile.flatMap(
            machineFile -> readObjectFieldFromLog(machineFile, PREFIX_BUILD_FINISHED, "timestamp"));

    OptionalInt buildTimeMs =
        finishTimestampMs.isPresent() && startTimestampMs.isPresent()
            ? OptionalInt.of((int) (finishTimestampMs.get() - startTimestampMs.get()))
            : OptionalInt.empty();

    Optional<Path> ruleKeyLoggerFile =
        Optional.of(logFile.getParent().resolve(BuckConstant.RULE_KEY_LOGGER_FILE_NAME))
            .filter(path -> projectFilesystem.isFile(path));

    Optional<Path> ruleKeyDiagKeysFile =
        Optional.of(logFile.getParent().resolve(BuckConstant.RULE_KEY_DIAG_KEYS_FILE_NAME))
            .filter(path -> projectFilesystem.isFile(path));

    Optional<Path> ruleKeyDiagGraphFile =
        Optional.of(logFile.getParent().resolve(BuckConstant.RULE_KEY_DIAG_GRAPH_FILE_NAME))
            .filter(path -> projectFilesystem.isFile(path));

    Optional<Path> traceFile =
        projectFilesystem.asView()
            .getFilesUnderPath(logFile.getParent(), EnumSet.of(FileVisitOption.FOLLOW_LINKS))
            .stream()
            .filter(input -> input.toString().endsWith(".trace"))
            .findFirst();

    Optional<Path> configJsonFile =
        Optional.of(logFile.resolveSibling(BuckConstant.CONFIG_JSON_FILE_NAME))
            .filter(projectFilesystem::isFile);

    Optional<Path> fixSpecFile =
        Optional.of(logFile.resolveSibling(BuckConstant.BUCK_FIX_SPEC_FILE_NAME))
            .filter(projectFilesystem::isFile);

    return BuildLogEntry.of(
        logFile,
        buildId,
        commandArgs,
        expandedCommandArgs,
        exitCode.map(OptionalInt::of).orElseGet(OptionalInt::empty),
        buildTimeMs,
        ruleKeyLoggerFile,
        machineReadableLogFile,
        ruleKeyDiagKeysFile,
        ruleKeyDiagGraphFile,
        traceFile,
        configJsonFile,
        fixSpecFile,
        projectFilesystem.getFileSize(logFile),
        Date.from(projectFilesystem.getLastModifiedTime(logFile).toInstant()));
  }
 
Example 9
Source File: ReduceOps.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Constructs a {@code TerminalOp} that implements a functional reduce on
 * {@code int} values, producing an optional integer result.
 *
 * @param operator the combining function
 * @return a {@code TerminalOp} implementing the reduction
 */
public static TerminalOp<Integer, OptionalInt>
makeInt(IntBinaryOperator operator) {
    Objects.requireNonNull(operator);
    class ReducingSink
            implements AccumulatingSink<Integer, OptionalInt, ReducingSink>, Sink.OfInt {
        private boolean empty;
        private int state;

        public void begin(long size) {
            empty = true;
            state = 0;
        }

        @Override
        public void accept(int t) {
            if (empty) {
                empty = false;
                state = t;
            }
            else {
                state = operator.applyAsInt(state, t);
            }
        }

        @Override
        public OptionalInt get() {
            return empty ? OptionalInt.empty() : OptionalInt.of(state);
        }

        @Override
        public void combine(ReducingSink other) {
            if (!other.empty)
                accept(other.state);
        }
    }
    return new ReduceOp<Integer, OptionalInt, ReducingSink>(StreamShape.INT_VALUE) {
        @Override
        public ReducingSink makeSink() {
            return new ReducingSink();
        }
    };
}
 
Example 10
Source File: Uuid2PosIntTable.java    From helper with MIT License 4 votes vote down vote up
@Override
protected OptionalInt emptyOptional() {
    return OptionalInt.empty();
}
 
Example 11
Source File: FreeIpaClientException.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public FreeIpaClientException(String message, Throwable cause) {
    super(message, cause);
    statusCode = OptionalInt.empty();
}
 
Example 12
Source File: HealthInfo.java    From vespa with Apache License 2.0 4 votes vote down vote up
static HealthInfo fromHealthStatusCode(String healthStatusCode) {
    return new HealthInfo(Optional.empty(), OptionalInt.empty(), Optional.of(healthStatusCode));
}
 
Example 13
Source File: ReduceOps.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Constructs a {@code TerminalOp} that implements a functional reduce on
 * {@code int} values, producing an optional integer result.
 *
 * @param operator the combining function
 * @return a {@code TerminalOp} implementing the reduction
 */
public static TerminalOp<Integer, OptionalInt>
makeInt(IntBinaryOperator operator) {
    Objects.requireNonNull(operator);
    class ReducingSink
            implements AccumulatingSink<Integer, OptionalInt, ReducingSink>, Sink.OfInt {
        private boolean empty;
        private int state;

        public void begin(long size) {
            empty = true;
            state = 0;
        }

        @Override
        public void accept(int t) {
            if (empty) {
                empty = false;
                state = t;
            }
            else {
                state = operator.applyAsInt(state, t);
            }
        }

        @Override
        public OptionalInt get() {
            return empty ? OptionalInt.empty() : OptionalInt.of(state);
        }

        @Override
        public void combine(ReducingSink other) {
            if (!other.empty)
                accept(other.state);
        }
    }
    return new ReduceOp<Integer, OptionalInt, ReducingSink>(StreamShape.INT_VALUE) {
        @Override
        public ReducingSink makeSink() {
            return new ReducingSink();
        }
    };
}
 
Example 14
Source File: OptionalUtils.java    From dalesbred with MIT License 4 votes vote down vote up
public static @NotNull OptionalInt optionalIntOfNullable(@Nullable Integer v) {
    return v != null ? OptionalInt.of(v) : OptionalInt.empty();
}
 
Example 15
Source File: BasicInt.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NoSuchElementException.class)
public void testEmptyGet() {
    OptionalInt empty = OptionalInt.empty();

    int got = empty.getAsInt();
}
 
Example 16
Source File: StreamingMkvReader.java    From amazon-kinesis-video-streams-parser-library with Apache License 2.0 4 votes vote down vote up
StreamingMkvReader(boolean requirePath,
        Collection<EBMLTypeInfo> typeInfosToRead,
        ParserByteSource byteSource) {
    this(requirePath, typeInfosToRead, byteSource, OptionalInt.empty());
}
 
Example 17
Source File: ReservationWrapper.java    From robozonky with Apache License 2.0 4 votes vote down vote up
@Override
public OptionalInt getLongestDpd() {
    return OptionalInt.empty();
}
 
Example 18
Source File: OptionalIntExample.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void optional_int_orElse() {
	
	OptionalInt optionalInt = OptionalInt.empty();
	
	assertEquals(77, optionalInt.orElse(77), 0);
}
 
Example 19
Source File: CharacterHit.java    From RichTextFX with BSD 2-Clause "Simplified" License 2 votes vote down vote up
/**
 * Returns a {@link CharacterHit} for cases where the insertion occurs outside the bounds of some visible entity
 * (e.g. the area, the paragraph in an area, the line in a paragraph)
 */
public static CharacterHit insertionAt(int insertionIndex) {
    return new CharacterHit(OptionalInt.empty(), insertionIndex);
}
 
Example 20
Source File: FutureValueNotional.java    From Strata with Apache License 2.0 2 votes vote down vote up
/**
 * Gets the number of days in the calculation period.
 * <p>
 * This defines the number of days from the adjusted start date to the adjusted end date
 * as calculated by the day count.
 * @return the optional value of the property, not null
 */
public OptionalInt getDayCountDays() {
  return dayCountDays != null ? OptionalInt.of(dayCountDays) : OptionalInt.empty();
}