Java Examples for org.fusesource.jansi.Ansi

The following java examples will help you to understand the usage of org.fusesource.jansi.Ansi. These source code samples are taken from different open source projects.

Example 1
Project: detective-master  File: ResultRenderAnsiConsoleImpl.java View source code
Ansi createAnsiCode(JobRunResult result) {
    Ansi ansi = ansi();
    Color currentColor;
    if (result.isIgnored()) {
        currentColor = BLUE;
    } else if (result.getSuccessed())
        currentColor = GREEN;
    else
        currentColor = RED;
    ansi.fg(currentColor);
    ansi.bold().a("Story Name: ").a(result.getStoryName()).boldOff().a("\n").bold().a("| -- Scenario Name: ").boldOff().a(result.getScenarioName());
    if (result.isIgnored()) {
        ansi.a("\n").bold().a("| -- Ignored:       Yes").boldOff();
    } else {
        ansi.a("\n").bold().a("| -- Successed:     ").boldOff().a(result.getSuccessed() ? "Yes" : "Failed");
    }
    ansi.a("\n");
    renderSteps(ansi, result.getSteps(), currentColor);
    if (result.getError() != null) {
        ansi.bold().a("| -- Error:         ").a(result.getError().getMessage()).boldOff().a("\n");
        ansi.bold().a("| -- Error Callstack:").boldOff().a(Utils.getStackTrace(result.getError())).a("\n");
    }
    ansi.reset();
    return ansi;
}
Example 2
Project: lumen-master  File: CompileCommandLine.java View source code
private void compileSource(String src, String file) {
    Driver driver = new Driver(src, deps);
    TokenSource lexer = driver.phase1Scanning(keywordsToIgnore);
    ProgramNode program = driver.phase2Parsing(lexer);
    driver.phase3Resolving(program);
    driver.phase4Analysis(program);
    String name = program.getClassNode().getName();
    saveBytecode(driver.phase5Bytecode(program), name, file);
    Ansi ansi = Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).fg(Ansi.Color.GREEN).a("Successfully compiled " + file).reset();
    System.out.println(ansi);
}
Example 3
Project: tetris4j-master  File: TetrisView.java View source code
@Override
public void showStartScreen() {
    gameState = GameState.MainMenu;
    AnsiConsole.out.print(Ansi.ansi().cursor(0, 0));
    AnsiConsole.out.print(Ansi.ansi().eraseScreen());
    String[] heading = Utils.readLines("/heading.txt");
    for (String s : heading) {
        AnsiConsole.out.println(Ansi.ansi().fg(Color.YELLOW).a("\t" + s).reset());
    }
    AnsiConsole.out.println();
    AnsiConsole.out.println();
    AnsiConsole.out.println();
    String[] menu = Utils.readLines("/menu.txt");
    for (String s : menu) {
        AnsiConsole.out.println(Ansi.ansi().fg(Color.BLUE).a(s).reset());
    }
}
Example 4
Project: Torch-master  File: ColouredConsoleSender.java View source code
@Override
public void sendMessage(String message) {
    if (terminal.isAnsiSupported()) {
        if (!conversationTracker.isConversingModaly()) {
            String result = message;
            for (ChatColor color : colors) {
                if (replacements.containsKey(color)) {
                    result = result.replaceAll("(?i)" + color.toString(), replacements.get(color));
                } else {
                    result = result.replaceAll("(?i)" + color.toString(), "");
                }
            }
            System.out.println(result + Ansi.ansi().reset().toString());
        }
    } else {
        super.sendMessage(message);
    }
}
Example 5
Project: cli-master  File: MultiRemoteCodenvy.java View source code
protected List<UserProjectReference> getProjects(String remoteName, boolean onlyPublic) {
    Codenvy codenvy = readyRemotes.get(remoteName);
    if (codenvy == null) {
        Ansi buffer = Ansi.ansi();
        buffer.fg(RED);
        buffer.a(String.format("The remote %s doesn't exists", remoteName));
        buffer.reset();
        System.out.println(buffer.toString());
        return Collections.emptyList();
    }
    return getProjects(remoteName, codenvy, onlyPublic);
}
Example 6
Project: shell-master  File: JLineShell.java View source code
@Override
public void setPromptPath(final String path, final boolean overrideStyle) {
    if (reader.getTerminal().isAnsiSupported()) {
        // ANSIBuffer ansi = JLineLogHandler.getANSIBuffer();
        Ansi ansi = ansi();
        if (path == null || "".equals(path)) {
            shellPrompt = ansi.fg(Color.YELLOW).a(getPromptText()).reset().toString();
        } else {
            if (overrideStyle) {
                ansi.a(path);
            } else {
                ansi.fg(Color.CYAN).a(path).reset();
            }
            shellPrompt = ansi.fg(Color.YELLOW).a(" " + getPromptText()).toString();
        }
    } else {
        // The superclass will do for this non-ANSI terminal
        super.setPromptPath(path);
    }
    // The shellPrompt is now correct; let's ensure it now gets used
    reader.setPrompt(AbstractShell.shellPrompt);
}
Example 7
Project: spring-shell-master  File: JLineShell.java View source code
@Override
public void setPromptPath(final String path, final boolean overrideStyle) {
    if (reader.getTerminal().isAnsiSupported()) {
        // ANSIBuffer ansi = JLineLogHandler.getANSIBuffer();
        Ansi ansi = ansi();
        if (path == null || "".equals(path)) {
            shellPrompt = ansi.fg(Color.YELLOW).a(getPromptText()).reset().toString();
        } else {
            if (overrideStyle) {
                ansi.a(path);
            } else {
                ansi.fg(Color.CYAN).a(path).reset();
            }
            shellPrompt = ansi.fg(Color.YELLOW).a(" " + getPromptText()).toString();
        }
    } else {
        // The superclass will do for this non-ANSI terminal
        super.setPromptPath(path);
    }
    // The shellPrompt is now correct; let's ensure it now gets used
    reader.setPrompt(AbstractShell.shellPrompt);
}
Example 8
Project: GeoGig-master  File: Diff.java View source code
public static void print(GeoGIG geogig, ConsoleReader console, DiffSummary<BoundingBox, BoundingBox> diffBounds) throws IOException {
    BoundingBox left = diffBounds.getLeft();
    BoundingBox right = diffBounds.getRight();
    Optional<BoundingBox> mergedResult = diffBounds.getMergedResult();
    BoundingBox both = new ReferencedEnvelope();
    if (mergedResult.isPresent()) {
        both = mergedResult.get();
    }
    Ansi ansi = AnsiDecorator.newAnsi(console.getTerminal().isAnsiSupported());
    ansi.a("left:  ").a(bounds(left)).newline();
    ansi.a("right: ").a(bounds(right)).newline();
    ansi.a("both:  ").a(bounds(both)).newline();
    ansi.a("CRS:   ").a(CRS.toSRS(left.getCoordinateReferenceSystem())).newline();
    console.print(ansi.toString());
}
Example 9
Project: gig-master  File: Diff.java View source code
public static void print(GeoGIG geogig, ConsoleReader console, DiffSummary<BoundingBox, BoundingBox> diffBounds) throws IOException {
    BoundingBox left = diffBounds.getLeft();
    BoundingBox right = diffBounds.getRight();
    Optional<BoundingBox> mergedResult = diffBounds.getMergedResult();
    BoundingBox both = new ReferencedEnvelope();
    if (mergedResult.isPresent()) {
        both = mergedResult.get();
    }
    Ansi ansi = AnsiDecorator.newAnsi(console.getTerminal().isAnsiSupported());
    ansi.a("left:  ").a(bounds(left)).newline();
    ansi.a("right: ").a(bounds(right)).newline();
    ansi.a("both:  ").a(bounds(both)).newline();
    ansi.a("CRS:   ").a(CRS.toSRS(left.getCoordinateReferenceSystem())).newline();
    console.print(ansi.toString());
}
Example 10
Project: cloudify-master  File: GigaShellMain.java View source code
/**
	 * This is the shell's main method. It starts the shell, sets the logging configurations, and the proxy if
	 * configured. Arguments, if passed, are expected in 1 of these 2 formats: -f <file_name> OR <command 1>;<command
	 * 2>;<command 3>;.... Passing commands set the interactive mode off.
	 *
	 * @param args
	 *            The commands to be executed, either in a file or as a list.
	 * @throws Exception
	 *             Reporting a failure to start the shell or execute the commands
	 */
