com.googlecode.totallylazy.Sequence Java Examples

The following examples show how to use com.googlecode.totallylazy.Sequence. 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: TypeCompleter.java    From java-repl with Apache License 2.0 6 votes vote down vote up
public CompletionResult call(String expression) throws Exception {
    final int lastSpace = expression.lastIndexOf(" ") + 1;
    final String packagePart = expression.substring(lastSpace);
    final int beginIndex = packagePart.lastIndexOf('.') + 1;

    Sequence<ResolvedPackage> resolvedPackages = typeResolver.packages().filter(where(ResolvedPackage::packageName, startsWith(packagePart)));

    Sequence<String> classesInPackage = beginIndex > 0
            ? typeResolver.packages().filter(where(ResolvedPackage::packageName, equalTo(packagePart.substring(0, beginIndex - 1))))
            .flatMap(ResolvedPackage::classes)
            .map(ResolvedClass::canonicalClassName)
            .filter(startsWith(packagePart))
            : empty(String.class);

    Sequence<CompletionCandidate> candidates = resolvedPackages.map(ResolvedPackage::packageName).join(classesInPackage)
            .map(candidatePackagePrefix(beginIndex))
            .filter(not(Strings.empty()))
            .unique()
            .sort(ascending(String.class))
            .map(asCompletionCandidate());

    return new CompletionResult(expression, lastSpace + beginIndex, candidates);
}
 
Example #2
Source File: Reflection.java    From totallylazy with Apache License 2.0 6 votes vote down vote up
/**
 * Finds a static method on actualType that takes a parameter of the same type as value and return
 * an instance of actualType.
 * <p>
 * Calls that static method with value and returns the result.
 **/
public static <T> T valueOf(Class<T> actualType, Object value) {
    Sequence<Method> candidates = allMethods(actualType)
            .filter(and(modifier(STATIC),
                    where(m -> m.getParameterTypes().length, is(1)))).
                    filter(and(
                            where(returnType(), matches(actualType)),
                            where(m -> m.getParameterTypes()[0], (t) -> t.isAssignableFrom(value.getClass()))));

    if (candidates.isEmpty()) {
        throw new NoSuchElementException(format(
                "Cannot create %s from '%s' (%s). You need to add a static constructor method to %s that accepts a %s",
                actualType.getCanonicalName(), value, value.getClass().getCanonicalName(),
                actualType.getSimpleName(), value.getClass().getSimpleName()));
    }

    return actualType.cast(candidates.pick(optional(invokeOn(null, value))));
}
 
Example #3
Source File: Main.java    From java-repl with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a root that matches all the {@link String} elements of the specified {@link List},
 * or null if there are no commonalities. For example, if the list contains
 * <i>foobar</i>, <i>foobaz</i>, <i>foobuz</i>, the method will return <i>foob</i>.
 */
private String getUnambiguousCompletions(final Sequence<CompletionCandidate> candidates) {
    if (candidates == null || candidates.isEmpty()) {
        return null;
    }

    // convert to an array for speed
    String[] strings = candidates.map(CompletionCandidate::value).toArray(new String[candidates.size()]);

    String first = strings[0];
    StringBuilder candidate = new StringBuilder();

    for (int i = 0; i < first.length(); i++) {
        if (startsWith(first.substring(0, i + 1), strings)) {
            candidate.append(first.charAt(i));
        } else {
            break;
        }
    }

    return candidate.toString();
}
 
Example #4
Source File: StaticMemberCompleter.java    From java-repl with Apache License 2.0 6 votes vote down vote up
private Option<Pair<String, Sequence<String>>> parseExpression(Pair<String, Sequence<String>> expression) {
    Option<Class<?>> expressionClass = evaluator.classFrom(expression.first());

    if (!expressionClass.isEmpty()) {
        return some(expression);
    }

    if (expression.first().contains(".")) {
        final String packagePart = expression.first().substring(0, expression.first().lastIndexOf("."));
        final String classPart = expression.first().substring(expression.first().lastIndexOf(".") + 1);

        return parseExpression(pair(packagePart, expression.second().cons(classPart)));
    }

    return Option.none();

}
 
