@Test public void serializeOptionalPrimitive() { final OptionalPrimitiveTestEntity entity = new OptionalPrimitiveTestEntity(); entity.d = OptionalDouble.of(69.5); entity.i = OptionalInt.of(69); entity.l = OptionalLong.of(69L); final VPackSlice vpack = vp.serialize(entity); assertThat(vpack, is(notNullValue())); assertThat(vpack.isObject(), is(true)); assertThat(vpack.get("d").isDouble(), is(true)); assertThat(vpack.get("d").getAsDouble(), is(69.5)); assertThat(vpack.get("i").isInteger(), is(true)); assertThat(vpack.get("i").getAsInt(), is(69)); assertThat(vpack.get("l").isInteger(), is(true)); assertThat(vpack.get("l").getAsLong(), is(69L)); }
StreamingMkvReader(boolean requirePath, Collection<EBMLTypeInfo> typeInfosToRead, ParserByteSource byteSource, OptionalInt maxContentBytesAtOnce) { this.requirePath = requirePath; typeInfosToRead.stream().forEach(t -> Validate.isTrue(t.getType() != EBMLTypeInfo.TYPE.MASTER)); this.typeInfosToRead = new HashSet(typeInfosToRead); this.byteSource = byteSource; this.mkvStreamReaderCallback = new MkvStreamReaderCallback(this.requirePath, elementFilter()); this.previousDataElement = Optional.empty(); MkvTypeInfoProvider typeInfoProvider = new MkvTypeInfoProvider(); try { typeInfoProvider.load(); } catch (IllegalAccessException e) { //TODO: fix this throw new RuntimeException("Could not load mkv info", e); } if (maxContentBytesAtOnce.isPresent()) { this.parser = new EBMLParser(typeInfoProvider, mkvStreamReaderCallback, maxContentBytesAtOnce.getAsInt()); } else { this.parser = new EBMLParser(typeInfoProvider, mkvStreamReaderCallback); } }
@Test public void frameStart() { final long[] payloads = {0, 126, 65536, Integer.MAX_VALUE + 1L}; final OptionalInt[] masks = {empty(), of(-1), of(0), of(0xCAFEBABE), of(Integer.MAX_VALUE), of(Integer.MIN_VALUE)}; for (boolean fin : new boolean[]{true, false}) { for (boolean rsv1 : new boolean[]{true, false}) { for (boolean rsv2 : new boolean[]{true, false}) { for (boolean rsv3 : new boolean[]{true, false}) { for (Opcode opcode : Opcode.values()) { for (long payloadLen : payloads) { for (OptionalInt mask : masks) { verifyFrameStart(fin, rsv1, rsv2, rsv3, opcode, payloadLen, mask); } } } } } } } System.out.println("Frames: " + frames + ", Total cases: " + cases); }
private void verify(boolean fin, boolean rsv1, boolean rsv2, boolean rsv3, Opcode opcode, long payloadLen, OptionalInt mask) { frames++; HeaderWriter writer = new HeaderWriter(); ByteBuffer expected = ByteBuffer.allocate(Frame.MAX_HEADER_SIZE_BYTES); writer.fin(fin).rsv1(rsv1).rsv2(rsv2).rsv3(rsv3).opcode(opcode).payloadLen(payloadLen); mask.ifPresentOrElse(writer::mask, writer::noMask); writer.write(expected); expected.flip(); verifyPermutations(expected, writer, () -> writer.fin(fin), () -> writer.rsv1(rsv1), () -> writer.rsv2(rsv2), () -> writer.rsv3(rsv3), () -> writer.opcode(opcode), () -> writer.payloadLen(payloadLen), () -> mask.ifPresentOrElse(writer::mask, writer::noMask)); }
private static OptionalInt findAffinityArg(Method meth) { OptionalInt affinityArg = OptionalInt.empty(); if (meth.getParameterCount() > 0) { for (int i = 0; i < meth.getParameterCount() && !affinityArg.isPresent(); i++) { Annotation[] annotations = meth.getParameterAnnotations()[i]; for (int j = 0; j < annotations.length; j++) { if (RpcAffinityKey.class.isAssignableFrom(annotations[j].annotationType())) { affinityArg = OptionalInt.of(i); break; } } } } return affinityArg; }
public List<CeremonyOfChaosMember> getWinners() { final List<CeremonyOfChaosMember> winners = new ArrayList<>(); //@formatter:off final OptionalInt winnerLifeTime = getMembers().values().stream() .mapToInt(CeremonyOfChaosMember::getLifeTime) .max(); if(winnerLifeTime.isPresent()) { getMembers().values().stream() .sorted(Comparator.comparingLong(CeremonyOfChaosMember::getLifeTime) .reversed() .thenComparingInt(CeremonyOfChaosMember::getScore) .reversed()) .filter(member -> member.getLifeTime() == winnerLifeTime.getAsInt()) .collect(Collectors.toCollection(() -> winners)); } //@formatter:on return winners; }
@Override protected void execute() { IntentExtensionService service = get(IntentExtensionService.class); OptionalInt length = service.getCompilers().keySet().stream() .mapToInt(s -> s.getName().length()) .max(); if (length.isPresent()) { service.getCompilers().entrySet().forEach(e -> { print("%-" + length.getAsInt() + "s\t%s", e.getKey().getName(), e.getValue().getClass().getName()); }); } else { print("There are no compilers registered."); } }
@Override public <C extends VPackSetupContext<C>> void setup(final C context) { context.registerDeserializer(Instant.class, VPackJdk8Deserializers.INSTANT); context.registerDeserializer(LocalDate.class, VPackJdk8Deserializers.LOCAL_DATE); context.registerDeserializer(LocalDateTime.class, VPackJdk8Deserializers.LOCAL_DATE_TIME); context.registerDeserializer(ZonedDateTime.class, VPackJdk8Deserializers.ZONED_DATE_TIME); context.registerDeserializer(OffsetDateTime.class, VPackJdk8Deserializers.OFFSET_DATE_TIME); context.registerDeserializer(ZoneId.class, VPackJdk8Deserializers.ZONE_ID); context.registerDeserializer(Optional.class, VPackJdk8Deserializers.OPTIONAL, true); context.registerDeserializer(OptionalDouble.class, VPackJdk8Deserializers.OPTIONAL_DOUBLE, true); context.registerDeserializer(OptionalInt.class, VPackJdk8Deserializers.OPTIONAL_INT, true); context.registerDeserializer(OptionalLong.class, VPackJdk8Deserializers.OPTIONAL_LONG, true); context.registerSerializer(Instant.class, VPackJdk8Serializers.INSTANT); context.registerSerializer(LocalDate.class, VPackJdk8Serializers.LOCAL_DATE); context.registerSerializer(LocalDateTime.class, VPackJdk8Serializers.LOCAL_DATE_TIME); context.registerSerializer(ZonedDateTime.class, VPackJdk8Serializers.ZONED_DATE_TIME); context.registerSerializer(OffsetDateTime.class, VPackJdk8Serializers.OFFSET_DATE_TIME); context.registerSerializer(ZoneId.class, VPackJdk8Serializers.ZONE_ID); context.registerSerializer(Optional.class, VPackJdk8Serializers.OPTIONAL); context.registerSerializer(OptionalDouble.class, VPackJdk8Serializers.OPTIONAL_DOUBLE); context.registerSerializer(OptionalInt.class, VPackJdk8Serializers.OPTIONAL_INT); context.registerSerializer(OptionalLong.class, VPackJdk8Serializers.OPTIONAL_LONG); }
@Test(groups = "unit") public void testEmpty() { OptionalInt empty = OptionalInt.empty(); OptionalInt present = OptionalInt.of(1); // empty assertTrue(empty.equals(empty)); assertTrue(empty.equals(OptionalInt.empty())); assertTrue(!empty.equals(present)); assertTrue(0 == empty.hashCode()); assertTrue(!empty.toString().isEmpty()); assertTrue(!empty.isPresent()); empty.ifPresent(v -> { fail(); }); AtomicBoolean emptyCheck = new AtomicBoolean(); empty.ifPresentOrElse(v -> fail(), () -> emptyCheck.set(true)); assertTrue(emptyCheck.get()); try { empty.ifPresentOrElse(v -> fail(), () -> { throw new ObscureException(); }); fail(); } catch (ObscureException expected) { } catch (AssertionError e) { throw e; } catch (Throwable t) { fail(); } assertEquals(2, empty.orElse(2)); assertEquals(2, empty.orElseGet(()-> 2)); }
static void use() { new ApplBuilder() .a(1) .b("") .c(1) .build(); new BbzBuilder(java.util.Optional.empty(), OptionalInt.empty()).build(); }
@Test public void testNumberToOptionalIntConverter(){ converter = new JavaOptionalConverterModule.NumberToOptionalIntConverter(); assertTrue(converter.canHandle(1l, TypeToken.of(OptionalInt.class))); assertFalse(converter.canHandle(1l, TypeToken.of(OptionalLong.class))); Object result = converter.convert(1l, TypeToken.of(OptionalInt.class)); assertTrue(result instanceof OptionalInt); assertEquals(1, ((OptionalInt) result).getAsInt()); }
@Override public OptionalInt extractResponseSequenceId(ByteBuf buffer) { try { TTransport inputTransport = new TChannelBufferInputTransport(buffer.duplicate()); TMessage message = protocolFactory.getProtocol(inputTransport).readMessageBegin(); return OptionalInt.of(message.getSequenceId()); } catch (Throwable ignored) { } return OptionalInt.empty(); }
@Override public final void load() { _classZones.clear(); _spawnTerritories.clear(); parseDatapackDirectory("data/zones", false); parseDatapackDirectory("data/zones/spawnZones", false); LOGGER.info(getClass().getSimpleName() + ": Loaded " + _classZones.size() + " zone classes and " + getSize() + " zones."); LOGGER.info(getClass().getSimpleName() + ": Loaded " + _spawnTerritories.size() + " NPC spawn territoriers."); final OptionalInt maxId = _classZones.values().stream().flatMap(map -> map.keySet().stream()).mapToInt(Integer.class::cast).filter(value -> value < 300000).max(); LOGGER.info(getClass().getSimpleName() + ": Last static id: " + maxId.getAsInt()); }
@SuppressWarnings("unchecked") public JsonPrinter addJavaHandlers() { return this .addObjectClassHandler(Enum.class, e -> e.name()) .addObjectClassHandler(Optional.class, o -> o.orElse(null)) .addObjectClassHandler(OptionalInt.class, i -> i.isPresent() ? i.getAsInt() : null) .addObjectClassHandler(OptionalDouble.class, i -> i.isPresent() ? i.getAsDouble() : null) .addObjectClassHandler(OptionalLong.class, i -> i.isPresent() ? i.getAsLong() : null) .addObjectClassHandler(Class.class, c -> c.getName()) .addObjectClassHandler(Path.class, p -> p.toString().replace('\\', '/')) .addObjectClassHandler(File.class, f -> f.toString().replace('\\', '/')); }
public void testFindLast_intStream() { Truth.assertThat(findLast(IntStream.of())).isEqualTo(OptionalInt.empty()); Truth.assertThat(findLast(IntStream.of(1, 2, 3, 4, 5))).isEqualTo(OptionalInt.of(5)); // test with a large, not-subsized Spliterator List<Integer> list = IntStream.rangeClosed(0, 10000).boxed().collect(Collectors.toCollection(LinkedList::new)); Truth.assertThat(findLast(list.stream().mapToInt(i -> i))).isEqualTo(OptionalInt.of(10000)); // no way to find out the stream is empty without walking its spliterator Truth.assertThat(findLast(list.stream().mapToInt(i -> i).filter(i -> i < 0))) .isEqualTo(OptionalInt.empty()); }
@Test public void canDeserializeCorrectly() throws IOException, ConfigurationException { final HikariDataSourceFactory factory = new YamlConfigurationFactory<>(HikariDataSourceFactory.class, BaseValidator.newValidator(), Jackson.newObjectMapper(), "dw") .build(new ResourceConfigurationSourceProvider(), "config.yaml"); assertThat(factory.getUser()).isEqualTo("nick"); assertThat(factory.getPassword()).isEqualTo("nickss"); assertThat(factory.getDatasourceClassName()).isEqualTo("org.postgresql.ds.PGSimpleDataSource"); assertThat(factory.getProperties()).containsExactly(entry("databaseName", "postgres")); assertThat(factory.getMinSize()).isEqualTo(OptionalInt.empty()); assertThat(factory.getMaxSize()).isEqualTo(12); assertThat(factory.isAutoCommit()).isTrue(); }
public int getLocalValueIndex(IQueueValue<?> value) throws QueueModelException { OptionalInt indexOpt = IntStream.range(0, localValues.size()).filter(i -> value.equals(localValues.get(i))).findFirst(); try { return indexOpt.getAsInt(); } catch (NoSuchElementException nseEx) { throw new QueueModelException(nseEx); } }
private void verifyFrameStart(boolean fin, boolean rsv1, boolean rsv2, boolean rsv3, Opcode opcode, long payloadLen, OptionalInt mask) { frames++; Frame.HeaderWriter w = new Frame.HeaderWriter(); ByteBuffer h = ByteBuffer.allocate(Frame.MAX_HEADER_SIZE_BYTES); w.fin(fin).rsv1(rsv1).rsv2(rsv2).rsv3(rsv3).opcode(opcode).payloadLen(payloadLen); mask.ifPresentOrElse(w::mask, w::noMask); w.write(h); h.flip(); forEachBufferPartition(h, buffers -> { cases++; Frame.Reader r = new Frame.Reader(); MockConsumer c = new MockConsumer(); for (ByteBuffer b : buffers) { r.readFrame(b, c); } assertEquals(fin, c.fin()); assertEquals(rsv1, c.rsv1()); assertEquals(rsv2, c.rsv2()); assertEquals(rsv3, c.rsv3()); assertEquals(opcode, c.opcode()); assertEquals(mask.isPresent(), c.mask()); assertEquals(payloadLen, c.payloadLen()); assertEquals(mask, c.maskingKey()); assertEquals(payloadLen == 0, c.isEndFrame()); }); }
@Test public void testNumberToOptionalLongConverter() { converter = new JavaOptionalConverterModule.NumberToOptionalLongConverter(); assertTrue(converter.canHandle(1f, TypeToken.of(OptionalLong.class))); assertFalse(converter.canHandle(1f, TypeToken.of(OptionalInt.class))); Object result = converter.convert(1f, TypeToken.of(OptionalLong.class)); assertTrue(result instanceof OptionalLong); assertEquals(1l, ((OptionalLong) result).getAsLong()); }
@Override public OptionalInt getValue(final JavaType type, final ResultSet rs, final int columnIndex, final PropertyMapperManager mapperManager) throws SQLException { int value = rs.getInt(columnIndex); if (!rs.wasNull()) { return OptionalInt.of(value); } else { return OptionalInt.empty(); } }
/** * 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(); } }; }
@Override public final OptionalInt min() { return reduce(Math::min); }
StreamingMkvReader(boolean requirePath, Collection<EBMLTypeInfo> typeInfosToRead, ParserByteSource byteSource) { this(requirePath, typeInfosToRead, byteSource, OptionalInt.empty()); }
public void testStream_optionalInt() { assertThat(stream(java.util.OptionalInt.empty())).isEmpty(); assertThat(stream(java.util.OptionalInt.of(5))).containsExactly(5); }
@Override public OptionalInt get() { return hasValue ? OptionalInt.of(value) : null; }
@Test(expectedExceptions=NoSuchElementException.class) public void testEmptyGet() { OptionalInt empty = OptionalInt.empty(); int got = empty.getAsInt(); }
@Value.Default default OptionalInt value() { return OptionalInt.empty(); }
@Value.Parameter OptionalInt i1();
@Builder.Factory public static int appl(Optional<Integer> a, java.util.Optional<String> b, java.util.OptionalInt c) { return a.hashCode() + b.hashCode() + c.hashCode(); }
@Builder.Factory public static int bbz(@Builder.Parameter java.util.Optional<String> b, @Builder.Parameter java.util.OptionalInt c) { return b.hashCode() + c.hashCode(); }
@Value.Parameter OptionalInt a();
public InputStreamMessageContent(Supplier<InputStream> streamSupplier, OptionalInt size, MessageContentEncoding encoding) { this.streamSupplier = streamSupplier; this.size = size; this.encoding = encoding; }
public void testIntMinMax() { assertEquals(IntStream.empty().min(), OptionalInt.empty()); assertEquals(IntStream.empty().max(), OptionalInt.empty()); assertEquals(1, IntStream.range(1, 1001).min().getAsInt()); assertEquals(1000, IntStream.range(1, 1001).max().getAsInt()); }
@Override public OptionalInt size() { return OptionalInt.of(size); }
private OptionalInt getPropertyValue(final String cacheName, final String propertySuffix) { return stroomPropertyService.getIntProperty(buildKey(cacheName, propertySuffix)); }
public OptionalInt getAdvertisedPort() { return advertisedPort; }
public OptionalIntExample(Integer value) { this.value = OptionalInt.of(value); }
@Test public void givenIntegerJSON_shouldDeserialiseToOptionalInt() { assertThat(jsonb.fromJson("{\"value\":10}", OptionalIntExample.class)) .hasFieldOrPropertyWithValue("value", OptionalInt.of(10)); }
@Override public final OptionalInt findFirst() { return evaluate(FindOps.makeInt(true)); }