public static void main(final String[] args) throws Exception {
    String[] actualArgs = args;
    initializeLogConfiguration();
    initializeProxyConfiguration();
    InputStream is = null;
    SequenceInputStream sis = null;
    final InputStream exitInputStream = new ByteArrayInputStream(EXIT_COMMAND.getBytes());
    boolean isInteractive = true;
    try {
        if (args.length > 0) {
            isInteractive = false;
            if (args[0].startsWith("-f=")) {
                final String filename = args[0].substring("-f=".length());
                final File file = new File(filename);
                if (!file.exists()) {
                    throw new IllegalArgumentException(filename + " does not exist");
                }
                is = new FileInputStream(filename);
            } else {
                String commandString = "";
                for (String arg : args) {
                    commandString = commandString.concat(arg + " ");
                }
                if (!commandString.endsWith(";")) {
                    commandString = commandString.concat(";");
                }
                commandString = commandString.replace(";", System.getProperty("line.separator"));
                is = new ByteArrayInputStream(commandString.getBytes("UTF-8"));
            }
            sis = new SequenceInputStream(is, exitInputStream);
            System.setIn(sis);
            actualArgs = new String[0];
        }
        instance = new GigaShellMain(isInteractive);
        instance.setApplication("cloudify");
        Ansi.ansi();
        instance.run(actualArgs);
    } finally {
        if (is != null) {
            is.close();
        }
        if (sis != null) {
            sis.close();
        }
        exitInputStream.close();
    }
}
Example 11
Project: ddf-catalog-master  File: SearchCommand.java View source code
@Override
protected Object doExecute() throws Exception {
    String formatString = "%1$-33s %2$-26s %3$-" + TITLE_MAX_LENGTH + "s %4$-" + EXCERPT_MAX_LENGTH + "s%n";
    CatalogFacade catalogProvider = getCatalog();
    Filter filter = null;
    if (cqlFilter != null) {
        filter = CQL.toFilter(cqlFilter);
    } else {
        if (searchPhrase == null) {
            searchPhrase = "*";
        }
        if (caseSensitive) {
            filter = getFilterBuilder().attribute(Metacard.ANY_TEXT).is().like().caseSensitiveText(searchPhrase);
        } else {
            filter = getFilterBuilder().attribute(Metacard.ANY_TEXT).is().like().text(searchPhrase);
        }
    }
    QueryImpl query = new QueryImpl(filter);
    query.setRequestsTotalResultsCount(true);
    if (numberOfItems > -1) {
        query.setPageSize(numberOfItems);
    }
    long start = System.currentTimeMillis();
    SourceResponse response = catalogProvider.query(new QueryRequestImpl(query));
    long end = System.currentTimeMillis();
    int size = 0;
    if (response.getResults() != null) {
        size = response.getResults().size();
    }
    console.println();
    console.printf(" %d result(s) out of %s%d%s in %3.3f seconds", (size), Ansi.ansi().fg(Ansi.Color.CYAN).toString(), response.getHits(), Ansi.ansi().reset().toString(), (end - start) / MILLISECONDS_PER_SECOND);
    console.printf(formatString, "", "", "", "");
    printHeaderMessage(String.format(formatString, ID, DATE, TITLE, EXCERPT));
    for (Result result : response.getResults()) {
        Metacard metacard = result.getMetacard();
        String title = (metacard.getTitle() != null ? metacard.getTitle() : "N/A");
        String excerpt = "N/A";
        String modifiedDate = "";
        if (searchPhrase != null) {
            if (metacard.getMetadata() != null) {
                XPathHelper helper = new XPathHelper(metacard.getMetadata());
                String indexedText = helper.getDocument().getDocumentElement().getTextContent();
                indexedText = indexedText.replaceAll("\\r\\n|\\r|\\n", " ");
                String normalizedSearchPhrase = searchPhrase.replaceAll("\\*", "");
                int index = -1;
                if (caseSensitive) {
                    index = indexedText.indexOf(normalizedSearchPhrase);
                } else {
                    index = indexedText.toLowerCase().indexOf(normalizedSearchPhrase.toLowerCase());
                }
                if (index != -1) {
                    int contextLength = (EXCERPT_MAX_LENGTH - normalizedSearchPhrase.length() - 8) / 2;
                    excerpt = "..." + indexedText.substring(Math.max(index - contextLength, 0), index);
                    excerpt = excerpt + Ansi.ansi().fg(Ansi.Color.GREEN).toString();
                    excerpt = excerpt + indexedText.substring(index, index + normalizedSearchPhrase.length());
                    excerpt = excerpt + Ansi.ansi().reset().toString();
                    excerpt = excerpt + indexedText.substring(index + normalizedSearchPhrase.length(), Math.min(indexedText.length(), index + normalizedSearchPhrase.length() + contextLength)) + "...";
                }
            }
        }
        if (metacard.getModifiedDate() != null) {
            modifiedDate = new DateTime(metacard.getModifiedDate().getTime()).toString(DATETIME_FORMATTER);
        }
        console.printf(formatString, metacard.getId(), modifiedDate, title.substring(0, Math.min(title.length(), TITLE_MAX_LENGTH)), excerpt);
    }
    return null;
}
Example 12
Project: ddf-master  File: IngestCommand.java View source code
@Override
protected Object executeWithSubject() throws Exception {
    if (batchSize * multithreaded > MAX_QUEUE_SIZE) {
        throw new IngestException(String.format("batchsize * multithreaded cannot be larger than %d.", MAX_QUEUE_SIZE));
    }
    final File inputFile = getInputFile();
    if (inputFile == null) {
        return null;
    }
    int totalFiles = totalFileCount(inputFile);
    fileCount.set(totalFiles);
    final ArrayBlockingQueue<Metacard> metacardQueue = new ArrayBlockingQueue<>(batchSize * multithreaded);
    ExecutorService queueExecutor = Executors.newSingleThreadExecutor();
    final long start = System.currentTimeMillis();
    printProgressAndFlush(start, fileCount.get(), 0);
    // Registering for the main thread and on behalf of the buildQueue thread;
    // the buildQueue thread will unregister itself when the files have all
    // been added to the blocking queue and the final registration will
    // be held for the await.
    phaser.register();
    phaser.register();
    queueExecutor.submit(() -> buildQueue(inputFile, metacardQueue, start));
    final ScheduledExecutorService batchScheduler = Executors.newSingleThreadScheduledExecutor();
    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(multithreaded);
    RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
    ExecutorService executorService = new ThreadPoolExecutor(multithreaded, multithreaded, 0L, TimeUnit.MILLISECONDS, blockingQueue, rejectedExecutionHandler);
    final CatalogFacade catalog = getCatalog();
    submitToCatalog(batchScheduler, executorService, metacardQueue, catalog, start);
    // await on catalog processing threads to complete emptying queue
    phaser.awaitAdvance(phaser.arrive());
    try {
        queueExecutor.shutdown();
        executorService.shutdown();
        batchScheduler.shutdown();
    } catch (SecurityException e) {
        LOGGER.info("Executor service shutdown was not permitted: {}", e);
    }
    printProgressAndFlush(start, fileCount.get(), ingestCount.get() + ignoreCount.get());
    long end = System.currentTimeMillis();
    console.println();
    String elapsedTime = timeFormatter.print(new Period(start, end).withMillis(0));
    console.println();
    console.printf(" %d file(s) ingested in %s %n", ingestCount.get(), elapsedTime);
    LOGGER.debug("{} file(s) ingested in {} [{} records/sec]", ingestCount.get(), elapsedTime, calculateRecordsPerSecond(ingestCount.get(), start, end));
    INGEST_LOGGER.info("{} file(s) ingested in {} [{} records/sec]", ingestCount.get(), elapsedTime, calculateRecordsPerSecond(ingestCount.get(), start, end));
    if (fileCount.get() != ingestCount.get()) {
        console.println();
        if ((fileCount.get() - ingestCount.get() - ignoreCount.get()) >= 1) {
            String failedAmount = Integer.toString(fileCount.get() - ingestCount.get() - ignoreCount.get());
            printErrorMessage(failedAmount + " file(s) failed to be ingested.  See the ingest log for more details.");
            INGEST_LOGGER.warn("{} files(s) failed to be ingested.", failedAmount);
        }
        if (ignoreList != null) {
            String ignoredAmount = Integer.toString(ignoreCount.get());
            printColor(Ansi.Color.YELLOW, ignoredAmount + " file(s) ignored.  See the ingest log for more details.");
            INGEST_LOGGER.warn("{} files(s) were ignored.", ignoredAmount);
        }
    }
    console.println();
    SecurityLogger.audit("Ingested {} files from {}", ingestCount.get(), filePath);
    return null;
}
Example 13
Project: maven-shared-master  File: Style.java View source code
Ansi apply(Ansi ansi) {
    if (bold) {
        ansi.bold();
    }
    if (color != null) {
        if (bright) {
            ansi.fgBright(color);
        } else {
            ansi.fg(color);
        }
    }
    if (bgColor != null) {
        if (bgBright) {
            ansi.bgBright(bgColor);
        } else {
            ansi.bg(bgColor);
        }
    }
    return ansi;
}
Example 14
Project: Visage-master  File: VisageFormatter.java View source code
@Override
public String format(LogRecord record) {
    if (record.getThrown() != null) {
        record.getThrown().printStackTrace();
    }
    Ansi ansi = Ansi.ansi();
    if (Visage.ansi) {
        ansi.fgBright(Color.BLACK);
    }
    Date date = new Date(record.getMillis());
    ansi.a("@");
    ansi.a(format.format(date));
    if (Visage.ansi) {
        ansi.reset();
    }
    ansi.a(Strings.padStart(Thread.currentThread().getName(), 22, ' '));
    ansi.a(" ");
    if (Visage.ansi && colors.containsKey(record.getLevel())) {
        ansi.fgBright(colors.get(record.getLevel()));
    }
    ansi.a(names.get(record.getLevel()));
    if (Visage.ansi) {
        ansi.reset();
    }
    ansi.a(": ");
    if (Visage.ansi && colors.containsKey(record.getLevel()) && record.getLevel().intValue() >= Level.SEVERE.intValue()) {
        ansi.bold();
        ansi.fgBright(colors.get(record.getLevel()));
    }
    ansi.a(record.getMessage());
    if (Visage.ansi) {
        ansi.reset();
    }
    ansi.a("\n");
    return ansi.toString();
}
Example 15
Project: ddf-platform-master  File: StatusApplicationCommand.java View source code
@Override
protected void applicationCommand() throws ApplicationServiceException {
    Application application = applicationService.getApplication(appName);
    if (application != null) {
        ApplicationStatus appStatus = applicationService.getApplicationStatus(application);
        console.println(application.getName());
        console.println("\nCurrent State is: " + appStatus.getState().toString());
        console.println("\nFeatures Located within this Application:");
        for (Feature curFeature : application.getFeatures()) {
            console.println("\t" + curFeature.getName());
        }
        console.println("\nRequired Features Not Started");
        if (appStatus.getErrorFeatures().isEmpty()) {
            console.print(Ansi.ansi().fg(Ansi.Color.GREEN).toString());
            console.println("\tNONE");
            console.print(Ansi.ansi().reset().toString());
        } else {
            for (Feature curFeature : appStatus.getErrorFeatures()) {
                console.print(Ansi.ansi().fg(Ansi.Color.RED).toString());
                console.println("\t" + curFeature.getName());
                console.print(Ansi.ansi().reset().toString());
            }
        }
        console.println("\nRequired Bundles Not Started");
        if (appStatus.getErrorBundles().isEmpty()) {
            console.print(Ansi.ansi().fg(Ansi.Color.GREEN).toString());
            console.println("\tNONE");
            console.print(Ansi.ansi().reset().toString());
        } else {
            for (Bundle curBundle : appStatus.getErrorBundles()) {
                console.print(Ansi.ansi().fg(Ansi.Color.RED).toString());
                console.println("\t[" + curBundle.getBundleId() + "]\t" + curBundle.getSymbolicName());
                console.print(Ansi.ansi().reset().toString());
            }
        }
    } else {
        console.println("No application found with name " + appName);
    }
    return;
}
Example 16
Project: jansi-master  File: AnsiRenderer.java View source code
private static Ansi render(Ansi ansi, String name) {
    Code code = Code.valueOf(name.toUpperCase(Locale.ENGLISH));
    if (code.isColor()) {
        if (code.isBackground()) {
            ansi.bg(code.getColor());
        } else {
            ansi.fg(code.getColor());
        }
    } else if (code.isAttribute()) {
        ansi.a(code.getAttribute());
    }
    return ansi;
}
Example 17
Project: karaf-master  File: DeployMojo.java View source code
protected void deployWithSsh(List<String> locations) throws MojoExecutionException {
    SshClient client = null;
    try {
        final Console console = System.console();
        client = SshClient.setUpDefaultClient();
        setupAgent(user, keyFile, client);
        client.setUserInteraction(new UserInteraction() {

            @Override
            public void welcome(ClientSession s, String banner, String lang) {
                console.printf(banner);
            }

            @Override
            public String[] interactive(ClientSession s, String name, String instruction, String lang, String[] prompt, boolean[] echo) {
                String[] answers = new String[prompt.length];
                try {
                    for (int i = 0; i < prompt.length; i++) {
                        if (console != null) {
                            if (echo[i]) {
                                answers[i] = console.readLine(prompt[i] + " ");
                            } else {
                                answers[i] = new String(console.readPassword(prompt[i] + " "));
                            }
                        }
                    }
                } catch (IOError e) {
                }
                return answers;
            }

            @Override
            public boolean isInteractionAllowed(ClientSession session) {
                return true;
            }

            @Override
            public void serverVersionInfo(ClientSession session, List<String> lines) {
            }

            @Override
            public String getUpdatedPassword(ClientSession session, String prompt, String lang) {
                return null;
            }
        });
        client.start();
        if (console != null) {
            console.printf("Logging in as %s\n", user);
        }
        ClientSession session = connect(client);
        if (password != null) {
            session.addPasswordIdentity(password);
        }
        session.auth().verify();
        StringWriter writer = new StringWriter();
        PrintWriter print = new PrintWriter(writer, true);
        for (String location : locations) {
            print.println("bundle:install -s " + location);
        }
        final ClientChannel channel = session.createChannel("exec", print.toString().concat(NEW_LINE));
        channel.setIn(new ByteArrayInputStream(new byte[0]));
        final ByteArrayOutputStream sout = new ByteArrayOutputStream();
        final ByteArrayOutputStream serr = new ByteArrayOutputStream();
        channel.setOut(AnsiConsole.wrapOutputStream(sout));
        channel.setErr(AnsiConsole.wrapOutputStream(serr));
        channel.open();
        channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
        sout.writeTo(System.out);
        serr.writeTo(System.err);
        // Expects issue KARAF-2623 is fixed
        final boolean isError = (channel.getExitStatus() != null && channel.getExitStatus().intValue() != 0);
        if (isError) {
            final String errorMarker = Ansi.ansi().fg(Color.RED).toString();
            final int fromIndex = sout.toString().indexOf(errorMarker) + errorMarker.length();
            final int toIndex = sout.toString().lastIndexOf(Ansi.ansi().fg(Color.DEFAULT).toString());
            throw new MojoExecutionException(NEW_LINE + sout.toString().substring(fromIndex, toIndex));
        }
    } catch (MojoExecutionException e) {
        throw e;
    } catch (Throwable t) {
        throw new MojoExecutionException(t, t.getMessage(), t.toString());
    } finally {
        try {
            client.stop();
        } catch (Throwable t) {
            throw new MojoExecutionException(t, t.getMessage(), t.toString());
        }
    }
}
Example 18
Project: seed-master  File: Seed.java View source code
private String buildWelcomeMessage() {
    Ansi welcomeMessage = Ansi.ansi().reset().fgBrightGreen().a(WELCOME_MESSAGE).reset();
    if (seedVersion != null) {
        welcomeMessage.a("\n").a("Core v").a(Strings.padEnd(seedVersion, 16, ' '));
    }
    if (businessVersion != null) {
        welcomeMessage.a(seedVersion != null ? "" : "\n").a("Business v").a(businessVersion);
    }
    welcomeMessage.a("\n");
    return welcomeMessage.reset().toString();
}
Example 19
Project: BungeeCord-master  File: ColouredWriter.java View source code
public void print(String s) {
    for (ChatColor color : colors) {
        s = s.replaceAll("(?i)" + color.toString(), replacements.get(color));
    }
    try {
        console.print(Ansi.ansi().eraseLine(Erase.ALL).toString() + ConsoleReader.RESET_LINE + s + Ansi.ansi().reset().toString());
        console.drawLine();
        console.flush();
    } catch (IOException ex) {
    }
}
Example 20
Project: commons-old-master  File: AnsiColorDiagnosticListener.java View source code
@Override
protected void reportOn(Diagnostic<? extends T> diagnostic) {
    switch(diagnostic.getKind()) {
        case NOTE:
            logDiagnostic(outWriter, Ansi.ansi().fg(Color.GREEN), diagnostic);
            break;
        case WARNING:
        case MANDATORY_WARNING:
            logDiagnostic(errWriter, Ansi.ansi().fg(Color.YELLOW), diagnostic);
            break;
        case ERROR:
            logDiagnostic(errWriter, Ansi.ansi().fg(Color.RED), diagnostic);
            break;
        case OTHER:
        default:
            outWriter.println(getMessage(diagnostic));
    }
}
Example 21
Project: spring-boot-master  File: AnsiString.java View source code
/**
	 * Append text with the given ANSI codes.
	 * @param text the text to append
	 * @param codes the ANSI codes
	 * @return this string
	 */
