Java Code Examples for com.googlecode.totallylazy.Strings

The following examples show how to use com.googlecode.totallylazy.Strings. These examples are extracted from open source projects. 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 Project: java-repl   Source File: TypeCompleter.java    License: 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 Project: java-repl   Source File: LoadSourceFile.java    License: 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 3
Source Project: yatspec   Source File: ContentAtUrl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    InputStream inputStream = null;
    try {
        inputStream = url.openStream();
        return Strings.toString(inputStream);
    } catch (IOException e) {
        return e.toString();
    } finally {
        closeQuietly(inputStream);
    }
}
 
Example 4
Source Project: yatspec   Source File: TestMethodExtractor.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
private ScenarioTable getScenarioTable(JavaMethod method) {
    ScenarioTable table = new ScenarioTable();
    table.setHeaders(getNames(method.getParameters()));

    final Sequence<Annotation> rows = getRows(method);
    for (Annotation row : rows) {
        List<String> values = getRowValues(row);
        table.addRow(sequence(values).map(Strings.trim()).toList());
    }
    return table;
}
 
Example 5
Source Project: yatspec   Source File: HtmlResultRendererTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void supportsCustomHeaderContent() throws Exception {
    TestResult result = new TestResult(getClass());

    String html = new HtmlResultRenderer().
            withCustomHeaderContent(new ContentAtUrl(getClass().getResource("CustomHeaderContent.html"))).
            render(result);

    assertThat(html, containsString(Strings.toString(getClass().getResource("CustomHeaderContent.html").openStream())));
}
 
Example 6
Source Project: yatspec   Source File: HtmlResultRendererTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void supportsCustomJavaScript() throws Exception {
    TestResult result = new TestResult(getClass());

    String html = new HtmlResultRenderer().
            withCustomScripts(new ContentAtUrl(getClass().getResource("customJavaScript.js"))).
            render(result);

    assertThat(html, containsString(Strings.toString(getClass().getResource("customJavaScript.js").openStream())));
}
 
Example 7
Source Project: totallylazy   Source File: Validators.java    License: Apache License 2.0 5 votes vote down vote up
public static LogicalValidator<String> isNotBlank() {
    return new LogicalValidator<String>() {
        @Override
        public ValidationResult validate(String instance) {
            if (Strings.isBlank(instance))
                return failure(PLEASE_PROVIDE_A_VALUE);
            return pass();
        }
    };
}
 
Example 8
Source Project: totallylazy   Source File: Uri.java    License: Apache License 2.0 5 votes vote down vote up
public Uri mergePath(String value) {
    if (value.startsWith("/")) {
        return path(value);
    }

    if (authority() != null && path().equals(Strings.EMPTY)) {
        return path("/" + value);
    }

    return path(path().replaceFirst("([^/]*)$", value));
}
 
Example 9
Source Project: totallylazy   Source File: SelectionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void canReduce() throws Exception {
    Aggregate<String, String> minimumName = Aggregate.aggregate(name, Strings.minimum);
    Aggregate<Integer, Integer> minimumAge = Aggregate.aggregate(age, Integers.minimum());
    assertThat(data.reduce(minimumAge), is(21));
    assertThat(data.reduce(minimumName), is("Bob"));
    assertThat(data.reduce(select(minimumName, minimumAge)), is(map("name", "Bob", "age", 21)));
}
 
Example 10
Source Project: totallylazy   Source File: TemplatesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void registeredRenderersAreCorrectlyCalled() throws Exception {
    Templates templates = templates(getClass()).extension("st");
    templates.add(instanceOf(String.class), s -> Strings.string(s.hashCode()));
    String value = "Dan";
    assertThat(templates.get("hello").render(map("name", value)), is("Hello " + value.hashCode()));
    assertThat(templates.get("parent").render(map("name", value)), is("Say Hello " + value.hashCode()));
}
 
