Java Code Examples for org.springframework.shell.standard.ShellOption

The following examples show how to use org.springframework.shell.standard.ShellOption. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: sqlhelper   Author: fangjinuo   File: ShowDatabaseCommands.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@ShellMethod(key = "show tables", value = "Show table names")
public List<String> getTableNames(
        @ShellOption(help = "the connection configuration name") String connectionName
) {
    Connection connection = getConnectionByConnectionConfigurationId(connectionName);
    try {
        DatabaseMetaData dbMetaData = connection.getMetaData();
        final DatabaseDescription databaseDescription = new DatabaseDescription(dbMetaData);

        List<Table> tables = new DatabaseLoader().loadTables(databaseDescription, Connections.getCatalog(connection), Connections.getSchema(connection), null);
        return Pipeline.of(tables).map(new Function<Table, String>() {
            @Override
            public String apply(Table table) {
                return SQLs.getTableFQN(databaseDescription, table.getCatalog(), table.getSchema(), table.getName());
            }
        }).asList();
    } catch (Throwable ex) {
        throw Throwables.wrapAsRuntimeException(ex);
    } finally {
        IOs.close(connection);
    }
}
 
Example #2
Source Project: sqlhelper   Author: fangjinuo   File: ShowDatabaseCommands.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@ShellMethod(key = "show indexes", value = "Show table index")
public List<String> getIndexNames(
        @ShellOption(help = "the connection configuration name") String connectionName,
        @ShellOption(help = "the table name") String table) {
    Connection connection = getConnectionByConnectionConfigurationId(connectionName);

    try {
        DatabaseMetaData dbMetaData = connection.getMetaData();
        DatabaseDescription databaseDescription = new DatabaseDescription(dbMetaData);
        List<Index> indexes = new DatabaseLoader().findTableIndexes(databaseDescription, Connections.getCatalog(connection), Connections.getSchema(connection), table);
        return Pipeline.of(indexes).map(new Function<Index, String>() {
            @Override
            public String apply(Index index) {
                return index.getName() + "\t" + SQLs.getTableFQN(index.getCatalog(), index.getSchema(), index.getTableName());
            }
        }).asList();
    } catch (Throwable ex) {
        throw Throwables.wrapAsRuntimeException(ex);
    } finally {
        IOs.close(connection);
    }
}
 
Example #3
Source Project: sqlhelper   Author: fangjinuo   File: ShowDatabaseCommands.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@ShellMethod(key = "show index", value = "Show index detail")
public Index getIndex(@ShellOption(help = "the connection configuration name") String connectionName,
                      @ShellOption(help = "the table name") String table,
                      @ShellOption(help = "the index name") String index) {
    Connection connection = getConnectionByConnectionConfigurationId(connectionName);

    try {
        DatabaseMetaData dbMetaData = connection.getMetaData();
        Table t = new DatabaseLoader().loadTable(new DatabaseDescription(dbMetaData), Connections.getCatalog(connection), Connections.getSchema(connection), table);
        return t.getIndex(index);
    } catch (Throwable ex) {
        throw Throwables.wrapAsRuntimeException(ex);
    } finally {
        IOs.close(connection);
    }
}
 
Example #4
Source Project: sqlhelper   Author: fangjinuo   File: ShowDatabaseCommands.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@ShellMethod(key = "show ddl", value = "Show table DDL")
public String getTableDDL(@ShellOption(help = "the connection configuration name") String connectionName,
                          @ShellOption(help = "the table name") String table) {
    Connection connection = getConnectionByConnectionConfigurationId(connectionName);
    try {
        DatabaseMetaData dbMetaData = connection.getMetaData();
        DatabaseDescription databaseDescription = new DatabaseDescription(dbMetaData);
        Table t = new DatabaseLoader().loadTable(databaseDescription, Connections.getCatalog(connection), Connections.getSchema(connection), table);
        Preconditions.checkNotNull(t, StringTemplates.formatWithPlaceholder("table {} is not exists", table));
        CommonTableGenerator generator = new CommonTableGenerator(databaseDescription);
        return generator.generate(t);
    } catch (Throwable ex) {
        throw Throwables.wrapAsRuntimeException(ex);
    } finally {
        IOs.close(connection);
    }
}
 