AnsiString append(String text, Code... codes) {
    if (codes.length == 0 || !isAnsiSupported()) {
        this.value.append(text);
        return this;
    }
    Ansi ansi = Ansi.ansi();
    for (Code code : codes) {
        ansi = applyCode(ansi, code);
    }
    this.value.append(ansi.a(text).reset().toString());
    return this;
}
Example 22
Project: spring-hadoop-master  File: AnsiString.java View source code
/**
	 * Append text with the given ANSI codes
	 * @param text the text to append
	 * @param codes the ANSI codes
	 * @return this string
	 */
AnsiString append(String text, Code... codes) {
    if (codes.length == 0 || !isAnsiSupported()) {
        this.value.append(text);
        return this;
    }
    Ansi ansi = Ansi.ansi();
    for (Code code : codes) {
        ansi = applyCode(ansi, code);
    }
    this.value.append(ansi.a(text).reset().toString());
    return this;
}
Example 23
Project: tailor-master  File: Printer.java View source code
/**
     * Print all rules along with their descriptions to STDOUT.
     */
public static void printRules() {
    Rules[] rules = Rules.values();
    AnsiConsole.out.println(Ansi.ansi().render(String.format("@|bold %d rules available|@%n", rules.length)));
    for (Rules rule : rules) {
        AnsiConsole.out.println(Ansi.ansi().render(String.format("@|bold %s|@%n" + "@|underline Description:|@ %s%n" + "@|underline Style Guide:|@ %s%n", rule.getName(), rule.getDescription(), rule.getLink())));
    }
}
Example 24
Project: dcache-master  File: UserAdminShell.java View source code
/**
     * Concurrently sends a command to several cells and collects the result from each.
     */