Example #5
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 #6
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 #7
Source File: ContextTest.java    From totallylazy with Apache License 2.0 6 votes vote down vote up
@Test
public void canSelectTextNodes() throws Exception {
    String xml = "<stream>Hello <b>Dan</b> Bodart</stream>";
    Document document = document(xml);

    Sequence<Node> nodes = selectNodes(document, "child::stream/child::text()");

    Sequence<Context> all = contexts(xml);
    Sequence<Context> locations = all.
            filter(xpath(child(name("stream")), child(text())));
    assertThat(locations.size(), is(nodes.size()));

    Node root = nodes.head();
    Context rootContext = locations.head();
    assertThat(rootContext.text(), is(root.getTextContent()));
}
 
Example #8
Source File: ConsoleConfig.java    From java-repl with Apache License 2.0 6 votes vote down vote up
public static Sequence<Class<? extends Command>> defaultCommands() {
    return Sequences.<Class<? extends Command>>sequence()
            .append(ClearScreen.class)
            .append(QuitApplication.class)
            .append(ShowHistory.class)
            .append(SearchHistory.class)
            .append(EvaluateFromHistory.class)
            .append(ResetAllEvaluations.class)
            .append(ReplayAllEvaluations.class)
            .append(EvaluateFile.class)
            .append(AddToClasspath.class)
            .append(LoadSourceFile.class)
            .append(ListValues.class)
            .append(ShowLastSource.class)
            .append(ShowTypeOfExpression.class)
            .append(CheckExpression.class);
}
 
Example #9
Source File: PersistentJsonRecord.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
static <T> T create(Class<T> aClass, Map<String, Object> map) {
    // TODO: Check is interface
    Sequence<Method> methods = sequence(aClass.getDeclaredMethods());
    PersistentSortedMap<String, Object> result = methods.fold(sortedMap(), (p, m) -> {
        String name = m.getName();
        Object value = map.remove(name);
        return value == null ? p : p.insert(name, Coercer.coerce(m.getGenericReturnType(), value));
    });
    return proxy(aClass, new Handler<>(aClass, pairs(map).fold(result, PersistentSortedMap::cons)));
}
 
Example #10
Source File: TestMethod.java    From yatspec with Apache License 2.0 5 votes vote down vote up
public static Status calculateStatus(final Sequence<Status> statuses) {
    if (statuses.contains(Status.Failed)) {
        return Status.Failed;
    }
    if (statuses.contains(Status.NotRun)) {
        return Status.NotRun;
    }
    return Status.Passed;
}
 
Example #11
Source File: JavaSourceRenderer.java    From yatspec with Apache License 2.0 5 votes vote down vote up
private String removeIndentation(String value) {
    Sequence<String> lines = lines(value);
    String indentation = lines.
            find(not(blankLine())).
            map(indentation()).getOrElse("");
    return lines.map(remove(indentation)).toString(lineSeparator());
}
 
Example #12
Source File: TestMethod.java    From yatspec with Apache License 2.0 5 votes vote down vote up
private List<String> createPossiblyVarargValueFrom(List<String> newValues, List<String> oldValues) {
    Sequence<String> actualValues = sequence(newValues);
    if (oldValues.size() > newValues.size()) {
        actualValues = sequence(newValues).join(sequence("[]").cycle()).take(oldValues.size());
    } else if (newValues.size() > oldValues.size()) {
        actualValues = actualValues.take(oldValues.size() - 1).append(actualValues.drop(oldValues.size() - 1).toString("[", ", ", "]"));
    }
    return actualValues.toList();
}
 
Example #13
Source File: Command.java    From java-repl with Apache License 2.0 5 votes vote down vote up
public static final Pair<String, Option<Integer>> parseNumericCommand(String input) {
    final Sequence<String> splitInput = sequence(input.split(COMMAND_SEPARATOR));

    try {
        return Pair.pair(splitInput.first(), some(parseInt(splitInput.tail().toString(COMMAND_SEPARATOR))));
    } catch (Exception e) {
        return Pair.pair(splitInput.first(), none(Integer.class));
    }
}
 