Example #5
Source Project: ssh-shell-spring-boot   Author: fonimus   File: ActuatorCommand.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Metrics method
 *
 * @param name metrics name to display
 * @param tags tags to filter with
 * @return metrics
 */
@ShellMethod(key = "metrics", value = "Display metrics endpoint.")
@ShellMethodAvailability("metricsAvailability")
public Object metrics(
        @ShellOption(value = {"-n", "--name"}, help = "Metric name to get", defaultValue = ShellOption.NULL) String name,
        @ShellOption(value = {"-t", "--tags"}, help = "Tags (key=value, separated by coma)", defaultValue =
                ShellOption.NULL) String tags
) {
    if (name != null) {
        MetricsEndpoint.MetricResponse result = metrics.metric(name, tags != null ? Arrays.asList(tags.split(",")
        ) : null);
        if (result == null) {
            String tagsStr = tags != null ? " and tags: " + tags : "";
            throw new IllegalArgumentException("No result for metrics name: " + name + tagsStr);
        }
        return result;
    }
    return metrics.listNames();
}
 
Example #6
Source Project: spring-cloud-skipper   Author: spring-cloud   File: PackageCommands.java    License: Apache License 2.0 6 votes vote down vote up
@ShellMethod(key = "package install", value = "Install a package.")
public String install(
		@ShellOption(help = "name of the package to install") String packageName,
		@ShellOption(help = "version of the package to install, if not specified latest version will be used", defaultValue = ShellOption.NULL) String packageVersion,
		@ShellOption(help = "specify values in a YAML file", defaultValue = ShellOption.NULL) File file,
		@ShellOption(help = "the comma separated set of properties to override during install", defaultValue = ShellOption.NULL) String properties,
		@ShellOption(help = "the release name to use") String releaseName,
		@ShellOption(help = "the platform name to use", defaultValue = "default") String platformName)
		throws IOException {
	// Commented out until https://github.com/spring-cloud/spring-cloud-skipper/issues/263 is
	// addressed
	// assertMutuallyExclusiveFileAndProperties(file, properties);
	Release release = skipperClient
			.install(getInstallRequest(packageName, packageVersion, file, properties, releaseName, platformName));
	return "Released " + release.getName() + ". Now at version v" + release.getVersion() + ".";
}
 
Example #7
Source Project: spring-cloud-skipper   Author: spring-cloud   File: ReleaseCommands.java    License: Apache License 2.0 6 votes vote down vote up
@ShellMethod(key = "release upgrade", value = "Upgrade a release.")
public Object upgrade(
		@ShellOption(help = "the name of the release to upgrade") String releaseName,
		@ShellOption(help = "the name of the package to use for the upgrade") String packageName,
		@ShellOption(help = "the version of the package to use for the upgrade, if not specified latest version will be used", defaultValue = ShellOption.NULL) String packageVersion,
		@ShellOption(help = "specify values in a YAML file", defaultValue = ShellOption.NULL) File file,
		@ShellOption(help = "the expression for upgrade timeout", defaultValue = ShellOption.NULL) String timeoutExpression,
		@ShellOption(help = "the comma separated set of properties to override during upgrade", defaultValue = ShellOption.NULL) String properties,
		@ShellOption(help = "force upgrade") boolean force,
		@ShellOption(help = "application names to force upgrade. If no specific list is provided, all the apps in the packages are force upgraded",
				defaultValue = ShellOption.NULL) String appNames)
		throws IOException {
	// Commented out until https://github.com/spring-cloud/spring-cloud-skipper/issues/263 is
	// addressed
	// assertMutuallyExclusiveFileAndProperties(file, properties);
	if (StringUtils.hasText(appNames)) {
		Assert.isTrue(force, "App names can be used only when the stream update is forced.");
	}
	Release release = skipperClient
			.upgrade(getUpgradeRequest(releaseName, packageName, packageVersion, file, properties, timeoutExpression, force, appNames));
	StringBuilder sb = new StringBuilder();
	sb.append(release.getName() + " has been upgraded.  Now at version v" + release.getVersion() + ".");
	return sb.toString();
}
 