private String sendToMany(Iterable<String> destinations, Serializable object) throws AclException {
    /* Check permissions */
    try {
        checkPermission("cell.*.execute");
    } catch (AclException e) {
        for (String cell : destinations) {
            checkPermission("cell." + cell + ".execute");
        }
    }
    /* Submit */
    List<Map.Entry<String, ListenableFuture<Serializable>>> futures = new ArrayList<>();
    for (String cell : destinations) {
        futures.add(immutableEntry(cell, _cellStub.send(new CellPath(cell), object, Serializable.class, _timeout)));
    }
    /* Collect results */
    StringBuilder result = new StringBuilder();
    for (Map.Entry<String, ListenableFuture<Serializable>> entry : futures) {
        result.append(Ansi.ansi().bold().a(entry.getKey()).boldOff()).append(":");
        try {
            String reply = Objects.toString(entry.getValue().get(), "");
            if (reply.isEmpty()) {
                result.append(Ansi.ansi().fg(GREEN).a(" OK").reset()).append("\n");
            } else {
                result.append("\n");
                for (String s : reply.split("\n")) {
                    result.append("    ").append(s).append("\n");
                }
            }
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof NoRouteToCellException) {
                result.append(Ansi.ansi().fg(RED).a(" Cell is unreachable.").reset()).append("\n");
            } else {
                result.append(" ").append(Ansi.ansi().fg(RED).a(cause.getMessage()).reset()).append("\n");
            }
        } catch (InterruptedException e) {
            result.append(" ^C\n");
            for (Map.Entry<String, ListenableFuture<Serializable>> entry2 : futures) {
                entry2.getValue().cancel(true);
            }
        } catch (CancellationException e) {
            result.append(" ^C\n");
        }
    }
    return result.toString();
}
Example 25
Project: deltascript-master  File: DeltaScriptFancyInterpreter.java View source code
private void writeBanner() throws IOException {
    AnsiConsole.out.println(Ansi.ansi().fg(Color.CYAN).a("    __________ ").fg(Color.DEFAULT).a(Attribute.INTENSITY_BOLD).a("   D E L T A S C R I P T").reset().newline().fg(Color.CYAN).a("   (_________()").newline().fg(Color.CYAN).a("    /  ===   / ").reset().a(" - Version ").a(DeltaScript.VERSION).newline().fg(Color.CYAN).a("   |  ==    |  ").reset().a(" - Developed by ").a(DeltaScript.AUTHOR).newline().fg(Color.CYAN).a("   /  ===   /  ").reset().a(" - ").a(DeltaScript.WEBSITE).newline().fg(Color.CYAN).a("  |  =  =  |   ").reset().a(" - Distributed under the GNU LGPL v3").newline().fg(Color.CYAN).a("  /  ===   /   ").newline().fg(Color.CYAN).a(" (________()   ").fg(Color.RED).a("Press CTRL-C to exit.").reset().newline());
}
Example 26
Project: gradle-master  File: DefaultAnsiExecutor.java View source code
private void positionCursorAt(Cursor position, Ansi ansi) {
    if (writeCursor.row == position.row) {
        if (writeCursor.col == position.col) {
            return;
        }
        if (writeCursor.col < position.col) {
            ansi.cursorRight(position.col - writeCursor.col);
        } else {
            ansi.cursorLeft(writeCursor.col - position.col);
        }
    } else {
        if (writeCursor.col > 0) {
            ansi.cursorLeft(writeCursor.col);
        }
        if (writeCursor.row < position.row) {
            ansi.cursorUp(position.row - writeCursor.row);
        } else {
            ansi.cursorDown(writeCursor.row - position.row);
        }
        if (position.col > 0) {
            ansi.cursorRight(position.col);
        }
    }
    writeCursor.copyFrom(position);
}
Example 27
Project: hapi-fhir-master  File: ExampleDataUploader.java View source code
private void downloadFileFromInternet(CloseableHttpResponse result, File localFile) throws IOException {
    FileOutputStream buffer = FileUtils.openOutputStream(localFile);
    try {
        long maxLength = result.getEntity().getContentLength();
        long nextLog = -1;
        // ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];
        while ((nRead = result.getEntity().getContent().read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
            long fileSize = FileUtils.sizeOf(localFile);
            if (fileSize > nextLog) {
                System.err.print("\r" + Ansi.ansi().eraseLine());
                System.err.print(FileUtils.byteCountToDisplaySize(fileSize));
                if (maxLength > 0) {
                    System.err.print(" [");
                    int stars = (int) (50.0f * ((float) fileSize / (float) maxLength));
                    for (int i = 0; i < stars; i++) {
                        System.err.print("*");
                    }
                    for (int i = stars; i < 50; i++) {
                        System.err.print(" ");
                    }
                    System.err.print("]");
                }
                System.err.flush();
                nextLog += 100000;
            }
        }
        buffer.flush();
        System.err.println();
        System.err.flush();
    } finally {
        IOUtils.closeQuietly(buffer);
    }
}
Example 28
Project: airship-master  File: TablePrinter.java View source code
public void print(Iterable<Record> records) {
    if (Ansi.isEnabled()) {
        Map<Column, Integer> columns = newLinkedHashMap();
        for (Iterator<Column> iterator = this.columns.iterator(); iterator.hasNext(); ) {
            Column column = iterator.next();
            int columnSize = 0;
            if (iterator.hasNext()) {
                columnSize = column.getHeader().length();
                for (Record record : records) {
                    String value = record.getValue(column);
                    if (value != null) {
                        columnSize = Math.max(value.length(), columnSize);
                    }
                }
            }
            columns.put(column, columnSize);
        }
        for (final Record record : Iterables.concat(ImmutableList.of(headerRecord), records)) {
            String line = Joiner.on(columnSeparator).join(transform(columns.entrySet(), columnFormatter(record)));
            System.out.println(line.replaceAll("\\s*$", ""));
        }
    } else {
        for (Record record : records) {
            boolean first = true;
            for (Column column : columns) {
                if (!first) {
                    System.out.print("\t");
                }
                first = false;
                String value = Objects.firstNonNull(record.getValue(column), "");
                System.out.print(value);
            }
            System.out.println();
        }
    }
}
Example 29
Project: ddf-admin-master  File: StatusApplicationCommand.java View source code
@Override
protected void applicationCommand() throws ApplicationServiceException {
    Application application = applicationService.getApplication(appName);
    if (application != null) {
        ApplicationStatus appStatus = applicationService.getApplicationStatus(application);
        console.println(application.getName());
        console.println("\nCurrent State is: " + appStatus.getState().toString());
        console.println("\nFeatures Located within this Application:");
        for (Feature curFeature : application.getFeatures()) {
            console.println("\t" + curFeature.getName());
        }
        console.println("\nRequired Features Not Started");
        if (appStatus.getErrorFeatures().isEmpty()) {
            console.print(Ansi.ansi().fg(Ansi.Color.GREEN).toString());
            console.println("\tNONE");
            console.print(Ansi.ansi().reset().toString());
        } else {
            for (Feature curFeature : appStatus.getErrorFeatures()) {
                console.print(Ansi.ansi().fg(Ansi.Color.RED).toString());
                console.println("\t" + curFeature.getName());
                console.print(Ansi.ansi().reset().toString());
            }
        }
        console.println("\nRequired Bundles Not Started");
        if (appStatus.getErrorBundles().isEmpty()) {
            console.print(Ansi.ansi().fg(Ansi.Color.GREEN).toString());
            console.println("\tNONE");
            console.print(Ansi.ansi().reset().toString());
        } else {
            for (Bundle curBundle : appStatus.getErrorBundles()) {
                console.print(Ansi.ansi().fg(Ansi.Color.RED).toString());
                console.println("\t[" + curBundle.getBundleId() + "]\t" + curBundle.getSymbolicName());
                console.print(Ansi.ansi().reset().toString());
            }
        }
    } else {
        console.println("No application found with name " + appName);
    }
    return;
}
Example 30
Project: pi4j-javaone-demos-master  File: AccessControl.java View source code
@Override
public void onStateChange(SensorStateChangeEvent event) {
    // display console message
    Ansi message = Ansi.ansi().fg(Ansi.Color.WHITE).a("Door sensor event: ");
    if (event.getNewState() == SensorState.OPEN) {
        message.fg(Ansi.Color.GREEN).a("--DOOR OPENED--");
        //  this may mean that the door was forcefully opened)
        if (lockRelay.isOpen()) {
            // set security violation to 'door-breach'
            setSecurityViolation(SecurityViolation.DoorBreach);
        } else {
            displayMessage(DOOR_OPENED);
        }
    } else {
        message.fg(Ansi.Color.YELLOW).a("--DOOR CLOSED--");
        displayMessage(DOOR_CLOSED);
    }
    AnsiConsole.out().println(message.reset());
}
Example 31
Project: tomee-master  File: ColorFormatter.java View source code
@Override
public synchronized String format(final LogRecord record) {
    final boolean exception = record.getThrown() != null;
    final Ansi sbuf = prefix(record);
    sbuf.a(record.getLevel().getLocalizedName());
    sbuf.a(" - ");
    sbuf.a(formatMessage(record));
    if (!exception) {
        suffix(sbuf, record);
    }
    sbuf.newline();
    if (exception) {
        try {
            final StringWriter sw = new StringWriter();
            final PrintWriter pw = new PrintWriter(sw);
            record.getThrown().printStackTrace(pw);
            pw.close();
            sbuf.a(sw.toString());
        } catch (final Exception ex) {
        } finally {
            suffix(sbuf, record);
        }
    }
    return sbuf.toString();
}
Example 32
Project: hive-master  File: SparkJobMonitor.java View source code
private void printStatusInPlace(Map<String, SparkStageProgress> progressMap) {
    StringBuilder reportBuffer = new StringBuilder();
    // Num of total and completed tasks
    int sumTotal = 0;
    int sumComplete = 0;
    // position the cursor to line 0
    repositionCursor();
    // header
    reprintLine(SEPARATOR);
    reprintLineWithColorAsBold(HEADER, Ansi.Color.CYAN);
    reprintLine(SEPARATOR);
    SortedSet<String> keys = new TreeSet<String>(progressMap.keySet());
    int idx = 0;
    final int numKey = keys.size();
    for (String s : keys) {
        SparkStageProgress progress = progressMap.get(s);
        final int complete = progress.getSucceededTaskCount();
        final int total = progress.getTotalTaskCount();
        final int running = progress.getRunningTaskCount();
        final int failed = progress.getFailedTaskCount();
        sumTotal += total;
        sumComplete += complete;
        StageState state = total > 0 ? StageState.PENDING : StageState.FINISHED;
        if (complete > 0 || running > 0 || failed > 0) {
            if (!perfLogger.startTimeHasMethod(PerfLogger.SPARK_RUN_STAGE + s)) {
                perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.SPARK_RUN_STAGE + s);
            }
            if (complete < total) {
                state = StageState.RUNNING;
            } else {
                state = StageState.FINISHED;
                perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.SPARK_RUN_STAGE + s);
                completed.add(s);
            }
        }
        int div = s.indexOf('_');
        String attempt = div > 0 ? s.substring(div + 1) : "-";
        String stageName = "Stage-" + (div > 0 ? s.substring(0, div) : s);
        String nameWithProgress = getNameWithProgress(stageName, complete, total);
        final int pending = total - complete - running;
        String stageStr = String.format(STAGE_FORMAT, nameWithProgress, attempt, state, total, complete, running, pending, failed);
        reportBuffer.append(stageStr);
        if (idx++ != numKey - 1) {
            reportBuffer.append("\n");
        }
    }
    reprintMultiLine(reportBuffer.toString());
    reprintLine(SEPARATOR);
    final float progress = (sumTotal == 0) ? 1.0f : (float) sumComplete / (float) sumTotal;
    String footer = getFooter(numKey, completed.size(), progress, startTime);
    reprintLineWithColorAsBold(footer, Ansi.Color.RED);
    reprintLine(SEPARATOR);
}
Example 33
Project: jledit-master  File: AbstractConsoleEditor.java View source code
/**
     * Displays a message and reads a boolean from the user input.
     * The mapping of the user input to a boolean value is specified by the implementation.
     *
     * @param message
     * @param defaultValue
     * @return
     */
