com.googlecode.totallylazy.Option Java Examples

The following examples show how to use com.googlecode.totallylazy.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: TestParser.java    From yatspec with Apache License 2.0 6 votes vote down vote up
private static Sequence<TestMethod> collectTestMethods(Class aClass, Sequence<Method> methods) throws IOException {
    final Option<JavaClass> javaClass = getJavaClass(aClass);
    if (javaClass.isEmpty()) {
        return empty();
    }

    Map<String, List<JavaMethod>> sourceMethodsByName = getMethods(javaClass.get()).toMap(sourceMethodName());
    Map<String, List<Method>> reflectionMethodsByName = methods.toMap(reflectionMethodName());

    List<TestMethod> testMethods = new ArrayList<TestMethod>();
    TestMethodExtractor extractor = new TestMethodExtractor();
    for (String name : sourceMethodsByName.keySet()) {
        List<JavaMethod> javaMethods = sourceMethodsByName.get(name);
        List<Method> reflectionMethods = reflectionMethodsByName.get(name);
        testMethods.add(extractor.toTestMethod(aClass, javaMethods.get(0), reflectionMethods.get(0)));
        // TODO: If people overload test methods we will have to use the full name rather than the short name
    }

    Sequence<TestMethod> myTestMethods = sequence(testMethods);
    Sequence<TestMethod> parentTestMethods = collectTestMethods(aClass.getSuperclass(), methods);

    return myTestMethods.join(parentTestMethods);
}
 
Example #2
Source File: Main.java    From java-repl with Apache License 2.0 6 votes vote down vote up
public static void main(String... args) throws Exception {
    console = new ResultPrinter(printColors(args));

    ConsoleReader consoleReader = new ConsoleReader(System.in, AnsiConsole.out);
    JavaREPLClient client = clientFor(hostname(args), port(args));
    Sequence<String> initialExpressions = initialExpressionsFromFile().join(initialExpressionsFromArgs(args));
    ExpressionReader expressionReader = expressionReaderFor(consoleReader, client, initialExpressions);

    Option<String> expression = none();
    Option<EvaluationResult> result = none();
    while (expression.isEmpty() || !result.isEmpty()) {
        expression = expressionReader.readExpression();

        if (!expression.isEmpty()) {
            result = client.execute(expression.get());
            if (!result.isEmpty()) {
                for (EvaluationLog log : result.get().logs()) {
                    if (!handleTerminalCommand(log)) {
                        handleTerminalMessage(log);
                    }
                }
            }
        }
    }
}
 
Example #3
Source File: StaticMemberCompleter.java    From java-repl with Apache License 2.0 6 votes vote down vote up
public CompletionResult call(String expression) throws Exception {
    final int lastSeparator = lastIndexOfSeparator(characters(" "), expression) + 1;
    final String packagePart = expression.substring(lastSeparator);

    Option<Pair<Class<?>, String>> completion = completionFor(packagePart);

    if (!completion.isEmpty()) {
        Function1<CompletionCandidate, String> value = CompletionCandidate::value;
        Sequence<CompletionCandidate> candidates = reflectionOf(completion.get().first())
                .declaredMembers()
                .filter(isStatic().and(isPublic()).and(not(isSynthetic())))
                .groupBy(candidateName())
                .map(candidate())
                .filter(where(value, startsWith(completion.get().second())));

        final int beginIndex = packagePart.lastIndexOf('.') + 1;
        return new CompletionResult(expression, lastSeparator + beginIndex, candidates);
    } else {
        return new CompletionResult(expression, 0, Sequences.empty(CompletionCandidate.class));
    }
}
 
Example #4
Source File: Evaluator.java    From java-repl with Apache License 2.0 6 votes vote down vote up
private Sequence<Result> modifiedResults(final Object expressionInstance) {
    return sequence(expressionInstance.getClass().getDeclaredFields())
            .reduceLeft(new Reducer<Field, Sequence<Result>>() {
                public Sequence<Result> call(Sequence<Result> results, Field field) throws Exception {
                    Option<Result> result = result(field.getName()).filter(where(Result::value, not(equalTo(field.get(expressionInstance)))));

                    if (result.isEmpty())
                        return results;

                    return results.append(Result.result(field.getName(), field.get(expressionInstance)));

                }

                public Sequence<Result> identity() {
                    return empty(Result.class);
                }
            });
}
 
Example #5
Source File: covered_covered_t.java    From coming with MIT License 6 votes vote down vote up
private Sequence<Result> modifiedResults(final Object expressionInstance) {
    return sequence(expressionInstance.getClass().getDeclaredFields())
            .reduceLeft(new Reducer<Field, Sequence<Result>>() {
                public Sequence<Result> call(Sequence<Result> results, Field field) throws Exception {
                    Option<Result> result = result(field.getName()).filter(where(Result::value, not(equalTo(field.get(expressionInstance)))));

                    if (result.isEmpty())
                        return results;

                    return results.append(Result.result(field.getName(), field.get(expressionInstance)));

                }

                public Sequence<Result> identity() {
                    return empty(Result.class);
                }
            });
}
 