Example #14
Source File: Lazy1Test.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@Test
public void isThreadSafe() throws Exception {
    CountCalls1<Number, Number> counting = CountCalls1.counting(increment);
    Function1<Number, Number> lazyCallable1 = counting.sleep(10).lazy();

    Sequence<Number> result = callConcurrently(
            lazyCallable1.deferApply(3), lazyCallable1.deferApply(6),
            lazyCallable1.deferApply(3), lazyCallable1.deferApply(6)).realise();

    assertThat(counting.count(3), is(1));
    assertThat(counting.count(6), is(1));
    assertThat(result.first(), is(4));
    assertThat(result.second(), is(7));
}
 
Example #15
Source File: ContextTest.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@Test
public void oneItemWithTwoChildren() throws Exception {
    String xml = "<stream><item><child/><child/></item></stream>";

    Sequence<Context> locations = contexts(xml);
    org.junit.Assert.assertEquals(locations.toString("\n"), "<stream>\n" +
            "<stream>/<item>\n" +
            "<stream>/<item>/<child>\n" +
            "<stream>/<item>/<child>");
}
 
Example #16
Source File: WebConsoleClientHandler.java    From java-repl with Apache License 2.0 5 votes vote down vote up
public Sequence<String> history() {
    createProcess();

    try {
        return new JavaREPLClient("localhost", port.get()).history();
    } catch (Exception e) {
        e.printStackTrace();
        return Sequences.empty();
    }
}
 
Example #17
Source File: CallOnTest.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@Test
public void canSortByProxy() throws Exception {
    User matt = user("Matt", "Savage");
    User dan = user("Dan", "Bodart");
    User bob = user("Bob", "Marshal");
    Sequence<User> unsorted = sequence(matt, dan, bob);
    Sequence<User> sorted = unsorted.sortBy(new CallOn<User, String>(){{call.firstName();}});
    assertThat(sorted, hasExactly(bob, dan, matt));
}
 
Example #18
Source File: XmlTest.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@Test
public void copiesAllText() throws Exception {
    String xml = "<stream>Hello &amp; World</stream>";
    Sequence<Node> stream = nodes(new StringReader(xml), "stream");
    assertThat(stream.size(), is(1));
    assertThat(Xml.asString(stream.head()), is("<stream>Hello &amp; World</stream>"));
}
 
Example #19
Source File: XmlTest.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@Test
public void supportsAttributesOnNestedStructures() throws Exception {
    String xml = "<stream><item><child foo='bar'/><child/></item><item><child/><child baz='bar'/></item></stream>";
    Sequence<Node> stream = nodes(new StringReader(xml), "item");
    assertThat(stream.size(), is(2));
    assertThat(Xml.asString(stream.first()), is("<item><child foo=\"bar\"/><child/></item>"));
    assertThat(Xml.asString(stream.second()), is("<item><child/><child baz=\"bar\"/></item>"));
}
 
Example #20
Source File: Types.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
public static Sequence<Type> classTypeParameters(Type concrete) {
    if (concrete instanceof Class) {
        return sequence(((Class) concrete).getTypeParameters()).safeCast(Type.class);
    }
    if (concrete instanceof ParameterizedType) {
        return sequence(((ParameterizedType) concrete).getActualTypeArguments());
    }
    throw new UnsupportedOperationException();
}
 
Example #21
Source File: Types.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static boolean withInLowerBounds(Type concrete, Sequence<Type> lowerBounds) {
    if (lowerBounds.isEmpty()) {
        return true;
    }
    if (Numbers.equalTo(lowerBounds.size(), 1)) {
        return (classOf(concrete)).isAssignableFrom(classOf(lowerBounds.first()));
    }
    throw new UnsupportedOperationException();
}
 