Example #8
Source Project: spring-cloud-skipper   Author: spring-cloud   File: ReleaseCommands.java    License: Apache License 2.0 6 votes vote down vote up
@ShellMethod(key = "release rollback", value = "Rollback the release to a previous or a specific release.")
public String rollback(
		@ShellOption(help = "the name of the release to rollback") String releaseName,
		@ShellOption(help = "the specific release version to rollback to. " +
				"Not specifying the value rolls back to the previous release.", defaultValue = "0") int releaseVersion,
		@ShellOption(help = "the expression for rollback timeout", defaultValue = ShellOption.NULL) String timeoutExpression) {

	RollbackRequest rollbackRequest = new RollbackRequest(releaseName, releaseVersion);
	Duration duration = DurationUtils.convert(timeoutExpression);
	if (duration != null) {
		rollbackRequest.setTimeout(duration.toMillis());
	}

	Release release = skipperClient.rollback(rollbackRequest);
	StringBuilder sb = new StringBuilder();
	sb.append(release.getName() + " has been rolled back.  Now at version v" + release.getVersion() + ".");
	return sb.toString();
}
 
Example #9
Source Project: spring-cloud-skipper   Author: spring-cloud   File: ReleaseCommands.java    License: Apache License 2.0 6 votes vote down vote up
@ShellMethod(key = "release list", value = "List the latest version of releases with status of deployed or failed.")
public Table list(
		@ShellOption(help = "wildcard expression to search by release name", defaultValue = ShellOption.NULL) String releaseName) {
	List<Release> releases = this.skipperClient.list(releaseName);
	LinkedHashMap<String, Object> headers = new LinkedHashMap<>();
	headers.put("name", "Name");
	headers.put("version", "Version");
	headers.put("info.lastDeployed", "Last updated");
	headers.put("info.status.statusCode", "Status");
	headers.put("pkg.metadata.name", "Package Name");
	headers.put("pkg.metadata.version", "Package Version");
	headers.put("platformName", "Platform Name");
	headers.put("info.status.platformStatusPrettyPrint", "Platform Status");
	TableModel model = new BeanListTableModel<>(releases, headers);
	TableBuilder tableBuilder = new TableBuilder(model);
	TableUtils.applyStyle(tableBuilder);
	return tableBuilder.build();
}
 
Example #10
Source Project: spring-cloud-skipper   Author: spring-cloud   File: ReleaseCommands.java    License: Apache License 2.0 6 votes vote down vote up
@ShellMethod(key = "release history", value = "List the history of versions for a given release.")
public Table history(
		@ShellOption(help = "wildcard expression to search by release name") @NotNull String releaseName) {
	Collection<Release> releases;
	releases = this.skipperClient.history(releaseName);
	LinkedHashMap<String, Object> headers = new LinkedHashMap<>();
	headers.put("version", "Version");
	headers.put("info.lastDeployed", "Last updated");
	headers.put("info.status.statusCode", "Status");
	headers.put("pkg.metadata.name", "Package Name");
	headers.put("pkg.metadata.version", "Package Version");
	headers.put("info.description", "Description");
	TableModel model = new BeanListTableModel<>(releases, headers);
	TableBuilder tableBuilder = new TableBuilder(model);
	TableUtils.applyStyle(tableBuilder);
	return tableBuilder.build();
}
 
Example #11
Source Project: spring-cloud-skipper   Author: spring-cloud   File: ManifestCommands.java    License: Apache License 2.0 6 votes vote down vote up
@ShellMethod(key = "manifest get", value = "Get the manifest for a release")
public Object getManifest(
		@ShellOption(help = "release name") @NotNull String releaseName,
		@ShellOption(help = "specific release version.", defaultValue = ShellOption.NULL) Integer releaseVersion) {
	String manifest;
	try {
		if (releaseVersion == null) {
			manifest = this.skipperClient.manifest(releaseName);
		}
		else {
			manifest = this.skipperClient.manifest(releaseName, releaseVersion);
		}
	}
	catch (HttpStatusCodeException e) {
		if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
			return "Release with name '" + releaseName + "' not found";
		}
		// if something else, rethrow
		throw e;
	}
	return manifest;
}
 
