Java Code Examples for io.vavr.control.Option#isDefined()

The following examples show how to use io.vavr.control.Option#isDefined() . 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: TagWriteProtocol.java    From ts-reaktive with MIT License 6 votes vote down vote up
/**
 * @param name The qualified name of the tag to write, or none() to have the last item of [getters] deliver a {@link QName}.
 * @param getters Getter function for each sub-protocol to write (and additional first element delivering a QName, if name == none())
 * @param protocols Protocols to use to write each of the getter elements
 */
public TagWriteProtocol(Option<QName> name, Vector<? extends WriteProtocol<XMLEvent,?>> protocols, Vector<Function1<T, ?>> g) {
    if (name.isDefined() && (protocols.size() != g.size()) ||
        name.isEmpty() && (protocols.size() != g.size() - 1)) {
        throw new IllegalArgumentException ("Number of protocols and getters does not match");
    }
    this.name = name;
    this.getName = t -> name.getOrElse(() -> (QName) g.head().apply(t));
    
    Vector<Function1<T, ?>> getters = (name.isEmpty()) ? g.drop(1) : g;
    
    Tuple2<Vector<Tuple2<WriteProtocol<XMLEvent,?>, Function1<T, ?>>>, Vector<Tuple2<WriteProtocol<XMLEvent,?>, Function1<T, ?>>>> partition =
        ((Vector<WriteProtocol<XMLEvent,?>>)protocols).zip(getters)
        .partition(t -> Attribute.class.isAssignableFrom(t._1.getEventType()));
    
    this.attrProtocols = partition._1().map(t -> t._1());
    this.attrGetters = partition._1().map(t -> t._2());
    this.otherProtocols = partition._2().map(t -> t._1());
    this.otherGetters = partition._2().map(t -> t._2());
}
 
Example 2
Source File: CacheImpl.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
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 3
Source File: PandaModule.java    From panda with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isSubmodule(Module module) {
    Option<Module> parentModule = module.getParent();

    while (parentModule.isDefined()) {
        Module parent = parentModule.get();

        if (parent.equals(this)) {
            return true;
        }

        parentModule = parent.getParent();
    }

    return false;
}
 
Example 4
Source File: TypeGenerator.java    From panda with Apache License 2.0 6 votes vote down vote up
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: SubparsersUtils.java    From panda with Apache License 2.0 6 votes vote down vote up
protected static Produce<Type, ExpressionResult> readType(ExpressionContext context) {
    Option<Snippet> typeSource = TypeDeclarationUtils.readType(context.getSynchronizedSource().getAvailableSource());

    if (!typeSource.isDefined()) {
        return new Produce<>(() -> ExpressionResult.error("Cannot read type", context.getSynchronizedSource().getAvailableSource()));
    }

    return context.getContext().getComponent(Components.IMPORTS)
            .forName(typeSource.get().asSource())
            .map(type -> {
                context.getSynchronizedSource().next(typeSource.get().size());
                return new Produce<Type, ExpressionResult>(type);
            })
            .getOrElse(() -> {
                return new Produce<>(() -> ExpressionResult.error("Unknown type", context.getSynchronizedSource().getAvailableSource()));
            });
}
 
Example 6
Source File: TypeParserUtils.java    From panda with Apache License 2.0 6 votes vote down vote up
public static Collection<Snippetable> readTypes(SynchronizedSource source) {
    Collection<Snippetable> types = new ArrayList<>(1);

    while (source.hasNext()) {
        if (!types.isEmpty()) {
            if (!source.getNext().equals(Separators.COMMA)) {
                break;
            }

            source.next();
        }

        Option<Snippet> type = TypeDeclarationUtils.readType(source);

        if (!type.isDefined()) {
            break;
        }

        types.add(type.get());
    }

    return types;
}
 
Example 7
Source File: OptionSerializer.java    From vavr-jackson with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(Option<?> value, JsonGenerator gen, SerializerProvider provider) throws IOException {
    if (plainMode) {
        if (value.isDefined()) {
            if (valueSerializer != null) {
                valueSerializer.serialize(value.get(), gen, provider);
            } else {
                write(value.get(), 0, gen, provider);
            }
        } else {
            gen.writeNull();
        }
    } else {
        gen.writeStartArray();
        if (value.isDefined()) {
            gen.writeString("defined");
            write(value.get(), 0, gen, provider);
        } else {
            gen.writeString("undefined");
        }
        gen.writeEndArray();
    }
}
 
