Skip to content
/ term4j Public

Simplify manipulations with CLI terminal(s) for Java-based applications

License

Notifications You must be signed in to change notification settings

dgroup/term4j

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

76 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Maven Javadocs License: MIT Commit activity Hits-of-Code

Build Status 0pdd Dependency Status Known Vulnerabilities

DevOps By Rultor.com EO badge We recommend IntelliJ IDEA

Qulice SQ maintainability Codebeat Codacy Badge Codecov

What it is

term4j is an object-oriented primitives to simplify the manipulations with CLI terminal(s) for Java-based applications.

Principles

Design principles behind term4j.

How to use

Get the latest version here:

<dependency>
    <groupId>io.github.dgroup</groupId>
    <artifactId>term4j</artifactId>
    <version>${version}</version>
</dependency>

Java version required: 1.8+.

Interface Purpose Implementations / Related
Arg<T> Allows to fetch the application arguments StringOf, NumberOf, PathOf, FileOf, EnvOf, PropOf, Alt, Unchecked, etc
Input Wrap the raw manipulation with std in StdOf, Inmem, etc
Output Wrap the raw manipulation with std out StdOf, Inmem, etc
Highlighted The colored extension of Text for std out Green, Red, Yellow, etc
Runtime Wrap the raw manipulation with JVM runtime RuntimeOf, FakeRuntime, AppException, Stacktrace, etc

All examples below are using the following frameworks/libs:

  • Hamcrest - Library of matchers, which can be combined in to create flexible expressions of intent in tests.
  • cactoos - Object-Oriented Java primitives, as an alternative to Google Guava and Apache Commons.
  • cactoos-matchers - Object-Oriented Hamcrest matchers

Fetch the string/Text argument:

$ java -jar app.jar --key vOIkv7mzQV2UkV1
public static void main(String[] cargs) {
    final List<String> args = new ListOf<>(cargs);
    MatcherAssert.assertThat(
        "The argument '--key' has value 'vOIkv7mzQV2UkV1'",
        new StringOf("--key", args),
        new ArgHas<>("vOIkv7mzQV2UkV1")
    );
    // or
    final Arg<String> key = new StringOf("--key", args);
}

Fetch the numeric argument:

$ java -jar app.jar -t 10
public static void main(String[] cargs) throws ArgNotFoundException {
    final List<String> args = new ListOf<>(cargs);
    MatcherAssert.assertThat(
        "The argument '-t' has value '10'",
        new NumberOf("-t", args).toInt(),
        new IsEqual<>(10)
    );
    // or
    final int threads = new NumberOf("-t", args).toInt();
}

Fetch the argument as a java.nio.file.Path or java.io.File:

$ java -jar app.jar -f ./readme.md
public static void main(String[] cargs) throws ArgNotFoundException {
    final List<String> args = new ListOf<>(cargs);
    MatcherAssert.assertThat(
        "The argument '-f' has path './readme.md'",
        new PathOf("-f", args),
        new ArgHas<>(Paths.get(".", "readme.md"))
    );
    // or
    final Arg<Path> src = new PathOf("-f", args);
}

Fetch the environment variable:

$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home
public static void main(String[] cargs) throws ArgNotFoundException {
    final List<String> args = new ListOf<>(cargs);
    MatcherAssert.assertThat(
        "The environment variable 'JAVA_HOME' has 1.8.0_181",
        new EnvOf("JAVA_HOME").value(),
        new StringContains("1.8.0_181")
    );
    // or
    final Arg<String> jhome = new EnvOf("JAVA_HOME");
}

Fetch the application property:

$ java -Dlevel=debug -jar app.jar
public static void main(String[] cargs) throws ArgNotFoundException {
    final List<String> args = new ListOf<>(cargs);
    MatcherAssert.assertThat(
        "The application property 'level' is 'debug'",
        new PropOf("level"),
        new ArgHas<>("debug")
    );
    // or
    final Arg<String> verbose = new PropOf("level");
}

The alternative value in case if the argument wasn't specified:

$ java -jar app.jar
public static void main(String[] cargs) {
    final List<String> args = new ListOf<>(cargs);
    MatcherAssert.assertThat(
        "The argument '--key' is using default value 'vOIkv7mzQV2UkV1'",
        new Alt(
            new StringOf("--key", args),
            "vOIkv7mzQV2UkV1"
        ),
        new ArgHas<>("vOIkv7mzQV2UkV1")
    );
    // or
    final Arg<String> key = new Alt(
        new StringOf("--key", args), "vOIkv7mzQV2UkV1"
    );
}

Wrap the std out, for example for unit testing purposes:

    /**
     * Simulate the STD input procedure.
     */
    @Test
    public void readFromStdin() {
        /**
         * The standard system input (stdin) which keeps the expected input lines in-memory
         *  instead of direct manipulations with {@link System#in} or {@link Console}.
         */
        final Input stdin = new Stdin(
            new InputOf(String.format("line1%nline2"))
        );
        MatcherAssert.assertThat(
            "The 1st line was read from console",
            stdin.value(),
            new IsEqual("line1")
        );
        MatcherAssert.assertThat(
            "The 2nd line was read from console",
            stdin.value(),
            new IsEqual("line2")
        );
    }

Wrap the std out, for example for unit testing purposes:

    /**
     * Simulate the STD print procedure using {@link StringWriter}.
     */
    @Test
    public void printToWriter() {
        // Write 4 lines delimited by `\n` or `\r\n` to the StringWriter
        final StringWriter swter = new StringWriter();
        final Output std = new Stdout(swter);
        std.print("line1", "line2");
        std.print("line3", "line4");
        // Check that the result string has 4 lines
        MatcherAssert.assertThat(
            "4 lines of text were printed to the output",
            swter.toString(),
            new HasLines("line1", "line2", "line3", "line4")
        );
    }

Print colored text to the std out:

public static void main(String[] cargs) {
    System.out.printf(
        "%n Status: [%s|%s] %n", new Green("Passed"), new Red("Failed")
    );
}

Colored message

See more.

RuntimeOf

Exit from application using particular exit code:

public static void main(String[] cargs) {
    try {
        // application exception happens
    } catch (final AppException cause) {
        new RuntimeOf().shutdownWith(
            cause.exitCode()
        );
    }
}