Example 11
Source Project: java-repl   Source File: WebConsoleClientHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void createProcess() {
    if (port.isEmpty()) {
        try {
            port = some(randomServerPort());
            ProcessBuilder builder = new ProcessBuilder("java", "-Xmx128M", "-cp", System.getProperty("java.class.path"), Repl.class.getCanonicalName(),
                    "--sandboxed", "--ignoreConsole", "--port=" + port.get(), "--expressionTimeout=5", "--inactivityTimeout=300", expression.map(Strings.format("--expression=%s")).getOrElse(""));
            builder.redirectErrorStream(true);
            process = some(builder.start());

            waitUntilProcessStarted();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 12
Source Project: java-repl   Source File: WebConsoleResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Hidden
@Path("snap/{id}")
@Produces(MediaType.TEXT_PLAIN)
public Response getSnap(@PathParam("id") String id) {
    File snap = snapFile(id);
    if (snap.exists()) {
        return ok().entity(Strings.lines(snap).toString("\n"));
    } else {
        return response(NOT_FOUND);
    }
}
 
Example 13
Source Project: java-repl   Source File: EvaluateFile.java    License: Apache License 2.0 5 votes vote down vote up
public void execute(String expression) {
    String path = parseStringCommand(expression).second().getOrNull();
    try {
        for (String line : Strings.lines(resolveURL(path).openStream())) {
            history.add(line);
            EvaluateExpression.evaluate(evaluator, logger, line);
        }

        logger.success(format("Finished evaluating %s", path));
    } catch (Exception e) {
        logger.error(format("Could evaluate %s. %s", path, e.getLocalizedMessage()));
    }
}
 
Example 14
Source Project: java-repl   Source File: ConsoleHistory.java    License: 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 15
Source Project: yatspec   Source File: Text.java    License: Apache License 2.0 4 votes vote down vote up
public static String wordify(String value) {
    final String wordified = quotedStrings.findMatches(value).replace(wordifier, doNothing);
    return Strings.capitalise(spaceRemover.matcher(wordified).replaceAll(" ").trim());
}
 
Example 16
Source Project: yatspec   Source File: Files.java    License: Apache License 2.0 4 votes vote down vote up
public static String replaceDotsWithSlashes(final String name) {
    return characters(name).map(dotsToSlashes()).toString(Strings.EMPTY, Strings.EMPTY, Strings.EMPTY);
}
 
Example 17
Source Project: yatspec   Source File: Files.java    License: Apache License 2.0 4 votes vote down vote up
public static String replaceDotsWithForwardSlashes(final String name) {
    return characters(name).map(dotsToForwardSlashes()).toString(Strings.EMPTY, Strings.EMPTY, Strings.EMPTY);
}
 
Example 18
Source Project: totallylazy   Source File: EqualsPredicate.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    return Strings.asString(value);
}
 
Example 19
Source Project: totallylazy   Source File: XPathFunctions.java    License: Apache License 2.0 4 votes vote down vote up
@XPathFunction("trim-and-join")
public static String trimAndJoin(NodeList nodes, String delimiter) {
    return Xml.textContents(nodes).map(Strings.trim()).toString(unescape(delimiter));
}
 
Example 20
Source Project: totallylazy   Source File: Renderer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Appendable render(Object instance, Appendable appendable) throws IOException {
    if(instance instanceof CharSequence) return appendable.append((CharSequence) instance);
    return appendable.append(Strings.asString(instance));
}
 
Example 21
Source Project: totallylazy   Source File: Uri.java    License: Apache License 2.0 4 votes vote down vote up
public Uri dropPath() {
    return path(Strings.EMPTY);
}
 
Example 22
Source Project: totallylazy   Source File: Uri.java    License: Apache License 2.0 4 votes vote down vote up
public Uri query(String value) {
    return new Uri(scheme, authority, path, Strings.isBlank(value) ? null : value, fragment);
}
 
Example 23
Source Project: totallylazy   Source File: Uri.java    License: Apache License 2.0 4 votes vote down vote up
public Uri removeDotSegments() {
    if(Strings.isEmpty(path)) return this;
    return path(DotSegments.remove(path));
}
 
Example 24
Source Project: totallylazy   Source File: EndsWithPredicateTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void supportsToString() throws Exception {
    assertThat(Strings.endsWith("13").toString(), Matchers.is("ends with '13'"));
}
 
Example 25
Source Project: totallylazy   Source File: EndsWithPredicateTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void supportsEqualityOnPredicateItself() throws Exception {
    assertThat(Strings.endsWith("13").equals(Strings.endsWith("13")), Matchers.is(true));
    assertThat(Strings.endsWith("13").equals(Strings.endsWith("14")), Matchers.is(false));
}
 
Example 26
Source Project: totallylazy   Source File: StartsWithPredicateTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void supportsToString() throws Exception {
    assertThat(Strings.startsWith("13").toString(), Matchers.is("starts with '13'"));
}
 
Example 27
Source Project: totallylazy   Source File: StartsWithPredicateTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void supportsEqualityOnPredicateItself() throws Exception {
    assertThat(Strings.startsWith("13").equals(Strings.startsWith("13")), Matchers.is(true));
    assertThat(Strings.startsWith("13").equals(Strings.startsWith("14")), Matchers.is(false));
}
 
Example 28
Source Project: totallylazy   Source File: ContainsPredicateTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void supportsToString() throws Exception {
    assertThat(Strings.contains("13").toString(), Matchers.is("contains '13'"));
}
 
Example 29
Source Project: totallylazy   Source File: ContainsPredicateTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void supportsEqualityOnPredicateItself() throws Exception {
    assertThat(Strings.contains("13").equals(Strings.contains("13")), Matchers.is(true));
    assertThat(Strings.contains("13").equals(Strings.contains("14")), Matchers.is(false));
}
 
Example 30
Source Project: java-repl   Source File: EvaluationClassRenderer.java    License: Apache License 2.0 4 votes vote down vote up
private static String renderPreviousMethods(EvaluationContext context) {
    return context.expressionsOfType(Method.class)
            .map(source().then(replaceAll("\n", "\n  ")).then(Strings.format("  %s")))
            .toString("\n\n");
}