Example #22
Source File: OrPredicate.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
public static <T> LogicalPredicate<T> or(Iterable<? extends Predicate<? super T>> predicates) {
    Sequence<Predicate<T>> sequence = Sequences.sequence(predicates).<Predicate<T>>unsafeCast().
            flatMap(OrPredicate.<T>asPredicates());
    if (sequence.exists(instanceOf(AlwaysTrue.class))) return Predicates.alwaysTrue();

    Sequence<Predicate<T>> collapsed = sequence.
            filter(instanceOf(AlwaysFalse.class).not());
    if (collapsed.isEmpty()) return Predicates.alwaysFalse();
    if (collapsed.size() == 1) return logicalPredicate(collapsed.head());
    if (collapsed.forAll(instanceOf(Not.class)))
        return Predicates.not(Predicates.<T>and(sequence.<Not<T>>unsafeCast().map(Not.functions.<T>predicate())));
    return new OrPredicate<T>(sequence);
}
 
Example #23
Source File: SimpleConsoleTest.java    From java-repl with Apache License 2.0 5 votes vote down vote up
private static Matcher<ConsoleResult> hasLogged(final ConsoleLog... logs) {
    return new FeatureMatcher<ConsoleResult, Sequence<ConsoleLog>>(hasItems(logs), "console log", "console log") {
        protected Sequence<ConsoleLog> featureValueOf(ConsoleResult consoleResult) {
            return consoleResult.logs();
        }
    };
}
 
Example #24
Source File: ShowHistory.java    From java-repl with Apache License 2.0 5 votes vote down vote up
public void execute(String expression) {
    Integer limit = parseNumericCommand(expression).second().getOrElse(history.items().size());
    Sequence<String> numberedHistory = numberedHistory(history).reverse().take(limit).reverse();

    if (!numberedHistory.isEmpty()) {
        logger.success(listValues("History", numberedHistory));
    } else {
        logger.success("No history.");
    }
}
 
Example #25
Source File: ReplayAllEvaluations.java    From java-repl with Apache License 2.0 5 votes vote down vote up
public void execute(String line) {
    logger.success("Replaying all evaluations:");
    Sequence<Expression> expressions = evaluator.expressions().deleteAll(defaultExpressions());

    evaluator.reset();
    for (Expression expression : expressions) {
        evaluate(evaluator, logger, expression.source());
    }
}
 
Example #26
Source File: ContextTest.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSupportChild() throws Exception {
    String xml = "<stream><user><first>Dan &amp; Bod</first><dob>1977</dob></user><user><first>Jason</first><dob>1978</dob></user></stream>";
    Document document = document(xml);

    Sequence<Node> nodes = selectNodes(document, "child::*");
    Sequence<Context> locations = contexts(xml).filter(xpath(child(name("*"))));
    assertThat(locations.size(), is(nodes.size()));

    Node root = nodes.head();
    Context rootContext = locations.head();
    assertThat(rootContext.name(), is(root.getNodeName()));
}
 
Example #27
Source File: StaticMemberCompleter.java    From java-repl with Apache License 2.0 5 votes vote down vote up
private Option<Pair<Class<?>, String>> completionFor(String expression) {
    Option<Pair<String, Sequence<String>>> parsedClass = parseExpression(pair(expression, Sequences.empty(String.class)));

    if (!parsedClass.isEmpty() && !parsedClass.get().second().isEmpty()) {
        return some(Pair.<Class<?>, String>pair(
                evaluator.classFrom(parsedClass.get().first()).get(),
                parsedClass.get().second().toString(".").trim()));
    } else {
        return none();
    }
}
 
Example #28
Source File: ClassReflection.java    From java-repl with Apache License 2.0 5 votes vote down vote up
public Sequence<MemberReflection<?>> declaredMembers() {
    return empty()
            .join(declaredClasses())
            .join(declaredConstructors())
            .join(declaredFields())
            .join(declaredMethods())
            .unique()
            .unsafeCast();
}
 
Example #29
Source File: PersistentMap.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
@Override
Sequence<V> values();
 
Example #30
Source File: Xml.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
public static Sequence<Node> nodes(Reader reader, Predicate<Context> predicate) {
    return contexts(reader).filter(predicate).map(DomConverter::convert);
}