com.googlecode.totallylazy.Sequences Java Examples

The following examples show how to use com.googlecode.totallylazy.Sequences. 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: EvaluationClassRendererTest.java    From java-repl with Apache License 2.0 6 votes vote down vote up
@Test
public void rendersTemplateForMethod() {
    assertThat(renderExpressionClass(evaluationContext(), "AClass", new Method("someMethod", Object.class, "someMethodName", Sequences.<Class<?>>empty())), is(new StringBuilder()
            .append("import java.lang.*;\n")
            .append("import java.util.*;\n")
            .append("import java.math.*;\n")
            .append("import static java.lang.Math.*;\n")
            .append("import java.util.function.*;\n")
            .append("public final class AClass extends javarepl.EvaluationTemplate {\n")
            .append("  public AClass(javarepl.EvaluationContext context) { super(context); }\n")
            .append("  $JAVAREPL_EXPRESSION_TOKEN$\n")
            .append("\n")
            .append("  public void evaluate() throws Exception {\n")
            .append("  }\n")
            .append("}")
            .toString()));
}
 
Example #2
Source File: DotSegments.java    From totallylazy with Apache License 2.0 6 votes vote down vote up
public static String remove(String path) {
    final Deque<CharSequence> segments = new ArrayDeque<CharSequence>();
    segment.findMatches(path).replace(notMatched -> {
        segments.add(notMatched);
        return null;
    }, match -> {
        switch (match.group(1)) {
            case ".":
                return null;
            case "..":
                if (!segments.isEmpty()) segments.removeLast();
                break;
            default:
                segments.add(match.group());
                break;
        }
        return null;
    });
    return Sequences.toString(segments, "");
}
 
Example #3
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 #4
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 #5
Source File: EvaluationClassRendererTest.java    From java-repl with Apache License 2.0 5 votes vote down vote up
@Test
public void rendersPreviousResultsMethodsAndImports() {
    EvaluationContext context = evaluationContext()
            .addResult(result("result1", "value1"))
            .addResult(result("result2", "value2"))
            .addExpression(new Import("import java.net.URL", "java.net.URL"))
            .addExpression(new Import("import java.io.File;", "java.io.File"))
            .addExpression(new Method("int method1(int i){\nreturn i;\n}", int.class, "method1", Sequences.<Class<?>>sequence(int.class)))
            .addExpression(new Method("char method1(char i){\nreturn i;\n}", char.class, "method2", Sequences.<Class<?>>sequence(char.class)));

    assertThat(renderExpressionClass(context, "AClass", new Statement("someStatement")), is(new StringBuilder()
            .append("import java.lang.*;\n")
            .append("import java.util.*;\n")
            .append("import java.math.*;\n")
            .append("import static java.lang.Math.*;\n")
            .append("import java.util.function.*;\n")
            .append("import java.net.URL;\n")
            .append("import java.io.File;;\n")
            .append("public final class AClass extends javarepl.EvaluationTemplate {\n")
            .append("  public AClass(javarepl.EvaluationContext context) { super(context); }\n")
            .append("  public java.lang.String result1 = valueOf(\"result1\");\n")
            .append("  public java.lang.String result2 = valueOf(\"result2\");\n")
            .append("  int method1(int i){\n")
            .append("  return i;\n")
            .append("  }\n")
            .append("\n")
            .append("  char method1(char i){\n")
            .append("  return i;\n")
            .append("  }\n")
            .append("  public void evaluate() throws Exception {\n")
            .append("    $JAVAREPL_EXPRESSION_TOKEN$;\n")
            .append("  }\n")
            .append("}")
            .toString()));
}
 
Example #6
Source File: GroupByTransducer.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
@Override
default Receiver<T> apply(Receiver<Group<K, T>> receiver) {
    return new Receiver<T>() {
        private final Map<K, Group<K, T>> groups = new ConcurrentHashMap<>();

        @Override
        public State start() {
            receivers().each(Receiver::start);
            return receiver.start();
        }

        @Override
        public State next(T item) {
            groups.computeIfAbsent(keyExtractor().apply(item), k -> {
                Group<K, T> group = new Group<>(k);
                receiver.next(group);
                return group;
            }).next(item);
            return State.Continue;
        }

        @Override
        public State error(Throwable throwable) {
            receivers().each(o -> o.error(throwable));
            return receiver.error(throwable);
        }

        @Override
        public void finish() {
            receivers().each(Receiver::finish);
            receiver.finish();
        }

        private Sequence<Receiver<T>> receivers() {
            return Sequences.sequence(groups.values());
        }
    };
}
 
