io.vavr.control.Option Java Examples
The following examples show how to use
io.vavr.control.Option.
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: Regex.java From ts-reaktive with MIT License | 6 votes |
/** * Returns a regex that transforms the returned type from T into U, using the supplied function. */ public <U> Regex<U> map(Function<T,U> f) { final Regex<T> parent = this; return new Regex<U>() { @Override public Option<U> match(String source) { return parent.match(source).map(f); } @Override protected U extract(Matcher m) { return null; } @Override public String toString() { return parent.toString(); } }; }
Example #2
Source File: SchemaTest.java From paleo with Apache License 2.0 | 6 votes |
@Test public void parse() throws IOException { Schema schema = Schema.parseJson(new StringReader(JSON)); assertEquals("Paleo Schema Title", schema.getTitle()); assertEquals("data.tsv", schema.getDataFileName()); assertEquals(3, schema.getFields().length()); assertEquals(Option.of("netzwerg"), schema.getMetaData().get("author")); assertTrue(schema.getCharsetName().isEmpty()); Field fooField = schema.getFields().get(0); assertEquals("Foo", fooField.getName()); assertEquals(ColumnType.INT, fooField.getType()); assertFalse(fooField.getFormat().isDefined()); Field barField = schema.getFields().get(1); assertEquals("Bar", barField.getName()); assertEquals(ColumnType.TIMESTAMP, barField.getType()); assertEquals("yyyyMMddHHmmss.SSS", barField.getFormat().get()); Field emptyField = schema.getFields().get(2); assertEquals("", emptyField.getName()); assertEquals(ColumnType.CATEGORY, emptyField.getType()); assertFalse(emptyField.getFormat().isDefined()); }
Example #3
Source File: AriCommandResponseKafkaProcessor.java From ari-proxy with GNU Affero General Public License v3.0 | 6 votes |
private static CompletionStage<Tuple2<AriResponse, CallContextAndCommandId>> toAriResponse( Tuple2<HttpResponse, CallContextAndCommandId> responseWithContext, Materializer materializer) { final HttpResponse response = responseWithContext._1; final long contentLength = response .entity() .getContentLengthOption() .orElseThrow(() -> new RuntimeException("failed to get content length")); return response .entity() .toStrict(contentLength, materializer) .thenCompose(strictText -> Option.of(StringUtils.trimToNull(strictText.getData().decodeString(Charset.defaultCharset()))) .map(rawBody -> Try .of(() -> genericReader.readTree(rawBody)) .map(jsonBody -> new AriResponse( response.status().intValue(), jsonBody)) .map(res -> responseWithContext.map1(httpResponse -> res)) .map(tuple -> CompletableFuture.completedFuture(tuple)) .getOrElseGet(t -> Future.<Tuple2<AriResponse, CallContextAndCommandId>>failed(t).toCompletableFuture())) .getOrElse(CompletableFuture.completedFuture(responseWithContext.map1(httpResponse -> new AriResponse(response.status().intValue(), null)))) ); }
Example #4
Source File: TypeGenerator.java From panda with Apache License 2.0 | 6 votes |
protected Type findOrGenerate(TypeLoader typeLoader, Module module, Class<?> javaType) { /*if (javaType.isPrimitive()) { javaType = ClassUtils.getNonPrimitiveClass(javaType); }*/ Option<Type> typeValue = typeLoader.forClass(javaType); if (typeValue.isDefined()) { return typeValue.get(); } Type type = initializedTypes.get(getId(module, javaType.getSimpleName())); if (type != null) { return type; } return generate(module, javaType.getSimpleName(), javaType); }
Example #5
Source File: Issue141Test.java From vavr-jackson with Apache License 2.0 | 6 votes |
@Test public void itShouldSerializeVavrOptionYearMonthAsStringWithoutJsonFormat() throws IOException { // Given an instance with io.vavr.control.Option MyVavrOptionalClassWithoutFormat obj = new MyVavrOptionalClassWithoutFormat(); obj.operatingMonth = Option.of(YearMonth.of(2019, 12)); // When serializing the instance using object mapper // with Java Time Module and VAVR Module ObjectMapper objectMapper = mapper(); objectMapper.registerModule(new JavaTimeModule()); objectMapper.registerModule(new VavrModule()); String json = objectMapper.writeValueAsString(obj); // Then serialization is successful Assertions.assertEquals("{\"operatingMonth\":[2019,12]}", json); MyVavrOptionalClassWithoutFormat obj2 = objectMapper.readValue(json, MyVavrOptionalClassWithoutFormat.class); // And deserialization is successful Assertions.assertEquals(Option.of(YearMonth.of(2019, 12)), obj2.operatingMonth); }
Example #6
Source File: AriCommandResponseKafkaProcessor.java From ari-proxy with GNU Affero General Public License v3.0 | 6 votes |
private static HttpRequest toHttpRequest(AriCommand ariCommand, String uri, String user, String password) { final String method = ariCommand.getMethod(); final JsonNode body = ariCommand.getBody(); final String bodyJson = Option.of(body) .map(value -> Try.of(() -> genericWriter.writeValueAsString(value))) .getOrElse(Try.success("")) .getOrElseThrow(t -> new RuntimeException(t)); return HttpMethods.lookup(method) .map(validHttpMethod -> HttpRequest .create() .withMethod(validHttpMethod) .addCredentials(HttpCredentials.createBasicHttpCredentials(user, password)) .withUri(uri + ariCommand.getUrl()) .withEntity(ContentTypes.APPLICATION_JSON, bodyJson.getBytes()) ) .orElseThrow(() -> new RuntimeException(String.format("Invalid http method: %s", method))); }
Example #7
Source File: CacheImpl.java From resilience4j with Apache License 2.0 | 6 votes |
private Option<V> getValueFromCache(K cacheKey) { try { Option<V> result = Option.of(cache.get(cacheKey)); if (result.isDefined()) { onCacheHit(cacheKey); return result; } else { onCacheMiss(cacheKey); return result; } } catch (Exception exception) { LOG.warn("Failed to get a value from Cache {}", getName(), exception); onError(exception); return Option.none(); } }
Example #8
Source File: ReplicatedActor.java From ts-reaktive with MIT License | 5 votes |
public ReplicatedActor(Class<C> commandType, Class<E> eventType, CommandHandler<C, E, S> handler) { super(commandType, eventType, handler); Receive invokeSuper = super.createReceiveRecover(); AtomicReference<Option<Boolean>> slave = new AtomicReference<>(none()); this.receiveRecover = ReceiveBuilder.create() .match(eventType, e -> slave.get().isEmpty() && !classifier().getDataCenterNames(e).isEmpty(), e -> { slave.set(some(!includesLocalDataCenter(e))); invokeSuper.onMessage().apply(e); }) .match(RecoveryCompleted.class, msg -> { if (slave.get().isEmpty()) { if (lastSequenceNr() > 0) { getContext().become(migrateNonReplicatedActor()); } else { getContext().become(justCreated()); } } else { getContext().become(slave.get().get() ? slave() : master()); } if (invokeSuper.onMessage().isDefinedAt(msg)) { invokeSuper.onMessage().apply(msg); } }) .build() .orElse(invokeSuper); }
Example #9
Source File: MetricsService.java From ari-proxy with GNU Affero General Public License v3.0 | 5 votes |
private void handleStop(StopCallSetupTimer stop) { Option .of(timers.get(stop.getCallcontext())) .peek(sample -> { sample.stop(registry.timer("CallSetupDelay", "stasisApp", stop.getApplication())); timers.remove(stop.getCallcontext()); }).toTry().onSuccess((metric) -> sender().tell(MetricRegistered.TIMER_STOPPED, self())); }
Example #10
Source File: AbstractScope.java From panda with Apache License 2.0 | 5 votes |
@Override public Option<Variable> getVariable(String name) { for (Variable variable : variables) { if (variable.getName().equals(name)) { return Option.of(variable); } } return getParentScope().flatMap(scope -> scope.getVariable(name)); }
Example #11
Source File: PandaType.java From panda with Apache License 2.0 | 5 votes |
@Override public Option<Type> getSuperclass() { for (Type base : getBases()) { if (TypeModels.isClass(base)) { return Option.of(base); } } return Option.none(); }
Example #12
Source File: SeqTest.java From vavr-jackson with Apache License 2.0 | 5 votes |
@Test void testWithOption() throws Exception { verifySerialization(typeReferenceWithOption(), List.of( Tuple.of(of(Option.some("value")), genJsonList("value")), Tuple.of(of(Option.none()), genJsonList((Object) null)) )); }
Example #13
Source File: ConstructorExpressionSubparser.java From panda with Apache License 2.0 | 5 votes |
private ExpressionResult parseDefault(ExpressionContext context, Type type, TokenInfo section) { Snippet argsSource = section.toToken(Section.class).getContent(); Expression[] arguments = ARGUMENT_PARSER.parse(context, argsSource); Option<Adjustment<TypeConstructor>> adjustedConstructor = type.getConstructors().getAdjustedConstructor(arguments); return adjustedConstructor .map(constructorArguments -> ExpressionResult.of(new TypeExecutableExpression(null, constructorArguments))) .getOrElse(() -> ExpressionResult.error(type.getSimpleName() + " does not have constructor with the required parameters: " + Arrays.toString(arguments), section)); }
Example #14
Source File: JSONProtocol.java From ts-reaktive with MIT License | 5 votes |
public static <T> Protocol<JSONEvent, Seq<T>> optionalVectorField(String name, Protocol<JSONEvent,T> inner) { return option( field(name, array( vector(inner) ) ) ).map(o -> o.getOrElse(Vector.empty()), (Seq<T> i) -> Option.when(!i.isEmpty(), i)); }
Example #15
Source File: ConcatenationOperatorSubparser.java From panda with Apache License 2.0 | 5 votes |
private boolean parseSubOperation(OperationParser parser, Context context, List<Expression> values, Operation operation, int start, int end) { if ((end - start) == 1) { values.add(operation.getElements().get(start).getExpression()); return true; } Operation subOperation = new Operation(operation.getElements().subList(start, end)); Option<Expression> expression = parser.parse(context, subOperation); expression.peek(values::add); return expression.isDefined(); }
Example #16
Source File: HeteroDescribableConfigurator.java From configuration-as-code-plugin with MIT License | 5 votes |
private Option<Descriptor<T>> lookupDescriptor(String symbol, CNode config) { return getDescriptors() .filter(descriptor -> findByPreferredSymbol(descriptor, symbol) || findBySymbols(descriptor, symbol, config)) .map(descriptor -> Tuple.of(preferredSymbol(descriptor), descriptor)) .foldLeft(HashMap.empty(), this::handleDuplicateSymbols) .values() .headOption() .orElse(() -> { throw new IllegalArgumentException("No " + target.getName() + " implementation found for " + symbol); }); }
Example #17
Source File: ACL.java From ts-reaktive with MIT License | 5 votes |
/** * Creates a new, empty, ACL, based on various lambda expressions for R and C. * @param getTargetId Function that yields a target UUID for a change (or none() if that change is to be ignored) * @param getGranted Function that yields a right that was granted for a change (or none() if the change doesn't grant rights) * @param getRevoked Function that yields a right that was revoked for a change (or none() if the change doesn't revoke rights) */ public static <R,C> ACL<R,C> empty( Function1<C, Option<UUID>> getTargetId, Function1<C, Option<R>> getGranted, Function1<C, Option<R>> getRevoked ) { return ACLBuilder.of(getTargetId, getGranted, getRevoked).empty(); }
Example #18
Source File: BookDatabaseRepository.java From library with MIT License | 5 votes |
@Override public Option<AvailableBook> findAvailableBookBy(BookId bookId) { return Match(findBy(bookId)).of( Case($Some($(instanceOf(AvailableBook.class))), Option::of), Case($(), Option::none) ); }
Example #19
Source File: OptionPlainTest.java From vavr-jackson with Apache License 2.0 | 5 votes |
@Test void test1() throws IOException { Option<?> src = Option.of(1); String json = mapper().writer().writeValueAsString(src); Assertions.assertEquals("1", json); Option<?> restored = mapper().readValue(json, Option.class); Assertions.assertEquals(src, restored); }
Example #20
Source File: EitherTest.java From vavr-jackson with Apache License 2.0 | 5 votes |
@Test void testWithOption() throws IOException { TypeReference<Either<Option<String>, Option<String>>> typeReference = new TypeReference<Either<Option<String>, Option<String>>>() {}; verifySerialization(typeReference, List.of( Tuple.of(Either.left(none()), genJsonList("left", null)), Tuple.of(Either.right(none()), genJsonList("right", null)), Tuple.of(Either.left(some("value")), genJsonList("left", "value")), Tuple.of(Either.right(some("value")), genJsonList("right", "value")) )); }
Example #21
Source File: SecurityUtil.java From streaming-file-server with MIT License | 5 votes |
public static Map<String, String> displayName() { return HashMap.of(profileUrlKey, profileUrlValue, displayName, Option.of(SecurityContextHolder.getContext()) .map(SecurityContext::getAuthentication) .map(auth -> (auth instanceof UserDetails) ? ((UserDetails) auth).getUsername() : auth.getName()) .getOrElse(() -> anonymousFriendlyName)) .toJavaMap(); }
Example #22
Source File: OptionTest.java From vavr-jackson with Apache License 2.0 | 5 votes |
@Test void test3() throws IOException { assertThrows(JsonMappingException.class, () -> { String json = "[\"defined\", 2, 3]"; mapper(optSettings).readValue(json, Option.class); }); }
Example #23
Source File: Patron.java From library with MIT License | 5 votes |
public Either<BookHoldFailed, BookPlacedOnHoldEvents> placeOnHold(AvailableBook aBook, HoldDuration duration) { Option<Rejection> rejection = patronCanHold(aBook, duration); if (rejection.isEmpty()) { BookPlacedOnHold bookPlacedOnHold = bookPlacedOnHoldNow(aBook.getBookId(), aBook.type(), aBook.getLibraryBranch(), patron.getPatronId(), duration); if (patronHolds.maximumHoldsAfterHolding(aBook)) { return announceSuccess(events(bookPlacedOnHold, MaximumNumberOhHoldsReached.now(patron, MAX_NUMBER_OF_HOLDS))); } return announceSuccess(events(bookPlacedOnHold)); } return announceFailure(bookHoldFailedNow(rejection.get(), aBook.getBookId(), aBook.getLibraryBranch(), patron)); }
Example #24
Source File: TupleTest.java From vavr-jackson with Apache License 2.0 | 5 votes |
@Test void testWithOption() throws IOException { verifySerialization(typeReferenceWithOption(), List.of( Tuple.of(ofObjects(Option.some("1"), Option.none()), genJsonTuple("1", null)), Tuple.of(ofObjects(Option.some("1"), Option.some("17")), genJsonTuple("1", "17")), Tuple.of(ofObjects(Option.none(), Option.some("17")), genJsonTuple(null, "17")), Tuple.of(ofObjects(Option.none(), Option.none()), genJsonTuple(null, null)) )); }
Example #25
Source File: SetTest.java From vavr-jackson with Apache License 2.0 | 5 votes |
@Test void testWithOption() throws Exception { verifySerialization(typeReferenceWithOption(), List.of( Tuple.of(of(Option.some("value")), genJsonList("value")), Tuple.of(of(Option.none()), genJsonList((Object) null)) )); }
Example #26
Source File: PatronProfileController.java From library with MIT License | 5 votes |
@PostMapping("/profiles/{patronId}/holds") ResponseEntity placeHold(@PathVariable UUID patronId, @RequestBody PlaceHoldRequest request) { Try<Result> result = placingOnHold.placeOnHold( new PlaceOnHoldCommand( Instant.now(), new PatronId(patronId), new LibraryBranchId(request.getLibraryBranchId()), new BookId(request.getBookId()), Option.of(request.getNumberOfDays()) ) ); return result .map(success -> ResponseEntity.ok().build()) .getOrElse(ResponseEntity.status(INTERNAL_SERVER_ERROR).build()); }
Example #27
Source File: AbstractCommandResultsAssert.java From ts-reaktive with MIT License | 5 votes |
/** * Asserts there is a validation error and returns it, casting it to the given type. * Useful for subclasses for concrete Results implementations that have a fixed message type. */ protected <M> M validationError(Class<M> type) { Option<Object> err = actual.getValidationError(0); if (err.isEmpty()) { throwAssertionError(new BasicErrorMessageFactory("Expected a Result with validation errors, but instead was %s", actualToString())); } return type.cast(err.get()); }
Example #28
Source File: SheetsReadModel.java From library with MIT License | 5 votes |
private void createNewHold(BookPlacedOnHold event) { sheets.update("INSERT INTO holds_sheet " + "(id, book_id, status, hold_event_id, hold_by_patron_id, hold_at, hold_till, expired_at, canceled_at, hold_at_branch, checked_out_at) VALUES " + "(holds_sheet_seq.nextval, ?, ?, ?, ?, ?, ?, null, null, ?, null)", event.getBookId(), "ACTIVE", event.getEventId(), event.getPatronId(), from(event.getWhen()), Option.of(event.getHoldTill()).map(Timestamp::from).getOrNull(), event.getLibraryBranchId()); }
Example #29
Source File: PandaTypeLoader.java From panda with Apache License 2.0 | 5 votes |
@Override public Option<Type> forName(CharSequence typeName) { if (typeName.toString().endsWith(PandaArray.IDENTIFIER)) { return ArrayClassTypeFetcher.fetch(this, typeName.toString()); } return loadedTypes.forName(typeName) .orElse(() -> ModuleResourceUtils.forName(loadedModules, typeName)) .orElse(() -> ModuleResourceUtils.forName(parents, typeName)) .peek(this::load); }
Example #30
Source File: PandaConstructor.java From panda with Apache License 2.0 | 4 votes |
@Override public Option<BaseCall> getBaseCall() { return Option.of(baseCallArgumentsSupplier).flatMap(Supplier::get); }