Example #12
Source Project: sqlhelper   Author: fangjinuo   File: ShowDatabaseCommands.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@ShellMethod(key = "show table", value = "Show table detail")
public Table getTable(@ShellOption(help = "the connection configuration name") String connectionName,
                      @ShellOption(help = "the table name") String table) {
    Connection connection = getConnectionByConnectionConfigurationId(connectionName);
    try {
        DatabaseMetaData dbMetaData = connection.getMetaData();
        return new DatabaseLoader().loadTable(new DatabaseDescription(dbMetaData), Connections.getCatalog(connection), Connections.getSchema(connection), table);
    } catch (Throwable ex) {
        throw Throwables.wrapAsRuntimeException(ex);
    } finally {
        IOs.close(connection);
    }
}
 
Example #13
Source Project: ICS-TestBed-Framework   Author: PMaynard   File: Main.java    License: GNU General Public License v3.0 5 votes vote down vote up
@ShellMethod(value = "Set listen interface.", group = "RTU", prefix="")
public void rtuListen(
        @ShellOption(defaultValue = "127.0.0.1") String listen
) {
    try {
        if(!listen.equals(DEFAULT_LISTEN))
            this.listen = listen;

    }catch (NumberFormatException ex) {
        System.out.println("Error: Expecting an integer.");
        LOGGER.log(Level.WARNING, ex.toString(), ex);
    }
}
 
Example #14
Source Project: ICS-TestBed-Framework   Author: PMaynard   File: Main.java    License: GNU General Public License v3.0 5 votes vote down vote up
@ShellMethod(value = "Set IEC104 Port.", group = "RTU", prefix="")
public void rtuIEC104Port(
    @ShellOption(defaultValue = "2404") String port
){
    try {
        if(Integer.parseInt(port) != DEFAULT_IEC104_PORT)
            this.portIEC104 = Integer.parseInt(port);

    }catch (NumberFormatException ex) {
        System.out.println("Error: Expecting an integer.");
        LOGGER.log(Level.WARNING, ex.toString(), ex);
    }
}
 
Example #15
Source Project: ssh-shell-spring-boot   Author: fonimus   File: ManageSessionsCommand.java    License: Apache License 2.0 5 votes vote down vote up
@ShellMethod("Displays session")
public String manageSessionsInfo(@ShellOption(value = {"-i", "--session-id"}) long sessionId) {
    ChannelSession session = sessionManager.getSession(sessionId);
    if (session == null) {
        return helper.getError("Session [" + sessionId + "] not found");
    }
    return helper.getSuccess(sessionTable(session.getServerSession()));
}
 
Example #16
Source Project: ssh-shell-spring-boot   Author: fonimus   File: ActuatorCommand.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Audit method
 *
 * @param principal principal to filter with
 * @param type      to filter with
 * @return audit
 */
@ShellMethod(key = "audit", value = "Display audit endpoint.")
@ShellMethodAvailability("auditAvailability")
public AuditEventsEndpoint.AuditEventsDescriptor audit(
        @ShellOption(value = {"-p", "--principal"}, defaultValue = ShellOption.NULL, help = "Principal to filter " +
                "on") String principal,
        @ShellOption(value = {"-t", "--type"}, defaultValue = ShellOption.NULL, help = "Type to filter on") String type) {
    return audit.events(principal, null, type);
}
 
Example #17
Source Project: ssh-shell-spring-boot   Author: fonimus   File: ActuatorCommand.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Environment method
 *
 * @param pattern pattern to filter with
 * @return env
 */
@ShellMethod(key = "env", value = "Display env endpoint.")
@ShellMethodAvailability("envAvailability")
public EnvironmentEndpoint.EnvironmentDescriptor env(
        @ShellOption(value = {"-p", "--pattern"}, defaultValue = ShellOption.NULL, help = "Pattern " +
                "to filter on") String pattern) {
    return env.environment(pattern);
}
 
Example #18
Source Project: ssh-shell-spring-boot   Author: fonimus   File: ActuatorCommand.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Loggers method
 *
 * @param action      action to make
 * @param loggerName  logger name for get or configure
 * @param loggerLevel logger level for configure
 * @return loggers
 */