Example #7
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 #8
Source File: AndPredicate.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
public static <T> LogicalPredicate<T> and(Iterable<? extends Predicate<? super T>> predicates) {
    Sequence<Predicate<T>> sequence = Sequences.sequence(predicates).<Predicate<T>>unsafeCast().
            flatMap(AndPredicate.<T>asPredicates());
    if (sequence.exists(instanceOf(AlwaysFalse.class))) return Predicates.alwaysFalse();

    Sequence<Predicate<T>> collapsed = sequence.
            filter(instanceOf(AlwaysTrue.class).not());
    if (collapsed.isEmpty()) return Predicates.alwaysTrue();
    if (collapsed.size() == 1) return logicalPredicate(collapsed.head());
    if (collapsed.forAll(instanceOf(Not.class)))
        return Predicates.not(Predicates.<T>or(sequence.<Not<T>>unsafeCast().map(Not.functions.<T>predicate())));
    return new AndPredicate<T>(collapsed);
}
 
Example #9
Source File: Xml.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
private static Sequence<Node> internalSelectNodes(final Node node, final String expression) {
    try {
        return sequence((NodeList) xpathExpression(expression).evaluate(node, XPathConstants.NODESET));
    } catch (XPathExpressionException e) {
        try {
            String nodeAsString = (String) xpathExpression(expression).evaluate(node, XPathConstants.STRING);
            return Sequences.<Node>sequence(documentFor(node).createTextNode(nodeAsString));
        } catch (XPathExpressionException ignore) {
            throw new IllegalArgumentException(String.format("Failed to compile xpath '%s'", expression), e);
        }
    }
}
 
Example #10
Source File: NumbersTest.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
/**
 * Test case for issue #14
 */
@Test
public void supportsShort() {
    assertThat(numbers((short)0, (short)0 ,(short)1).reduceLeft(Numbers.maximum), NumberMatcher.is((short) 1));

    Sequence<Short> s = Sequences.sequence((short)0, (short)0 ,(short)1);
    Number result = s.reduceLeft(Numbers.maximum());
    assertEquals(Short.class, result.getClass());
    assertThat(result, NumberMatcher.is(Short.valueOf((short) 1)));
}
 
Example #11
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 #12
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 #13
Source File: InstanceMemberCompleter.java    From java-repl with Apache License 2.0 5 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);
    final Boolean canComplete = packagePart.matches("[a-zA-Z0-9\\$_\\\\.\\(\\[\\]]*") && packagePart.contains(".");

    final int beginIndex = packagePart.lastIndexOf('.') + 1;
    Option<Class<?>> aClass = canComplete
            ? evaluator.typeOfExpression(packagePart.substring(0, beginIndex - 1)).map(Types::classOf)
            : none();

    if (aClass.isDefined()) {
        ClassReflection classReflection = reflectionOf(aClass.get());

        Sequence<MemberReflection<?>> join = Sequences.empty()
                .join(classReflection.declaredFields())
                .join(classReflection.declaredMethods())
                .unique()
                .unsafeCast();

        Sequence<CompletionCandidate> candidates = join
                .filter(isPublic().and(not(isStatic())))
                .groupBy(candidateName())
                .map(candidate())
                .filter(where(CompletionCandidate::value, startsWith(packagePart.substring(beginIndex))));

        return new CompletionResult(expression, lastSeparator + beginIndex, candidates);
    } else {
        return new CompletionResult(expression, 0, Sequences.empty(CompletionCandidate.class));
    }
}
 
Example #14
Source File: CompletionResult.java    From java-repl with Apache License 2.0 5 votes vote down vote up
public static CompletionResult fromJson(String json) {
    Map<String, Object> jsonMap = map(Json.map(json));

    Sequence<Map<String, Object>> candidates = CANDIDATES.map(Sequences::sequence).apply(jsonMap);

    return new CompletionResult(
            EXPRESSION.apply(jsonMap),
            POSITION.map(Integer::valueOf).apply(jsonMap),
            candidates.map(candidate -> new CompletionCandidate(VALUE.apply(candidate), FORMS.map(Sequences::sequence).apply(candidate)))
    );
}
 