@Override
public boolean readBoolean(String message, Boolean defaultValue) throws IOException {
    saveCursorPosition();
    Ansi style = ansi();
    if (getTheme().getPromptBackground() != null) {
        style.bg(getTheme().getPromptBackground());
    }
    if (getTheme().getPromptForeground() != null) {
        style.fg(getTheme().getPromptForeground());
    }
    for (int i = 1; i <= getFooterSize(); i++) {
        JlEditConsole.out.print(ansi().cursor(terminal.getHeight() - getFooterSize() + i, 1));
        JlEditConsole.out.print(style.eraseLine(Ansi.Erase.FORWARD));
    }
    JlEditConsole.out.print(ansi().cursor(terminal.getHeight(), 1));
    JlEditConsole.out.print(style.a(message).bold().eraseLine(Ansi.Erase.FORWARD));
    restoreCursorPosition();
    flush();
    try {
        EditorOperation operation;
        while (true) {
            operation = readOperation();
            switch(operation.getType()) {
                case NEWLINE:
                    return defaultValue;
                case TYPE:
                    if ("y".equals(operation.getInput()) || "Y".equals(operation.getInput())) {
                        return true;
                    } else if ("n".equals(operation.getInput()) || "N".equals(operation.getInput())) {
                        return false;
                    }
            }
        }
    } finally {
        redrawFooter();
    }
}
Example 34
Project: pact-jvm-master  File: AnsiRenderer.java View source code
private static String render(final String text, final String... codes) {
    Ansi ansi = Ansi.ansi();
    for (String name : codes) {
        Code code = Code.valueOf(name.toUpperCase(Locale.ENGLISH));
        if (code.isColor()) {
            if (code.isBackground()) {
                ansi = ansi.bg(code.getColor());
            } else {
                ansi = ansi.fg(code.getColor());
            }
        } else if (code.isAttribute()) {
            ansi = ansi.a(code.getAttribute());
        }
    }
    return ansi.a(text).reset().toString();
}
Example 35
Project: pact-master  File: AnsiRenderer.java View source code
private static String render(final String text, final String... codes) {
    Ansi ansi = Ansi.ansi();
    for (String name : codes) {
        Code code = Code.valueOf(name.toUpperCase(Locale.ENGLISH));
        if (code.isColor()) {
            if (code.isBackground()) {
                ansi = ansi.bg(code.getColor());
            } else {
                ansi = ansi.fg(code.getColor());
            }
        } else if (code.isAttribute()) {
            ansi = ansi.a(code.getAttribute());
        }
    }
    return ansi.a(text).reset().toString();
}
Example 36
Project: ThingML-master  File: JavaThingActionCompiler.java View source code
@Override
public void traceVariablePost(VariableAssignment action, StringBuilder builder, Context ctx) {
/*if ((action.getProperty().eContainer() instanceof Thing) && action.getProperty().getCardinality() == null) {//FIXME: see above
            //builder.append("if(isDebug()) System.out.println(org.fusesource.jansi.Ansi.ansi().eraseScreen().render(\"@|magenta \" + getName() + \": property " + action.getProperty().getName() + " changed from \" + debug_" + ctx.getVariableName(action.getProperty()) + " + \" to \" + " + ctx.getVariableName(action.getProperty()) + " + \"|@\"));\n");
            builder.append("if(isDebug()) "
                    + "System.out.println(getName() + \": property " + action.getProperty().getName() + " changed from \" + debug_" + ctx.getVariableName(action.getProperty()) + " + \" to \" + " + ctx.getVariableName(action.getProperty()) + ");\n");
        }*/
}
Example 37
Project: grails-core-master  File: GrailsConsole.java View source code
private Ansi erasePreviousLine(String categoryName) {
    int cursorMove = this.cursorMove;
    if (userInputActive)
        cursorMove++;
    if (cursorMove > 0) {
        int moveLeftLength = categoryName.length() + lastMessage.length();
        if (userInputActive) {
            moveLeftLength += PROMPT.length();
        }
        return ansi().cursorUp(cursorMove).cursorLeft(moveLeftLength).eraseLine(FORWARD);
    }
    return ansi();
}
Example 38
Project: grails-master  File: GrailsConsole.java View source code
private Ansi erasePreviousLine(String categoryName) {
    int cursorMove = this.cursorMove;
    if (userInputActive)
        cursorMove++;
    if (cursorMove > 0) {
        int moveLeftLength = categoryName.length() + lastMessage.length();
        if (userInputActive) {
            moveLeftLength += PROMPT.length();
        }
        return ansi().cursorUp(cursorMove).cursorLeft(moveLeftLength).eraseLine(FORWARD);
    }
    return ansi();
}
Example 39
Project: Glowstone-master  File: ConsoleManager.java View source code
private String colorize(String string) {
    if (string.indexOf(ChatColor.COLOR_CHAR) < 0) {
        // no colors in the message
        return string;
    } else if (!jLine || !reader.getTerminal().isAnsiSupported()) {
        // color not supported
        return ChatColor.stripColor(string);
    } else {
        // colorize or strip all colors
        for (ChatColor color : colors) {
            if (replacements.containsKey(color)) {
                string = string.replaceAll("(?i)" + color, replacements.get(color));
            } else {
                string = string.replaceAll("(?i)" + color, "");
            }
        }
        return string + Ansi.ansi().reset();
    }
}
Example 40
Project: kotlin-master  File: PlainTextMessageRenderer.java View source code
@Override
public String render(@NotNull CompilerMessageSeverity severity, @NotNull String message, @Nullable CompilerMessageLocation location) {
    StringBuilder result = new StringBuilder();
    int line = location != null ? location.getLine() : -1;
    int column = location != null ? location.getColumn() : -1;
    String lineContent = location != null ? location.getLineContent() : null;
    String path = location != null ? getPath(location) : null;
    if (path != null) {
        result.append(path);
        result.append(":");
        if (line > 0) {
            result.append(line).append(":");
            if (column > 0) {
                result.append(column).append(":");
            }
        }
        result.append(" ");
    }
    if (COLOR_ENABLED) {
        Ansi ansi = Ansi.ansi().bold().fg(severityColor(severity)).a(severity.getPresentableName()).a(": ").reset();
        if (IMPORTANT_MESSAGE_SEVERITIES.contains(severity)) {
            ansi.bold();
        }
        // Only make the first line of the message bold. Otherwise long overload ambiguity errors or exceptions are hard to read
        String decapitalized = decapitalizeIfNeeded(message);
        int firstNewline = decapitalized.indexOf(LINE_SEPARATOR);
        if (firstNewline < 0) {
            result.append(ansi.a(decapitalized).reset());
        } else {
            result.append(ansi.a(decapitalized.substring(0, firstNewline)).reset().a(decapitalized.substring(firstNewline)));
        }
    } else {
        result.append(severity.getPresentableName());
        result.append(": ");
        result.append(decapitalizeIfNeeded(message));
    }
    if (lineContent != null && 1 <= column && column <= lineContent.length() + 1) {
        result.append(LINE_SEPARATOR);
        result.append(lineContent);
        result.append(LINE_SEPARATOR);
        result.append(StringsKt.repeat(" ", column - 1));
        result.append("^");
    }
    return result.toString();
}
Example 41
Project: tajo-master  File: DefaultTajoCliOutputFormatter.java View source code
public void reprintProgressLine(PrintWriter out, String progressBar, int progress, String responseTime, QueryStatus status) {
    // [=====>>                                   ] 10%  3.18 sec
    String lineFormat = "[%s] %d%%  %s";
    if (isRealTerminal()) {
        boolean isLastLine = false;
        if (status.getState() == TajoProtos.QueryState.QUERY_SUCCEEDED) {
            progressBar = "@|green " + progressBar + "|@";
            isLastLine = true;
        } else if (status.getState() == TajoProtos.QueryState.QUERY_ERROR || status.getState() == TajoProtos.QueryState.QUERY_FAILED || status.getState() == TajoProtos.QueryState.QUERY_KILLED) {
            progressBar = "@|red " + progressBar + "|@";
            isLastLine = true;
        }
        String line = String.format(lineFormat, progressBar, progress, responseTime);
        out.print(ansi().eraseLine(Ansi.Erase.ALL).a('\r').render(line));
        if (isLastLine) {
            out.println();
        }
    } else {
        String line = String.format(lineFormat, progressBar, progress, responseTime);
        out.println(line);
    }
    out.flush();
}
Example 42
Project: rascal-master  File: TreeAdapter.java View source code
public ITree visitTreeAppl(ITree arg) throws IOException {
    boolean reset = false;
    String category = null;
    if (fHighlight) {
        IConstructor prod = TreeAdapter.getProduction(arg);
        category = ProductionAdapter.getCategory(prod);
        if (category == null) {
            if ((TreeAdapter.isLiteral(arg) || TreeAdapter.isCILiteral(arg))) {
                category = META_KEYWORD;
                for (IValue child : TreeAdapter.getArgs(arg)) {
                    int c = TreeAdapter.getCharacter((ITree) child);
                    if (c != '-' && !Character.isJavaIdentifierPart(c)) {
                        category = null;
                    }
                }
            }
        }
        if (category != null) {
            Ansi code = ansiOpen.get(category);
            if (code != null) {
                fStream.write(code.toString());
                reset = true;
            }
        }
    }
    IList children = (IList) arg.get("args");
    for (IValue child : children) {
        child.accept(this);
    }
    if (fHighlight && reset) {
        Ansi code = ansiClose.get(category);
        if (code != null) {
            fStream.write(code.toString());
        }
    }
    return arg;
}
Example 43
Project: infinispan-master  File: ShellImpl.java View source code
@Override
public String renderColor(final Color color, final String output) {
    if (!config.isColorEnabled()) {
        return output;
    }
    Ansi ansi = new Ansi();
    switch(color) {
        case BLACK:
            ansi.fg(Ansi.Color.BLACK);
            break;
        case BLUE:
            ansi.fg(Ansi.Color.BLUE);
            break;
        case CYAN:
            ansi.fg(Ansi.Color.CYAN);
            break;
        case GREEN:
            ansi.fg(Ansi.Color.GREEN);
            break;
        case MAGENTA:
            ansi.fg(Ansi.Color.MAGENTA);
            break;
        case RED:
            ansi.fg(Ansi.Color.RED);
            break;
        case WHITE:
            ansi.fg(Ansi.Color.WHITE);
            break;
        case YELLOW:
            ansi.fg(Ansi.Color.YELLOW);
            break;
        case BOLD:
            ansi.a(Ansi.Attribute.INTENSITY_BOLD);
            break;
        case ITALIC:
            ansi.a(Ansi.Attribute.ITALIC);
            ansi.a(Ansi.Attribute.INTENSITY_FAINT);
            break;
        default:
            return output;
    }
    return ansi.render(output).reset().toString();
}
Example 44
Project: MyPet-master  File: MyPetLogger.java View source code
public String applyStyles(String message) {
    for (ChatColor color : replacements.keySet()) {
        if (this.replacements.containsKey(color)) {
            message = message.replaceAll("(?i)" + color.toString(), this.replacements.get(color));
        } else {
            message = message.replaceAll("(?i)" + color.toString(), "");
        }
    }
    return message + Ansi.ansi().reset().toString();
}
Example 45
Project: GrowControl-master  File: gcClient.java View source code
// ------------------------------------------------------------------------------- //
/*
	protected void updateConfig() {
		// config version
		{
			boolean configVersionDifferent = false;
			final String configVersion = this.config.getVersion();
			final String clientVersion = this.getVersion();
			if(utils.notEmpty(configVersion) && utils.notEmpty(clientVersion)) {
				if(configVersion.endsWith("x") || configVersion.endsWith("*")) {
					final String vers = utilsString.trims(configVersion, "x", "*");
					if(!clientVersion.startsWith(vers))
						configVersionDifferent = true;
				} else {
					if(!configVersion.equals(clientVersion))
						configVersionDifferent = true;
				}
			}
			if(configVersionDifferent)
				log().warning(gcClientDefines.CONFIG_FILE+" for this client may need updates");
		}
		// log level
		{
			final Boolean debug = this.config.getDebug();
			if(debug != null && debug.booleanValue())
				xVars.debug(debug.booleanValue());
			if(!xVars.debug()) {
				// set log level
				final xLevel level = this.config.getLogLevel();
				if(level != null)
					xLog.getRoot()
						.setLevel(level);
			}
		}
	}
*/
//	// connect to server
//	public void Connect(String host, int port, String user, String pass) {
//		pxnThreadQueue.addToMain("SocketConnect",
//			new doConnect(host, port, user, pass));
//	}
//	private class doConnect implements Runnable {
//
//		public pxnSocketClient socket = null;
//		private final String host;
//		private final int    port;
//@SuppressWarnings("unused")
//		private final String user;
//@SuppressWarnings("unused")
//		private final String pass;
//
//
//		public doConnect(String host, int port, String user, String pass) {
//			if(host == null || host.isEmpty())
//				host = "127.0.0.1";
//			if(port < 1) port = 1142;
//			if(user == null || user.isEmpty()) user = null;
//			if(pass == null || pass.isEmpty()) pass = null;
//			this.host = host;
//			this.port = pxnUtilsMath.MinMax(port, 1, 65535);
//			this.user = user;
//			this.pass = pass;
//		}
//
//
//		// connect to server
//		@Override
//		public synchronized void run() {
//pxnLog.get().info("Connecting..");
//			// create socket
//			if(socket == null)
//				socket = new pxnSocketClient();
//			socket.setHost(this.host);
//			socket.setPort(this.port);
//			// create processor
//			socket.setFactory(new pxnSocketProcessorFactory() {
//				@Override
//				public gcPacketReader newProcessor() {
//					return new gcPacketReader();
//				}
//			});
//			socket.Start();
//			if(!pxnSocketState.CONNECTED.equals(socket.getState())) {
//				pxnLog.get().warning("Failed to connect!");
//				return;
//			}
//			// send HELLO packet
//			gcPacketSender.sendHELLO(
//				socket.getWorker(),
//				gcClient.version);
////				connectInfo.username,
////				connectInfo.password);
//pxnLog.get().severe("CONNECTED!!!!!!!!!!!!!!!!!!!");
//			guiManager.get().Update(guiManager.GUI.DASH);
//		}
//
//
//	}
//	// get zones
//	public List<String> getZones() {
//		synchronized(zones) {
//			return new ArrayList<String>(zones);
//		}
//	}
//	public String[] getZonesArray() {
//		synchronized(zones) {
//			return (String[]) zones.toArray();
//		}
//	}
// ascii header
@Override
protected void displayLogo() {
    final PrintStream out = AnsiConsole.out;
    final Ansi.Color bgcolor = Ansi.Color.BLACK;
    out.println();
    // line 1
    out.println(Ansi.ansi().a(" ").bg(bgcolor).bold().a("      ").fg(Ansi.Color.GREEN).a("P").fg(Ansi.Color.WHITE).a("oi").fg(Ansi.Color.GREEN).a("X").fg(Ansi.Color.WHITE).a("son").a("                          ").a("                          ").reset());
    // line 2
    out.println(Ansi.ansi().a(" ").bg(bgcolor).bold().a("   ").fg(Ansi.Color.BLACK).a("©").fg(Ansi.Color.GREEN).a("GROW").fg(Ansi.Color.WHITE).a("CONTROL").boldOff().a("   ").fg(/* C */
    Ansi.Color.MAGENTA).a("_ _        ").fg(/* E */
    Ansi.Color.YELLOW).a(",`--',").a("                     ").fg(/* H */
    Ansi.Color.WHITE).a("\" ' \"    ").reset());
    // line 3
    out.println(Ansi.ansi().a(" ").bg(bgcolor).a("   ").fg(/* A */
    Ansi.Color.BLUE).a("_  ").fg(Ansi.Color.CYAN).a("Client     ").fg(/* C */
    Ansi.Color.MAGENTA).a("(_\\_)      ").fg(/* E */
    Ansi.Color.YELLOW).a(". ").bold().a("_\\/_ ").boldOff().a(".").a("                  ").fg(/* H */
    Ansi.Color.WHITE).a("\" \\ | / \"  ").reset());
    // line 4
    out.println(Ansi.ansi().a(" ").bg(bgcolor).a(" ").fg(/* A */
    Ansi.Color.BLUE).a("_(_)_          ").fg(/* C */
    Ansi.Color.MAGENTA).a("(__").a("<").a("_{)     ").fg(/* E */
    Ansi.Color.YELLOW).a("`. ").bold().a("/\\ ").boldOff().a(".'   ").fg(/* F */
    Ansi.Color.WHITE).a(".\\|/.         ").fg(/* H */
    Ansi.Color.WHITE).a("' --").bold().a("(:)").boldOff().a("-- ' ").reset());
    // line 5
    out.println(Ansi.ansi().a(" ").bg(bgcolor).fg(/* A */
    Ansi.Color.BLUE).a("(_)").bold().a("@").boldOff().a("(_)          ").fg(/* C */
    Ansi.Color.MAGENTA).a("{_/_}        ").fg(/* E */
    Ansi.Color.YELLOW).a("\"").fg(Ansi.Color.GREEN).a("||").fg(Ansi.Color.YELLOW).a("\"     ").fg(/* F */
    Ansi.Color.WHITE).a("-").bold().a("(:)").boldOff().a("-          ").fg(/* H */
    Ansi.Color.WHITE).a("\" / | \\ \"  ").reset());
    // line 6
    out.println(Ansi.ansi().a(" ").bg(bgcolor).a("  ").fg(/* A */
    Ansi.Color.BLUE).a("(_)").fg(Ansi.Color.GREEN).a("\\.         ").fg(/* C */
    Ansi.Color.GREEN).a("|\\ |           ").fg(/* E */
    Ansi.Color.GREEN).a("|| /\\   ").fg(/* F */
    Ansi.Color.WHITE).a("\"/").fg(Ansi.Color.GREEN).a("|").fg(Ansi.Color.WHITE).a("\\\"           ").fg(/* H */
    Ansi.Color.WHITE).a("\" '").fg(Ansi.Color.GREEN).a("|").fg(Ansi.Color.WHITE).a("' \"   ").reset());
    // line 7
    out.println(Ansi.ansi().a(" ").bg(bgcolor).a("    ").fg(/* A */
    Ansi.Color.GREEN).a(". |/| ").fg(/* B */
    Ansi.Color.RED).a(".vVv.  ").fg(/* C */
    Ansi.Color.GREEN).a("\\\\| /| ").fg(/* D */
    Ansi.Color.RED).a("\\V/  ").fg(/* E */
    Ansi.Color.GREEN).a("/\\||//\\)   ").fg(/* F */
    Ansi.Color.GREEN).a("'|'    ").fg(/* G */
    Ansi.Color.GREEN).a("`").fg(Ansi.Color.YELLOW).bold().a("@").fg(Ansi.Color.GREEN).boldOff().a("'   ").fg(/* H */
    Ansi.Color.GREEN).a("|\\   |      ").reset());
    // line 8
    out.println(Ansi.ansi().a(" ").bg(bgcolor).a("    ").fg(/* A */
    Ansi.Color.GREEN).a("|\\|/   ").fg(/* B */
    Ansi.Color.GREEN).a("\\").fg(Ansi.Color.RED).a("#").fg(Ansi.Color.GREEN).a("/    ").fg(/* C */
    Ansi.Color.GREEN).a("\\|//  ").fg(/* D */
    Ansi.Color.GREEN).a("`").bold().a("|").boldOff().a("/ ").fg(/* E */
    Ansi.Color.GREEN).a("(/\\||/    ").fg(/* F */
    Ansi.Color.GREEN).a(".\\ | ,   ").fg(/* G */
    Ansi.Color.GREEN).a("\\").bold().a("|").boldOff().a("/   ").fg(/* H */
    Ansi.Color.GREEN).a("/_ \\ |  /`| ").reset());
    // line 9
    out.println(Ansi.ansi().a(" ").bg(bgcolor).a("     ").fg(Ansi.Color.GREEN).a(/* A */
    "\\|   ").a(/* B */
    "\\\\").bold().a("|").boldOff().a("//    ").a(/* C */
    "|/  ").a(/* D */
    "\\\\").bold().a("|").boldOff().a("//   ").a(/* E */
    "||     ").a(/* F */
    "/-\\|/_\\ ").a(/* G */
    "\\\\").bold().a("|").boldOff().a("//,   ").a(/* H */
    "/-\\|/_//  ").reset());
    // line 10
    out.println(Ansi.ansi().a(" ").bg(bgcolor).fg(Ansi.Color.GREEN).a("^/^/^/^/^/^/^/^/^/^/^/^/^/^/^/^/").a("^/^/^/^/^/^/^/^/^/^/^/^/^/^/^/^/^").reset());
    // line 11
    out.println(Ansi.ansi().a(" ").bg(bgcolor).fg(Ansi.Color.GREEN).a("////////////////////////////////").a("/////////////////////////////////").reset());
    out.println();
    out.println(" Copyright (C) 2007-2014 PoiXson, Mattsoft");
    out.println(" - Brainchild of the one known as lorenzo -");
    out.println(" This program comes with absolutely no warranty. This is free software");
    out.println(" and you are welcome to modify it or redistribute it under certain");
    out.println(" conditions. Type 'show license' for license details.");
    out.println();
    out.flush();
}
Example 46
Project: logging-log4j2-master  File: JAnsiTextRenderer.java View source code
/**
     * Renders the given text with the given names which can be ANSI code names or Log4j style names.
     * 
     * @param text
     *            The text to render
     * @param names
     *            ANSI code names or Log4j style names.
     * @return A rendered string containing ANSI codes.
     */