@ShellMethod(key = "loggers", value = "Display or configure loggers.")
@ShellMethodAvailability("loggersAvailability")
public Object loggers(
        @ShellOption(value = {"-a", "--action"}, help = "Action to perform", defaultValue = "list") LoggerAction action,
        @ShellOption(value = {"-n", "--name"}, help = "Logger name for configuration or display", defaultValue =
                ShellOption.NULL) String loggerName,
        @ShellOption(value = {"-l", "--level"}, help = "Logger level for configuration", defaultValue =
                ShellOption.NULL) LogLevel loggerLevel) {
    if ((action == LoggerAction.get || action == LoggerAction.conf) && loggerName == null) {
        throw new IllegalArgumentException("Logger name is mandatory for '" + action + "' action");
    }
    switch (action) {
        case get:
            LoggersEndpoint.LoggerLevels levels = loggers.loggerLevels(loggerName);
            return "Logger named [" + loggerName + "] : [configured: " + levels.getConfiguredLevel() + "]";
        case conf:
            if (loggerLevel == null) {
                throw new IllegalArgumentException("Logger level is mandatory for '" + action + "' action");
            }
            loggers.configureLogLevel(loggerName, loggerLevel);
            return "Logger named [" + loggerName + "] now configured to level [" + loggerLevel + "]";
        default:
            // list
            return loggers.loggers();
    }
}
 
Example #19
Source Project: ssh-shell-spring-boot   Author: fonimus   File: DemoCommand.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Echo command
 *
 * @param message message to print
 * @param color   color for the message
 * @return message
 */
@ShellMethod("Echo command")
public String echo(String message, @ShellOption(defaultValue = ShellOption.NULL) PromptColor color) {
    if (color != null) {
        return new AttributedStringBuilder().append(message,
                AttributedStyle.DEFAULT.foreground(color.toJlineAttributedStyle())).toAnsi();
    }
    return message;
}
 
Example #20
Source Project: spring-cloud-skipper   Author: spring-cloud   File: PackageCommands.java    License: Apache License 2.0 5 votes vote down vote up
@ShellMethod(key = "package delete", value = "Delete a package.")
public String packageDelete(@ShellOption(help = "the package name to be deleted") String packageName) {
	try {
		this.skipperClient.packageDelete(packageName);
	}
	catch (PackageDeleteException e) {
		return e.getMessage();
	}
	return String.format("Deleted Package '%s'", packageName);
}
 
Example #21
Source Project: spring-cloud-skipper   Author: spring-cloud   File: ConfigCommands.java    License: Apache License 2.0 5 votes vote down vote up
@ShellMethod(key = "skipper config", value = "Configure the Spring Cloud Skipper REST server to use.")
public String target(
		@ShellOption(help = "the location of the Spring Cloud Skipper REST endpoint", defaultValue = SkipperClientProperties.DEFAULT_TARGET)
				String uri,
		@ShellOption(help = "the username for authenticated access to the Admin REST endpoint", defaultValue = ShellOption.NULL)
				String username,
		@ShellOption(help = "the password for authenticated access to the Admin REST endpoint " +
				"(valid only with a username)", defaultValue = ShellOption.NULL)
				String password,
		@ShellOption(help = "a command to run that outputs the HTTP credentials used for authentication", defaultValue = ShellOption.NULL)
				String credentialsProviderCommand,
		@ShellOption(help = "accept any SSL certificate (even self-signed)")
				boolean skipSslValidation) throws Exception {
	// @formatter:on
	if (credentialsProviderCommand == null && password != null && username == null) {
		return "A password may be specified only together with a username";
	}

	if (credentialsProviderCommand == null &&
			password == null && username != null) {
		// read password from the command line
		password = userInput.prompt("Password", "", false);
	}

	this.targetHolder.changeTarget(new Target(uri, username, password, skipSslValidation),
			credentialsProviderCommand);

	return (this.targetHolder.getTarget().getTargetResultMessage());
}
 
Example #22
Source Project: spring-cloud-skipper   Author: spring-cloud   File: ReleaseCommands.java    License: Apache License 2.0 5 votes vote down vote up
@ShellMethod(key = "release delete", value = "Delete the release.")
public String delete(
		@ShellOption(help = "the name of the release to delete") String releaseName,
		@ShellOption(help = "delete the release package", defaultValue = "false") boolean deletePackage) {
	this.skipperClient.delete(releaseName, deletePackage);
	StringBuilder sb = new StringBuilder();
	sb.append(releaseName + " has been deleted.");
	return sb.toString();
}
 