Example #6
Source File: WebConsoleResource.java    From java-repl with Apache License 2.0 6 votes vote down vote up
@POST
@Hidden
@Path("create")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> create(@FormParam("expression") Option<String> expression,
                                  @FormParam("snap") Option<String> snap) throws Exception {


    Option<String> initial = snap.isDefined()
            ? some(format(":eval %s", snapUri(snap.get())))
            : expression;

    Option<WebConsoleClientHandler> clientHandler = agent.createClient(initial);

    return clientHandler.map(clientHandlerToModel()).get()
            .insert("welcomeMessage", welcomeMessage());
}
 
Example #7
Source File: LoadSourceFile.java    From java-repl with Apache License 2.0 6 votes vote down vote up
public void execute(String expression) {
    Option<String> path = parseStringCommand(expression).second();

    if (!path.isEmpty()) {
        try {
            evaluator.evaluate(Strings.lines(path.map(asFile()).get()).toString("\n"))
                    .leftOption()
                    .forEach(throwException());
            logger.success(format("Loaded source file from %s", path.get()));
        } catch (Exception e) {
            logger.error(format("Could not load source file from %s.\n  %s", path.get(), e.getLocalizedMessage()));
        }
    } else {
        logger.error(format("Path not specified"));
    }
}
 
Example #8
Source File: ConsoleHistory.java    From java-repl with Apache License 2.0 5 votes vote down vote up
public static final ConsoleHistory historyFromFile(Predicate<String> ignored, Option<File> file) {
    if (file.isEmpty())
        return emptyHistory(ignored, file);

    try {
        return new ConsoleHistory(Strings.lines(file.get()), ignored, file);
    } catch (Exception e) {
        return emptyHistory(ignored, file);
    }
}
 
Example #9
Source File: WebConsoleClientHandler.java    From java-repl with Apache License 2.0 5 votes vote down vote up
public Option<Integer> exitCode() {
    if (process.isEmpty())
        return none();

    try {
        Thread.sleep(100);
        return some(process.get().exitValue());
    } catch (Exception e) {
        return none();
    }
}
 
Example #10
Source File: PersistentMapTest.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@Test
public void canPutAndReturnOldValue() throws Exception {
    PersistentMap <Integer, String> pairs = map(4, "Four", 5, "Five", 3, "Three", 2, "Two", 6, "Six");
    Pair<PersistentMap <Integer, String>, Option<String>> result = PersistentMap.methods.put(pairs, 4, "NewFour");
    assertThat(result.first().lookup(4).get(), is("NewFour"));
    assertThat(result.second().get(), is("Four"));
}
 
Example #11
Source File: WebConsole.java    From java-repl with Apache License 2.0 5 votes vote down vote up
public synchronized Option<WebConsoleClientHandler> removeClient(String id) {
    Option<WebConsoleClientHandler> clientHandler = clients.lookup(id);

    if (!clientHandler.isEmpty()) {
        clientHandler.get().shutdown();
        clients = clients.delete(clientHandler.get().id());
    }

    return clientHandler;
}
 
Example #12
Source File: Main.java    From java-repl with Apache License 2.0 5 votes vote down vote up
private static JavaREPLClient clientFor(Option<String> hostname, Option<Integer> port) throws Exception {
    console.printInfo(welcomeMessage());

    if (hostname.isDefined() && port.isDefined()) {
        return connectToRemoteInstance(hostname.get(), port.get());
    } else {
        return startNewLocalInstance("localhost", port.getOrElse(randomServerPort()));
    }
}
 
Example #13
Source File: RestConsoleExpressionReader.java    From java-repl with Apache License 2.0 5 votes vote down vote up
public Option<String> readExpression(String line) {
    lines = lines.append(line);
    if (expressionIsTerminated(lines)) {
        Option<String> result = some(lines.toString("\n"));
        lines = Sequences.empty();
        return result;
    } else {
        return none();
    }
}
 
Example #14
Source File: AggregateCompleter.java    From java-repl with Apache License 2.0 5 votes vote down vote up
private Option<Group<Integer, CompletionResult>> completeGroup(String expression) {
    return completers.map(complete(expression))
            .unique()
            .groupBy(CompletionResult::position)
            .sortBy(groupKey(Integer.class))
            .reverse()
            .headOption();
}
 
Example #15
Source File: WebConsoleResource.java    From java-repl with Apache License 2.0 5 votes vote down vote up
@POST
@Hidden
@Path("readExpression")
@Produces(MediaType.APPLICATION_JSON)
public Response readExpression(@FormParam("id") String id, @FormParam("line") String line) {
    Option<WebConsoleClientHandler> clientHandler = agent.client(id);

    if (!clientHandler.isEmpty()) {
        return clientHandler.get().readExpression(line);
    } else {
        return response(BAD_REQUEST);
    }
}
 