Example 8
Source File: RemoteThreadWebDriverMapImpl.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
/**
 * Load the browserstack details from configuration
 */
private void loadBrowserStackSettings() {
	final Option<Tuple2<String, String>> credentials = REMOTE_TESTS_UTILS.getCredentials();
	if (credentials.isDefined()) {
		browserStackUsername = credentials.get()._1();
		browserStackAccessToken = credentials.get()._2();
	} else {
		/*
				Log an error because there were no details
			 */
		LOGGER.error("Could not load browserstack config");
	}
}
 
Example 9
Source File: AbstractStatefulPersistentActor.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Applies the results that came in from a handler, emitting any events, and responding to sender().
 */
protected void handleResults(CommandHandler.Results<E> results) {
    Option<Object> error = results.getValidationError(lastSequenceNr());
    if (error.isDefined()) {
        log.debug("  invalid: {}", error.get());
        sender().tell(error.get(), self());
    } else if (results.isAlreadyApplied()) {
        log.debug("  was already applied.");
        sender().tell(results.getIdempotentReply(lastSequenceNr()), self());
    } else {
        Seq<E> events = results.getEventsToEmit();
        log.debug("  emitting {}", events);
        if (events.isEmpty()) {
            sender().tell(results.getReply(events, lastSequenceNr()), self());
        } else {
            if (lastSequenceNr() == 0) {
                validateFirstEvent(events.head());
            }
            AtomicInteger need = new AtomicInteger(events.size());
            persistAllEvents(events, evt -> {
                if (need.decrementAndGet() == 0) {
                    sender().tell(results.getReply(events, lastSequenceNr()), self());
                }
            });
        }
    }
}
 
Example 10
Source File: ConcatenationOperatorSubparser.java    From panda with Apache License 2.0 5 votes vote down vote up
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 11
Source File: TypeParserUtils.java    From panda with Apache License 2.0 5 votes vote down vote up
public static void appendExtended(Context context, Type type, Snippetable typeSource) {
    String name = typeSource.toString();
    Option<Type> extendedType = context.getComponent(Components.IMPORTS).forName(name);

    if (extendedType.isDefined()) {
        StateComparator.requireInheritance(context, extendedType.get(), typeSource);
        type.addBase(extendedType.get());
        return;
    }

    throw new PandaParserFailure(context, typeSource,
            "Type " + name + " not found",
            "Make sure that the name does not have a typo and module which should contain that class is imported"
    );
}
 
Example 12
Source File: Serializer.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
private static String expectedOptionJson(Option<?> opt, int opts) {
    if ((opts & EXTENDED_OPTION) == 0) {
        return expectedJson(opt.get(), opts);
    } else {
        if (opt.isDefined()) {
            return "[\"defined\"," + expectedJson(opt.get(), opts) + "]";
        } else {
            return "[\"undefined\"]";
        }
    }
}
 
Example 13
Source File: VariableExpressionSubparser.java    From panda with Apache License 2.0 4 votes vote down vote up
@Override
public @Nullable ExpressionResult next(ExpressionContext context, TokenInfo token) {
    boolean period = TokenUtils.contentEquals(context.getSynchronizedSource().getPrevious(), Separators.PERIOD);

    if (token.getType() != TokenTypes.UNKNOWN) {
        return null;
    }

    if ((!period && context.hasResults()) || (period && !context.hasResults())) {
        return null;
    }

    // do not accept variable names starting with numbers
    if (NumberUtils.startsWithNumber(token.getToken())) {
        return null;
    }

    String name = token.getValue();

    // if there is anything on stack, we can search only for fields
    if (context.hasResults()) {
        ExpressionResult result = fromInstance(context, context.peekExpression(), token).orElseGet(() -> {
            return ExpressionResult.error("Cannot find field called '" + name + "'", token);
        });

        if (result.isPresent()) {
            context.popExpression();
        }

        return result;
    }

    Option<Variable> variableValue = context.getContext().getComponent(Components.SCOPE).getVariable(name);

    // respect local variables before fields
    if (variableValue.isDefined()) {
        Variable variable = variableValue.get();
        return ExpressionResult.of(new VariableExpression(variable).toExpression());
    }

    Type type = context.getContext().getComponent(TypeComponents.PROTOTYPE);

    if (type != null) {
        return fromInstance(context, ThisExpression.of(type), token).orElseGet(() -> {
            return ExpressionResult.error("Cannot find class/variable '" + name + "'", token);
        });
    }

    // return ExpressionResult.error("Cannot find variable or field called '" + name + "'", token);
    return null;
}