Example #23
Source Project: spring-cloud-skipper   Author: spring-cloud   File: ReleaseCommands.java    License: Apache License 2.0 5 votes vote down vote up
@ShellMethod(key = "release cancel", value = "Request a cancellation of current release operation.")
public String cancel(
		@ShellOption(help = "the name of the release to cancel") String releaseName) {
	CancelResponse cancelResponse = this.skipperClient.cancel(new CancelRequest(releaseName));
	if (cancelResponse != null && cancelResponse.getAccepted() != null && cancelResponse.getAccepted()) {
		return "Cancel request for release " + releaseName + " sent";
	}
	throw new SkipperException("Cancel request for release " + releaseName + " not accepted");
}
 
Example #24
Source Project: spring-cloud-skipper   Author: spring-cloud   File: ReleaseCommands.java    License: Apache License 2.0 5 votes vote down vote up
@ShellMethod(key = "release status", value = "Status for a last known release version.")
public Object status(
		@ShellOption(help = "release name") @NotNull String releaseName,
		@ShellOption(help = "the specific release version.", defaultValue = ShellOption.NULL) Integer releaseVersion) {
	Info info;
	try {
		if (releaseVersion == null) {
			info = this.skipperClient.status(releaseName);
		}
		else {
			info = this.skipperClient.status(releaseName, releaseVersion);
		}
	}
	catch (ReleaseNotFoundException e) {
		return "Release with name '" + e.getReleaseName() + "' not found";
	}
	Object[][] data = new Object[3][];
	data[0] = new Object[] { "Last Deployed", info.getFirstDeployed() };
	data[1] = new Object[] { "Status", info.getStatus().getStatusCode().toString() };

	DeploymentState aggregateState = aggregateState(info.getStatus().getDeploymentStateList());
	StringBuilder sb = new StringBuilder();
	sb.append(DeploymentStateDisplay.fromKey(aggregateState.name()).getDescription() + "\n");
	sb.append(info.getStatus().getPlatformStatusPrettyPrint());
	data[2] = new Object[] { "Platform Status", sb.toString() };
	TableModel model = new ArrayTableModel(data);
	TableBuilder tableBuilder = new TableBuilder(model);
	TableUtils.applyStyleNoHeader(tableBuilder);
	return tableBuilder.build();
}
 
Example #25
Source Project: java-examples   Author: pajikos   File: ScannerCommand.java    License: MIT License 5 votes vote down vote up
@ShellMethod(value = "Scan open ports for a specific IP address")
public String scan(
        @ShellOption(help = "IP address") String ip,
        @ShellOption(help = "Specific port or port range, e.g. 1-1024") String port,
        @ShellOption(help = "Weather only open ports should be displayed") boolean displayOnlyOpen
) throws ExecutionException, InterruptedException {
    //Add all required ports into port scanner
    List<Future<ScannerService.ScanResult>> futureList;
    if (port.contains(PORT_SEPARATOR)) {
        String[] rangeLimits = port.split(PORT_SEPARATOR);
        futureList = addToScan(ip, range(Integer.parseInt(rangeLimits[0]), Integer.parseInt(rangeLimits[1])));
    } else {
        futureList = addToScan(ip, Integer.parseInt(port));
    }

    //Read and write results
    for (final Future<ScannerService.ScanResult> scanResultFuture : futureList) {
        ScannerService.ScanResult scanResult = scanResultFuture.get();
        if (displayOnlyOpen) {
            if (scanResult.isOpen()) {
                System.out.println(scanResult);
            }
        } else {
            System.out.println(scanResult);
        }
    }

    return "DONE";
}
 
Example #26
Source Project: ssh-shell-spring-boot   Author: fonimus   File: HistoryCommand.java    License: Apache License 2.0 4 votes vote down vote up
@ShellMethod(value = "Display or save the history of previously run commands")
public List<String> history(@ShellOption(help = "A file to save history to.", defaultValue = ShellOption.NULL) File file) throws IOException {
    return new History(helper.getHistory()).history(file);
}
 
