com.googlecode.totallylazy.Strings Java Examples

The following examples show how to use com.googlecode.totallylazy.Strings. 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: 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 #2
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 #3
Source File: TestMethodExtractor.java    From yatspec with 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 #4
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 #5
Source File: EvaluateFile.java    From java-repl with 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 #6
Source File: WebConsoleResource.java    From java-repl with 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 #7
Source File: WebConsoleClientHandler.java    From java-repl with 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 #8
Source File: TemplatesTest.java    From totallylazy with 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 #9
Source File: SelectionTest.java    From totallylazy with 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 File: Uri.java    From totallylazy with 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 #11
Source File: ContentAtUrl.java    From yatspec with 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 #12
Source File: HtmlResultRendererTest.java    From yatspec with 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 #13
Source File: HtmlResultRendererTest.java    From yatspec with 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 #14
Source File: Validators.java    From totallylazy with 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 #15
Source File: EqualsPredicate.java    From totallylazy with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    return Strings.asString(value);
}
 
Example #16
Source File: Text.java    From yatspec with 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 #17
Source File: Files.java    From yatspec with 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 #18
Source File: Main.java    From java-repl with Apache License 2.0 4 votes vote down vote up
private static Function1<File, Sequence<String>> readExpressionsFile() {
    return f -> sequence(Files.readAllLines(f.toPath(), StandardCharsets.UTF_8)).filter(not(Strings::isBlank));
}
 
Example #19
Source File: Files.java    From yatspec with 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 #20
Source File: EvaluationClassRenderer.java    From java-repl with Apache License 2.0 4 votes vote down vote up
private static String renderPreviousImports(EvaluationContext context) {
    return context.expressionsOfType(Import.class)
            .map(source().then(Strings.format("%s;")))
            .toString("\n");
}
 
Example #21
Source File: EvaluationClassRenderer.java    From java-repl with 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");
}
 
Example #22
Source File: Renderer.java    From totallylazy with 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 #23
Source File: ContainsPredicateTest.java    From totallylazy with 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 #24
Source File: ContainsPredicateTest.java    From totallylazy with 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 #25
Source File: StartsWithPredicateTest.java    From totallylazy with 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 #26
Source File: StartsWithPredicateTest.java    From totallylazy with 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 File: EndsWithPredicateTest.java    From totallylazy with 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 #28
Source File: EndsWithPredicateTest.java    From totallylazy with 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 #29
Source File: Uri.java    From totallylazy with 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 #30
Source File: Uri.java    From totallylazy with 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);
}