@Test public void equals() { ImmutableJdkOptionals o1 = ImmutableJdkOptionals.of() .withV2("v2") .withI1(1) .withD1(1.0); ImmutableJdkOptionals o2 = ImmutableJdkOptionals.of( Optional.of("v2"), OptionalInt.of(1), OptionalLong.empty(), OptionalDouble.of(1.0)); check(o1).is(o2); check(o1.hashCode()).is(o2.hashCode()); }
@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); }
private ByteArrayOutputStream setupTestForMasterElementWithOneChildAndElementSizedBasedTermination() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte [] EBML_element_rawbytes = writeElement(EBML_id_bytes, wrapByte(0x84), outputStream); byte [] EBMLVersion_element_rawbytes = writeElement(EBMLVersion_id_bytes, wrapByte(0x81), outputStream); byte [] EBMLVersion_data_bytes = new byte [] { (byte) 0x4}; outputStream.write(EBMLVersion_data_bytes); parserCallback.setCheckExpectedCallbacks(true); parserCallback.expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .typeInfo(TestEBMLTypeInfoProvider.EBML) .elementCount(0) .numBytes(OptionalLong.of(4)) .bytes(EBML_element_rawbytes) .build()); addExpectedCallbacksForEBMLVersion(EBMLVersion_element_rawbytes, EBMLVersion_data_bytes, 1) .expectCallback(createExpectedCallbackForEndEBML(0)); return outputStream; }
@Test(timeout = 10000) @DirtiesContext public void testSerialHeader() throws Exception { UUID id = UUID.randomUUID(); uut.publish(Fact.of("{\"id\":\"" + id + "\",\"type\":\"someType\",\"ns\":\"default\",\"aggIds\":[\"" + id + "\"]}", "{}")); UUID id2 = UUID.randomUUID(); uut.publish(Fact.of("{\"id\":\"" + id2 + "\",\"type\":\"someType\",\"meta\":{\"foo\":\"bar\"},\"ns\":\"default\",\"aggIds\":[\"" + id2 + "\"]}", "{}")); OptionalLong serialOf = uut.serialOf(id); assertTrue(serialOf.isPresent()); Fact f = uut.fetchById(id).get(); Fact fact2 = uut.fetchById(id2).get(); assertEquals(serialOf.getAsLong(), f.serial()); assertTrue(f.before(fact2)); }
@Test public void test02() throws Exception { try (SqlAgent agent = config.agent()) { agent.required(() -> { PropertyMapperTestEntity test1 = new PropertyMapperTestEntity(1); test1.intValue = OptionalInt.empty(); test1.longValue = OptionalLong.empty(); test1.doubleValue = OptionalDouble.empty(); test1.dateValue = null; test1.datetimeValue = null; test1.enumValue = null; test1.bigIntValue = null; agent.insert(test1); PropertyMapperTestEntity data = agent.find(PropertyMapperTestEntity.class, 1).orElse(null); assertThat(data, is(test1)); }); } }
private ByteArrayOutputStream setupTestForMasterElementWithOneChildAndUnknownlength() 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); outputStream.write(EBML_ZERO_LENGTH_RAWBYTES); parserCallback.setCheckExpectedCallbacks(true); parserCallback.expectCallback(createExpectedCallbackForStartOfEBMLUnknownLength(EBML_element_rawbytes)); addExpectedCallbacksForEBMLVersion(EBMLVersion_element_rawbytes, EBMLVersion_data_bytes, 1) .expectCallback(createExpectedCallbackForEndEBML(0)) .expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .elementCount(2) .typeInfo(TestEBMLTypeInfoProvider.EBML) .numBytes(OptionalLong.of(0)) .bytes(EBML_ZERO_LENGTH_RAWBYTES) .build()) .expectCallback(createExpectedCallbackForEndEBML(2)); return outputStream; }
@Nullable private BodyReader createBodyReader(InputStream inputStream, RawHttpHeaders headers, boolean hasBody) { @Nullable BodyReader bodyReader; if (hasBody) { @Nullable Long bodyLength = null; OptionalLong headerLength = parseContentLength(headers); if (headerLength.isPresent()) { bodyLength = headerLength.getAsLong(); } BodyType bodyType = getBodyType(headers, bodyLength); bodyReader = new LazyBodyReader(bodyType, inputStream, bodyLength, options.allowNewLineWithoutReturn()); } else { bodyReader = null; } return bodyReader; }
void use() { UsingAllOptionals value = ImmutableUsingAllOptionals.builder() .v1(1) .v2(2) .i1(OptionalInt.of(1)) .d1(1.1) .l1(OptionalLong.empty()) .jso(javaslang.control.Option.none()) .build(); Objects.equals(value.v1().get(), value.v2().get()); Objects.hash(value.i1(), value.l1(), value.d1()); }
private OptionalLong maybeMaxTickTime() { return tickQuoteRepository .getAll() .values() .stream() .map(TickQuote::tick) .mapToLong(ITick::getTime) .max(); }
@Nonnull public static OptionalLong parseLong(@Nonnull String s) { try { return OptionalLong.of(Long.parseLong(s)); } catch (NumberFormatException e) { return OptionalLong.empty(); } }
default OptionalLong getLongProperty(String name) { Optional<String> optValue = getProperty(name); if (optValue.isPresent()) { return OptionalLong.of(Long.parseLong(optValue.get())); } else { return OptionalLong.empty(); } }
@SuppressWarnings({"unchecked", "OptionalUsedAsFieldOrParameterType"}) private <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, OptionalLong timeoutNanos) throws InterruptedException { Objects.requireNonNull(tasks, "'tasks' should not be 'null'."); CompletableFuture[] futures = new CompletableFuture[tasks.size()]; int index = 0; for (Callable<T> task : tasks) { futures[index++] = submit(task); } boolean completeWithTimeout = timeoutNanos.isPresent(); try { if (completeWithTimeout) { CompletableFuture.allOf(futures) .get(timeoutNanos.getAsLong(), TimeUnit.NANOSECONDS); completeWithTimeout = false; } else { CompletableFuture.allOf(futures) .get(); } } catch (ExecutionException | TimeoutException ignored) { logger.error("Got exception while waiting for completion of '{}' tasks.", tasks.size(), ignored); } if (completeWithTimeout) { TimeoutException timeoutException = new TimeoutException( "Got timeout after '" + timeoutNanos.getAsLong() + "' nanos." ); for (CompletableFuture future : futures) { future.completeExceptionally(timeoutException); } } return Arrays.stream(futures) .map(future -> (Future<T>) future) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); }
@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_longStream() { Truth.assertThat(findLast(LongStream.of())).isEqualTo(OptionalLong.empty()); Truth.assertThat(findLast(LongStream.of(1, 2, 3, 4, 5))).isEqualTo(OptionalLong.of(5)); // test with a large, not-subsized Spliterator List<Long> list = LongStream.rangeClosed(0, 10000).boxed().collect(Collectors.toCollection(LinkedList::new)); Truth.assertThat(findLast(list.stream().mapToLong(i -> i))).isEqualTo(OptionalLong.of(10000)); // no way to find out the stream is empty without walking its spliterator Truth.assertThat(findLast(list.stream().mapToLong(i -> i).filter(i -> i < 0))) .isEqualTo(OptionalLong.empty()); }
@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 void onPartialContent(EBMLElementMetaData elementMetaData, ParserBulkByteSource bulkByteSource, int bytesToRead) { contentBuffer.clear(); bulkByteSource.readBytes(contentBuffer, bytesToRead); contentBuffer.flip(); long elementNumber = elementMetaData.getElementNumber(); EBMLTypeInfo typeInfo = elementMetaData.getTypeInfo(); log.info("On PartialContent: elementCount " + elementNumber + " typeInfo " + typeInfo.toString() + " bytesToRead " + bytesToRead); if (log.isDebugEnabled()) { log.debug("Rawbytes { " + hexDump(contentBuffer) + " }"); } dumpByteBufferToRawOutput(contentBuffer); if (checkExpectedCallbacks) { CallbackDescription expectedCallback = callbackDescriptions.remove(); CallbackDescription actualCallback = CallbackDescription.builder() .callbackType(CallbackDescription.CallbackType.CONTENT) .elementCount(elementNumber) .typeInfo(typeInfo) .numBytes(OptionalLong.of(bytesToRead)) .bytes(convertToByteArray(contentBuffer)) .build(); Validate.isTrue(compareCallbackDescriptions(expectedCallback, actualCallback), getMismatchExpectationMessage(expectedCallback, actualCallback)); } }
@Test public void testStringToOptionalLongConverter() { converter = new JavaOptionalConverterModule.StringToOptionalLongConverter(); assertTrue(converter.canHandle("1", TypeToken.of(OptionalLong.class))); assertFalse(converter.canHandle("1", TypeToken.of(OptionalInt.class))); Object result = converter.convert("1", TypeToken.of(OptionalLong.class)); assertTrue(result instanceof OptionalLong); assertEquals(1, ((OptionalLong) result).getAsLong()); }
private TestEBMLParserCallback.CallbackDescription createExpectedCallbackForStartOfEBMLUnknownLength(byte[] EBML_element_rawbytes) { return TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .typeInfo(TestEBMLTypeInfoProvider.EBML) .elementCount(0) .numBytes(OptionalLong.of(EBMLParserInternalElement.UNKNOWN_LENGTH_VALUE)) .bytes(EBML_element_rawbytes) .build(); }
default OptionalLong getVersion(@NonNull final String elementId) { return getField(elementId, "_version").map(GetField::getValue).map(Object::toString).map(Long::parseLong) .map(OptionalLong::of).orElse(OptionalLong.empty()); }
@NonNull public OptionalLong fromProto(@NonNull MSG_OptionalSerial serialOf) { // note that an unsigned is used to transport the serial. Serials MUST be >0 if (serialOf.getPresent() && serialOf.getSerial() > 0) { return OptionalLong.of(serialOf.getSerial()); } else { return OptionalLong.empty(); } }
@Override public OptionalLong serialOf(UUID l) { // hilariously inefficient for (Map.Entry<Long, Fact> e : store.entrySet()) { if (l.equals(e.getValue().id())) { return OptionalLong.of(e.getKey().longValue()); } } return OptionalLong.empty(); }
@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); }
@Override public OptionalLong getValue(final JavaType type, final ResultSet rs, final int columnIndex, final PropertyMapperManager mapperManager) throws SQLException { long value = rs.getLong(columnIndex); if (!rs.wasNull()) { return OptionalLong.of(value); } else { return OptionalLong.empty(); } }
private void setExpectedCallbacksForEBMLElement() { parserCallback.setCheckExpectedCallbacks(true); parserCallback.expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .elementCount(0) .typeInfo(TestEBMLTypeInfoProvider.EBML) .numBytes(OptionalLong.of(0)) .bytes(EBML_ZERO_LENGTH_RAWBYTES) .build()) .expectCallback(createExpectedCallbackForEndEBML(0)); }
@Test public void testNumberToOptionalDoubleConverter() { converter = new JavaOptionalConverterModule.NumberToOptionalDoubleConverter(); assertTrue(converter.canHandle(1l, TypeToken.of(OptionalDouble.class))); assertFalse(converter.canHandle(1l, TypeToken.of(OptionalLong.class))); Object result = converter.convert(1l, TypeToken.of(OptionalDouble.class)); assertTrue(result instanceof OptionalDouble); assertEquals(1, ((OptionalDouble) result).getAsDouble(), 0.01); }
@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()); }
@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)); }
@Test public void should_verify_an_actual_optional_long_is_conform_to_an_expected_result() { assertThat(resultOf(() -> { gwtMock.whenAnEventHappensInRelationToAnActionOfTheConsumer(); return OptionalLong.of(123); }).isPresent()).hasSameClassAs(assertThat(OptionalLong.empty())); }
@Test public void testStringToOptionalDoubleConverter() { converter = new JavaOptionalConverterModule.StringToOptionalDoubleConverter(); assertTrue(converter.canHandle("1", TypeToken.of(OptionalDouble.class))); assertFalse(converter.canHandle("1", TypeToken.of(OptionalLong.class))); Object result = converter.convert("1", TypeToken.of(OptionalDouble.class)); assertTrue(result instanceof OptionalDouble); assertEquals(1, ((OptionalDouble) result).getAsDouble(), 0.01); }
@Test(groups = "unit") public void testEmpty() { OptionalLong empty = OptionalLong.empty(); OptionalLong present = OptionalLong.of(1); // empty assertTrue(empty.equals(empty)); assertTrue(empty.equals(OptionalLong.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)); }
@Override public void onStartElement(EBMLElementMetaData elementMetaData, long elementDataSize, ByteBuffer idAndSizeRawBytes, ElementPathSupplier pathSupplier) { long elementNumber = elementMetaData.getElementNumber(); EBMLTypeInfo typeInfo = elementMetaData.getTypeInfo(); log.info("On Start: elementNumber " + elementNumber + " typeInfo " + typeInfo.toString() + " size " + elementDataSize); if (log.isDebugEnabled()) { log.debug("Rawbytes { " + hexDump(idAndSizeRawBytes) + " }"); } dumpByteBufferToRawOutput(idAndSizeRawBytes); if (checkExpectedCallbacks) { CallbackDescription expectedCallback = callbackDescriptions.remove(); CallbackDescription actualCallback = CallbackDescription.builder() .elementCount(elementNumber) .callbackType(CallbackDescription.CallbackType.START) .typeInfo(typeInfo) .numBytes(OptionalLong.of(elementDataSize)) .bytes(convertToByteArray(idAndSizeRawBytes)) .build(); Validate.isTrue(compareCallbackDescriptions(expectedCallback, actualCallback), getMismatchExpectationMessage(expectedCallback, actualCallback)); } }
public void test_optionalLong_present() throws Exception { String text = JSON.toJSONString(OptionalLong.empty()); Assert.assertEquals("null", text); }
@Value.Parameter OptionalLong l1();
private Single<Long> fromRepository() { final OptionalLong mayBeTickTime = maybeMaxTickTime(); return mayBeTickTime.isPresent() ? Single.just(mayBeTickTime.getAsLong()) : Single.error(new JFException("No tick time available!")); }
@Nonnull OptionalLong getLastTested(@Nonnull T key);
@Nonnull OptionalLong getLastTested(@Nonnull I key);
public OptionalLongExample(Long value) { this.value = OptionalLong.of(value); }
@Override public final <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { return invokeAll(tasks, OptionalLong.empty()); }