private String render(final String text, final String... names) {
    final Ansi ansi = Ansi.ansi();
    for (final String name : names) {
        final Code[] codes = styleMap.get(name);
        if (codes != null) {
            render(ansi, codes);
        } else {
            render(ansi, toCode(name));
        }
    }
    return ansi.a(text).reset().toString();
}
Example 47
Project: presto-master  File: Query.java View source code
private static void renderErrorLocation(String query, ErrorLocation location, PrintStream out) {
    List<String> lines = ImmutableList.copyOf(Splitter.on('\n').split(query).iterator());
    String errorLine = lines.get(location.getLineNumber() - 1);
    String good = errorLine.substring(0, location.getColumnNumber() - 1);
    String bad = errorLine.substring(location.getColumnNumber() - 1);
    if ((location.getLineNumber() == lines.size()) && bad.trim().isEmpty()) {
        bad = " <EOF>";
    }
    if (REAL_TERMINAL) {
        Ansi ansi = Ansi.ansi();
        ansi.fg(Ansi.Color.CYAN);
        for (int i = 1; i < location.getLineNumber(); i++) {
            ansi.a(lines.get(i - 1)).newline();
        }
        ansi.a(good);
        ansi.fg(Ansi.Color.RED);
        ansi.a(bad).newline();
        for (int i = location.getLineNumber(); i < lines.size(); i++) {
            ansi.a(lines.get(i)).newline();
        }
        ansi.reset();
        out.print(ansi);
    } else {
        String prefix = format("LINE %s: ", location.getLineNumber());
        String padding = Strings.repeat(" ", prefix.length() + (location.getColumnNumber() - 1));
        out.println(prefix + errorLine);
        out.println(padding + "^");
    }
}
Example 48
Project: SocPuppet-master  File: ConsoleManager.java View source code
private String colorize(String string) {
    if (!string.contains("")) {
        // no colors in the message
        return string;
    } else if (!jLine || !reader.getTerminal().isAnsiSupported()) {
        // color not supported
        return Colors.removeAll(string);
    } else {
        String c = "(,(1[0-5]|0?[0-9]))?";
        // colorize or strip all colors
        for (Colors color : colors) {
            if (!string.contains(color.toString())) {
                continue;
            }
            if (replacements.containsKey(color)) {
                string = string.replaceAll("(?i)" + color.toString() + c, replacements.get(color));
            } else {
                string = string.replaceAll("(?i)" + color.toString() + c, "");
            }
        }
        return string + Ansi.ansi().reset().toString();
    }
}
Example 49
Project: vertexium-master  File: VertexiumShell.java View source code
static void setTerminalType(String type, boolean suppressColor) {
    assert type != null;
    type = type.toLowerCase();
    boolean enableAnsi = true;
    switch(type) {
        case TerminalFactory.AUTO:
            type = null;
            break;
        case TerminalFactory.UNIX:
            type = UnixTerminal.class.getCanonicalName();
            break;
        case TerminalFactory.WIN:
        case TerminalFactory.WINDOWS:
            type = WindowsTerminal.class.getCanonicalName();
            break;
        case TerminalFactory.FALSE:
        case TerminalFactory.OFF:
        case TerminalFactory.NONE:
            type = UnsupportedTerminal.class.getCanonicalName();
            // Disable ANSI, for some reason UnsupportedTerminal reports ANSI as enabled, when it shouldn't
            enableAnsi = false;
            break;
        default:
            // Should never happen
            throw new IllegalArgumentException("Invalid Terminal type: $type");
    }
    if (enableAnsi) {
        // must be called before IO(), since it modifies System.in
        installAnsi();
        Ansi.setEnabled(!suppressColor);
    } else {
        Ansi.setEnabled(false);
    }
    if (type != null) {
        System.setProperty(TerminalFactory.JLINE_TERMINAL, type);
    }
}
Example 50
Project: cloud-slang-master  File: CompilerHelperTest.java View source code
@Test
public void testCompileFoldersCleanup() throws Exception {
    final URI folderPath = getClass().getResource("/executables/dir3").toURI();
    List<String> folders = new ArrayList<>();
    folders.add(folderPath.getPath());
    compilerHelper.compileFolders(folders);
    final URI flowPath = getClass().getResource("/executables/dir3/flow.sl").toURI();
    final URI opPath = getClass().getResource("/executables/dir3/dir3_1/test_op.sl").toURI();
    verify(slang).compileSource(SlangSource.fromFile(opPath), newHashSet(SlangSource.fromFile(opPath), SlangSource.fromFile(flowPath)), PrecompileStrategy.WITH_CACHE);
    InOrder inOrderConsolePrinter = inOrder(consolePrinter);
    inOrderConsolePrinter.verify(consolePrinter, times(2)).printWithColor(any(Ansi.Color.class), anyString());
    inOrderConsolePrinter.verify(consolePrinter).waitForAllPrintTasksToFinish();
    inOrderConsolePrinter.verifyNoMoreInteractions();
    InOrder inOrder = inOrder(slang);
    inOrder.verify(slang, atLeastOnce()).compileSource(SlangSource.fromFile(flowPath), newHashSet(SlangSource.fromFile(opPath), SlangSource.fromFile(flowPath)), PrecompileStrategy.WITH_CACHE);
    inOrder.verify(slang).invalidateAllInPreCompileCache();
    inOrder.verifyNoMoreInteractions();
}
Example 51
Project: Glowstone-Legacy-master  File: ConsoleManager.java View source code
private String colorize(String string) {
    if (string.indexOf(ChatColor.COLOR_CHAR) < 0) {
        // no colors in the message
        return string;
    } else if (!jLine || !reader.getTerminal().isAnsiSupported()) {
        // color not supported
        return ChatColor.stripColor(string);
    } else {
        // colorize or strip all colors
        for (ChatColor color : colors) {
            if (replacements.containsKey(color)) {
                string = string.replaceAll("(?i)" + color.toString(), replacements.get(color));
            } else {
                string = string.replaceAll("(?i)" + color.toString(), "");
            }
        }
        return string + Ansi.ansi().reset().toString();
    }
}
Example 52
Project: GlowstonePlusPlus-master  File: ConsoleManager.java View source code
private String colorize(String string) {
    if (string.indexOf(ChatColor.COLOR_CHAR) < 0) {
        // no colors in the message
        return string;
    } else if (!jLine || !reader.getTerminal().isAnsiSupported()) {
        // color not supported
        return ChatColor.stripColor(string);
    } else {
        // colorize or strip all colors
        for (ChatColor color : colors) {
            if (replacements.containsKey(color)) {
                string = string.replaceAll("(?i)" + color.toString(), replacements.get(color));
            } else {
                string = string.replaceAll("(?i)" + color.toString(), "");
            }
        }
        return string + Ansi.ansi().reset().toString();
    }
}
Example 53
Project: legacy-jclouds-cli-master  File: Main.java View source code
public static void main(String args[]) throws Exception {
    Main main = new Main();
    try {
        main.run(args);
    } catch (CommandNotFoundException cnfe) {
        String str = Ansi.ansi().fg(Ansi.Color.RED).a("Command not found: ").a(Ansi.Attribute.INTENSITY_BOLD).a(cnfe.getCommand()).a(Ansi.Attribute.INTENSITY_BOLD_OFF).fg(Ansi.Color.DEFAULT).toString();
        System.err.println(str);
        System.exit(Errno.UNKNOWN.getErrno());
    } catch (CommandException ce) {
        System.err.println(ce.getNiceHelp());
        System.exit(Errno.UNKNOWN.getErrno());
    } catch (AuthorizationException ae) {
        System.err.println("Authorization error: " + ae.getMessage());
        System.exit(Errno.EACCES.getErrno());
    } catch (ContainerNotFoundException cnfe) {
        System.err.println("Container not found: " + cnfe.getMessage());
        System.exit(Errno.ENOENT.getErrno());
    } catch (FileNotFoundException fnfe) {
        System.err.println("File not found: " + fnfe.getMessage());
        System.exit(Errno.ENOENT.getErrno());
    } catch (IOException ioe) {
        System.err.println("IO error: " + ioe.getMessage());
        System.exit(Errno.EIO.getErrno());
    } catch (KeyNotFoundException knfe) {
        System.err.println("Blob not found: " + knfe.getMessage());
        System.exit(Errno.ENOENT.getErrno());
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(Errno.UNKNOWN.getErrno());
    }
    // We must explicitly exit on success since we do not close
    // BlobStoreContext and ComputeServiceContext.
    System.exit(0);
}
Example 54
Project: citeproc-java-master  File: TestSuiteRunner.java View source code
@Override
public Boolean call() throws Exception {
    Exception ex;
    try {
        runTest(file);
        ex = null;
    } catch (IllegalArgumentExceptionIllegalStateException | IOException |  e) {
        ex = e;
    }
    synchronized (TestSuiteRunner.this) {
        //output name
        String name = file.getName().substring(0, file.getName().length() - 5);
        System.out.print(name);
        for (int i = 0; i < (79 - name.length() - 9); ++i) {
            System.out.print(" ");
        }
        //output result
        if (ex == null) {
            System.out.println("[" + Ansi.ansi().fg(Ansi.Color.GREEN).a("SUCCESS").reset() + "]");
            return Boolean.TRUE;
        } else {
            System.out.println("[" + Ansi.ansi().fg(Ansi.Color.RED).a("FAILURE").reset() + "]");
            System.err.println(ex.getMessage());
            return Boolean.FALSE;
        }
    }
}
Example 55
Project: seam-forge-master  File: ShellImpl.java View source code
@Override
public String renderColor(final ShellColor color, final String output) {
    if (!colorEnabled) {
        return output;
    }
    Ansi ansi = new Ansi();
    switch(color) {
        case BLACK:
            ansi.fg(Ansi.Color.BLACK);
            break;
        case BLUE:
            ansi.fg(Ansi.Color.BLUE);
            break;
        case CYAN:
            ansi.fg(Ansi.Color.CYAN);
            break;
        case GREEN:
            ansi.fg(Ansi.Color.GREEN);
            break;
        case MAGENTA:
            ansi.fg(Ansi.Color.MAGENTA);
            break;
        case RED:
            ansi.fg(Ansi.Color.RED);
            break;
        case WHITE:
            ansi.fg(Ansi.Color.WHITE);
            break;
        case YELLOW:
            ansi.fg(Ansi.Color.YELLOW);
            break;
        case BOLD:
            ansi.a(Ansi.Attribute.INTENSITY_BOLD);
            break;
        default:
            ansi.fg(Ansi.Color.WHITE);
    }
    return ansi.render(output).reset().toString();
}
Example 56
Project: Bias-master  File: MachinePickerView.java View source code
public void render(final VirtualMachine machine, final int index) {
    boolean agentLoaded = machine.isAgentLoaded();
    Ansi.Color color = agentLoaded ? GREEN : DEFAULT;
    String prefix = agentLoaded ? index + ": " : " - ";
    terminal.write( a -> a.fg(color).a(prefix).a(machine.getDisplayName()).reset());
}
Example 57
Project: honest-profiler-master  File: MachinePickerView.java View source code
public void render(final VirtualMachine machine, final int index) {
    boolean agentLoaded = machine.isAgentLoaded();
    Ansi.Color color = agentLoaded ? GREEN : DEFAULT;
    String prefix = agentLoaded ? index + ": " : " - ";
    terminal.write( a -> a.fg(color).a(prefix).a(machine.getDisplayName()).reset());
}
Example 58
Project: LanternServer-master  File: ColoredConsoleFormatter.java View source code
private static void add(char code, Ansi replacement) {
    replacements.put(code, replacement.toString());
    // Add here one so we can check for 0 by default,
    // this requires also to subtract the one for lookups
    lookup.put(code, (byte) ((byte) code + 1));
}
Example 59
Project: Resty-master  File: Colorer.java View source code
private static String diy(String color, String value) {
    if (devEnable) {
        return String.valueOf(Ansi.ansi().eraseScreen().render("@|" + color + " " + value + "|@"));
    } else {
        return value;
    }
}
Example 60
Project: Comix-master  File: LogWriter.java View source code
private void println(String line) {
    try {
        console.print(ConsoleReader.RESET_LINE + line.replaceAll("\\p{C}", "") + Ansi.ansi().reset().toString() + "\n\r");
        console.drawLine();
        console.flush();
    } catch (IOException ex) {
    }
}
Example 61
Project: elasticshell-master  File: AbstractConsole.java View source code
@Override
public void print(String message) {
    logger.debug("print: {}", message);
    out.print(Ansi.ansi().render(message));
}
Example 62
Project: openengsb-master  File: OutputStreamFormater.java View source code
public static String formatValues(String name, String value) {
    return Ansi.ansi().a("  ").a(Ansi.Attribute.INTENSITY_BOLD).a(name).a(spaces(padding - name.length())).a(Ansi.Attribute.RESET).a("   ").a(value).toString();
}
Example 63
Project: eswc2015-tutorial-master  File: ShellUtil.java View source code
private void colorize(Color bg, Color fg, String fmt, Object... args) {
    try {
        Ansi ansi = Ansi.ansi().bg(bg).fg(fg).a(String.format(fmt, args)).reset();
        this.output.print(ansi);
    } catch (Exception e) {
        showFailure(e, fmt, args);
    }
}
Example 64
Project: CorfuDB-master  File: AbstractCorfuTest.java View source code
/** Run when the test successfully completes.
         * @param description   A description of the method run.
         */