Example #27
Source Project: ssh-shell-spring-boot   Author: fonimus   File: ManageSessionsCommand.java    License: Apache License 2.0 4 votes vote down vote up
@ShellMethod("Stop session")
public String manageSessionsStop(@ShellOption(value = {"-i", "--session-id"}) long sessionId) {
    return sessionManager.stopSession(sessionId) ?
            helper.getSuccess("Session [" + sessionId + "] stopped") :
            helper.getWarning("Unable to stop session [" + sessionId + "], maybe it does not exist");
}
 
Example #28
Source Project: ssh-shell-spring-boot   Author: fonimus   File: ThreadCommand.java    License: Apache License 2.0 4 votes vote down vote up
@ShellMethod("Thread command.")
public String threads(@ShellOption(defaultValue = "LIST") ThreadAction action,
                      @ShellOption(help = "Order by column. Default is: ID", defaultValue = "ID") ThreadColumn orderBy,
                      @ShellOption(help = "Reverse order by column. Default is: false") boolean reverseOrder,
                      @ShellOption(help = "Not interactive. Default is: false") boolean staticDisplay,
                      @ShellOption(help = "Only for DUMP action", defaultValue = ShellOption.NULL) Long threadId) {

    if (action == ThreadAction.DUMP) {
        Thread th = get(threadId);
        helper.print("Name  : " + th.getName());
        helper.print("State : " + helper.getColored(th.getState().name(), color(th.getState())) + "\n");
        Exception e = new Exception("Thread [" + th.getId() + "] stack trace");
        e.setStackTrace(th.getStackTrace());
        e.printStackTrace(helper.terminalWriter());
        return "";
    }

    if (staticDisplay) {
        return table(orderBy, reverseOrder, false);
    }

    boolean[] finalReverseOrder = {reverseOrder};
    ThreadColumn[] finalOrderBy = {orderBy};

    Interactive.InteractiveBuilder builder = Interactive.builder();
    for (ThreadColumn value : ThreadColumn.values()) {
        String key = value == ThreadColumn.INTERRUPTED ? "t" : value.name().toLowerCase().substring(0, 1);
        builder.binding(KeyBinding.builder().description("ORDER_" + value.name()).key(key)
                .input(() -> {
                    if (value == finalOrderBy[0]) {
                        finalReverseOrder[0] = !finalReverseOrder[0];
                    } else {
                        finalOrderBy[0] = value;
                    }
                }).build());
    }
    builder.binding(KeyBinding.builder().key("r").description("REVERSE")
            .input(() -> finalReverseOrder[0] = !finalReverseOrder[0]).build());

    helper.interactive(builder.input((size, currentDelay) -> {
        List<AttributedString> lines = new ArrayList<>(size.getRows());

        lines.add(new AttributedStringBuilder()
                .append("Time: ")
                .append(FORMATTER.format(LocalDateTime.now()), AttributedStyle.BOLD)
                .append(", refresh delay: ")
                .append(String.valueOf(currentDelay), AttributedStyle.BOLD)
                .append(" ms\n")
                .toAttributedString());

        for (String s : table(finalOrderBy[0], finalReverseOrder[0], true).split("\n")) {
            lines.add(AttributedString.fromAnsi(s));
        }

        lines.add(AttributedString.fromAnsi("Press 'r' to reverse order, first column letter to change order by"));
        String msg = INTERACTIVE_LONG_MESSAGE.length() <= helper.terminalSize().getColumns() ?
                INTERACTIVE_LONG_MESSAGE : INTERACTIVE_SHORT_MESSAGE;
        lines.add(AttributedString.fromAnsi(msg));

        return lines;
    }).build());
    return "";
}
 
Example #29
Source Project: ssh-shell-spring-boot   Author: fonimus   File: AnyOsFileValueProviderTest.java    License: Apache License 2.0 2 votes vote down vote up
private void test(@ShellOption(valueProvider = AnyOsFileValueProvider.class) File file, File otherFile,
                  String notAFile) {

}
 
Example #30
Source Project: ssh-shell-spring-boot   Author: fonimus   File: DemoCommand.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Echo command
 *
 * @param message message to print
 * @return message
 */
@ShellMethod("Echo command")
public String echo(@ShellOption(valueProvider = CustomValuesProvider.class) String message) {
    return message;
}