Example #16
Source File: AggregateCompleter.java    From java-repl with Apache License 2.0 5 votes vote down vote up
public CompletionResult call(String expression) throws Exception {
    Option<Group<Integer, CompletionResult>> group = completeGroup(expression);

    if (group.isEmpty())
        return new CompletionResult(expression, 0, empty(CompletionCandidate.class));

    return new CompletionResult(expression, group.get().key(), group.get().flatMap(CompletionResult::candidates));
}
 
Example #17
Source File: ConsoleConfig.java    From java-repl with Apache License 2.0 5 votes vote down vote up
private ConsoleConfig(Option<File> historyFile, Sequence<String> expressions, ConsoleLogger logger, Sequence<Class<? extends Command>> commands, Sequence<Result> results, Boolean sandboxed) {
    this.historyFile = historyFile;
    this.expressions = expressions;
    this.logger = logger;
    this.commands = commands;
    this.results = results;
    this.sandboxed = sandboxed;
}
 
Example #18
Source File: Types.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
public static <T> Option<Class<T>> classOption(Type concrete) {
    if (concrete instanceof Class) {
        return some(Unchecked.<Class<T>>cast(concrete));
    }
    if (concrete instanceof ParameterizedType) {
        return some(Types.<T>classOf(((ParameterizedType) concrete).getRawType()));
    }
    return none();
}
 
Example #19
Source File: JsonRecord.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@Override
public Object put(String key, Object value) {
    try {
        Option<Field> field = field(key);
        if (field.isDefined()) {
            Field actual = field.get();
            actual.set(this, Coercer.coerce(actual.getGenericType(), value));
            return Fields.get(actual, this);
        } else {
            return _otherFields.put(key, value);
        }
    } catch (IllegalAccessException e) {
        throw lazyException(e);
    }
}
 
Example #20
Source File: ExpressionReader.java    From java-repl with Apache License 2.0 5 votes vote down vote up
public Option<String> readExpression() {
    Sequence<String> lines = Sequences.empty();

    do {
        lines = lines.append(lineReader.apply(lines));
    } while (!expressionIsTerminated(lines));

    return lines.contains(null)
            ? none(String.class)
            : some(lines.toString("\n").trim());
}
 
Example #21
Source File: AVLTreeTest.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@Test
public void supportsHeadOption() {
    assertThat(map(1, "A").
            cons(pair(2, "B")).
            cons(pair(3, "C")).headOption(),
            is(some(pair(2, "B"))));

    assertThat(
            empty(Integer.class, String.class).headOption(),
            is(Option.<Pair<Integer, String>>none()));
}
 
Example #22
Source File: AbstractTreeMap.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@Override
public Option<V> lookup(K other) {
    int difference = difference(other);
    if (difference == 0) return Option.option(value);
    if (difference < 0) return left.lookup(other);
    return right.lookup(other);
}
 
Example #23
Source File: ArrayTrie.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@tailrec
public Option<V> get(K[] key) {
    if (Arrays.isEmpty(key)) return value;
    Option<ArrayTrie<K, V>> child = childFor(key);
    if (child.isEmpty()) return none();
    return child.get().get(tail(key));
}
 
Example #24
Source File: ArrayTrie.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@tailrec
public boolean contains(K[] key) {
    if (Arrays.isEmpty(key)) return !value.isEmpty();
    Option<ArrayTrie<K, V>> child = childFor(key);
    if (child.isEmpty()) return false;
    return child.get().contains(tail(key));
}
 
Example #25
Source File: OptionalParserTest.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@Test
public void isOptional() throws Exception {
    OptionalParser<String> parser = optional(string("foo"));
    Result<Option<String>> result = parser.parse("foo");
    assertThat(result.value(), is(some("foo")));
    assertThat(result.remainder(), is(emptySegment(Character.class)));
}
 
Example #26
Source File: TimingOutConsole.java    From java-repl with Apache License 2.0 5 votes vote down vote up
public TimingOutConsole(Console console, Option<Integer> expressionTimeout, Option<Integer> inactivityTimeout) {
    super(console);
    this.expressionTimeout = expressionTimeout;
    this.inactivityTimeout = inactivityTimeout;

    scheduleInactivityTimeout();
}
 
Example #27
Source File: TreeSet.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
@Override
public Option<T> headOption() {
    return isEmpty()
            ? Option.<T>none()
            : some(head());
}
 
Example #28
Source File: TreeSet.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
@Override
public Option<T> lookup(T value) {
    return map.lookup(value);
}
 
Example #29
Source File: ArrayTrie.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
private ArrayTrie(Option<V> value, PersistentMap<K, ArrayTrie<K, V>> children) {
    this.value = value;
    this.children = children;
}
 
Example #30
Source File: ArrayTrie.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
public static <K, V> ArrayTrie<K, V> trie(Option<V> value, PersistentMap<K, ArrayTrie<K, V>> children) {
    return new ArrayTrie<K, V>(value, children);
}