protected void succeeded(Description description) {
    if (!testStatus.equals("")) {
        testStatus = " [" + testStatus + "]";
    }
    System.out.print(ansi().a("[").fg(Ansi.Color.GREEN).a("PASS").reset().a("]" + testStatus).newline());
}
Example 65
Project: transparent-master  File: Console.java View source code
public static void lockConsole() {
    if (!consoleLock.isHeldByCurrentThread())
        consoleLock.lock();
    else
        nestedLock++;
    if (isReading && in != null) {
        AnsiConsole.out.print(ERASE);
        AnsiConsole.out.print(new Ansi().cursorLeft(in.getCursorBuffer().cursor + PROMPT.length()));
    }
}
Example 66
Project: flare-spork-master  File: GruntParser.java View source code
@Override
protected void printClear() {
    AnsiConsole.systemInstall();
    Ansi ansi = Ansi.ansi();
    System.out.println(ansi.eraseScreen());
    System.out.println(ansi.cursor(0, 0));
    AnsiConsole.systemUninstall();
}
Example 67
Project: pig-master  File: GruntParser.java View source code
@Override
protected void printClear() {
    AnsiConsole.systemInstall();
    Ansi ansi = Ansi.ansi();
    System.out.println(ansi.eraseScreen());
    System.out.println(ansi.cursor(0, 0));
    AnsiConsole.systemUninstall();
}
Example 68
Project: spork-master  File: GruntParser.java View source code
@Override
protected void printClear() {
    AnsiConsole.systemInstall();
    Ansi ansi = Ansi.ansi();
    System.out.println(ansi.eraseScreen());
    System.out.println(ansi.cursor(0, 0));
    AnsiConsole.systemUninstall();
}
Example 69
Project: spork-streaming-master  File: GruntParser.java View source code
@Override
protected void printClear() {
    AnsiConsole.systemInstall();
    Ansi ansi = Ansi.ansi();
    System.out.println(ansi.eraseScreen());
    System.out.println(ansi.cursor(0, 0));
    AnsiConsole.systemUninstall();
}