Example #15
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 #16
Source File: ByNamingConventionMessageProducer.java    From yatspec with Apache License 2.0 5 votes vote down vote up
public Iterable<SequenceDiagramMessage> messages(CapturedInputAndOutputs inputAndOutputs) {
    Sequence<SequenceDiagramMessage> result = Sequences.empty();
    Set<String> keys = inputAndOutputs.getTypes().keySet();
    for (String key : keys) {
        Matcher matcher = pattern.matcher(key);
        if (matcher.matches()) {
            final String what = matcher.group(1).trim();
            final String from = matcher.group(2).trim();
            final String to = matcher.group(3).trim();
            result = result.append(new SequenceDiagramMessage(from, to, what, key.replaceAll(" ","_").replaceAll("\\(","_").replaceAll("\\)","_")));
        }
    }
    return result;
}
 
Example #17
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 #18
Source File: JavaREPLClient.java    From java-repl with Apache License 2.0 5 votes vote down vote up
public synchronized Option<EvaluationResult> execute(String expr) throws Exception {
    String json = client.handle(post(url("execute")).form("expression", expr)).entity().toString();

    if (json.isEmpty())
        return none();

    Map<String, Object> response = map(json);
    Sequence<Map<String, Object>> logs = LOGS.map(Sequences::sequence).call(response);
    String expression = EXPRESSION.call(response);

    return some(new EvaluationResult(expression, logs.map(modelToEvaluationLog())));
}
 
Example #19
Source File: PredicatesTest.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
@Test
public void supportsSupersetOf() throws Exception {
    assertThat(supersetOf(sequence("a")).matches(sequence("a", "b")), is(true));
    assertThat(supersetOf(sequence("a", "b")).matches(sequence("a")), is(false));
    assertThat(supersetOf(Sequences.<String>sequence()).matches(sequence("a")), is(true));
}
 
Example #20
Source File: ShowHistory.java    From java-repl with Apache License 2.0 4 votes vote down vote up
public static Sequence<String> numberedHistory(ConsoleHistory consoleHistory) {
    return Numbers.range(1)
            .zip(consoleHistory.items().map(replace("\n", "\n   ")))
            .map(values().then(Sequences.toString("  ")));
}
 
Example #21
Source File: ListMap.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
public static <K, V> PersistentMap<K, V> listMap(K key1, V value1, K key2, V value2, K key3, V value3, K key4, V value4) {
    return listMap(Sequences.sequence(pair(key1, value1), pair(key2, value2), pair(key3, value3), pair(key4, value4)));
}
 
Example #22
Source File: Comparators.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
public static <T> Comparator<T> comparators(final Comparator<? super T>  first, final Comparator<? super T>  second) {
    return comparators(Sequences.<Comparator<? super T>>sequence(first, second));
}
 
Example #23
Source File: AbstractMap.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
@Override
public Set<Entry<K, V>> entrySet() {
    return Sequences.<Entry<K, V>>sequence(this).toSet();
}
 
Example #24
Source File: Comparators.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
public static <T> Comparator<T> comparators(final Comparator<? super T>  first) {
    return comparators(Sequences.<Comparator<? super T>>sequence(first));
}
 
Example #25
Source File: Numbers.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
public static Function1<Iterable<Number>, Number> sumIterable() {
    return numbers -> Sequences.reduceLeft(numbers, sum());
}
 
Example #26
Source File: Context.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    return Sequences.toString(path(), "/");
}
 
Example #27
Source File: Xml.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
public static Sequence<Node> selectNodesForwardOnly(final Node node, final String expression) {
    return Sequences.forwardOnly(new PoppingIterator<Node>(selectNodes(node, expression).toList().iterator()));
}
 
Example #28
Source File: HashTreeMap.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
@Override
public Iterator<Pair<K, V>> iterator() {
    return hash.values().flatMap(Sequences.<Pair<K, V>>identity()).iterator();
}
 
Example #29
Source File: ListMap.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
public static <K, V> PersistentMap<K, V> listMap(K key1, V value1, K key2, V value2, K key3, V value3, K key4, V value4, K key5, V value5) {
    return listMap(Sequences.sequence(pair(key1, value1), pair(key2, value2), pair(key3, value3), pair(key4, value4), pair(key5, value5)));
}
 
Example #30
Source File: ListMap.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
public static <K, V> PersistentMap<K, V> listMap(Iterable<? extends Pair<K, V>> pairs) {
    return listMap(reverse(Sequences.sequence((pairs))));
}