Search in sources :

Example 1 with ShellMethod

use of org.springframework.shell.standard.ShellMethod in project cas by apereo.

the class ValidateEndpointCommand method validateEndpoint.

/**
 * Validate endpoint.
 *
 * @param url     the url
 * @param proxy   the proxy
 * @param timeout the timeout
 * @return true/false
 */
@ShellMethod(key = "validate-endpoint", value = "Test connections to an endpoint to verify connectivity, SSL, etc")
public boolean validateEndpoint(@ShellOption(value = { "url", "--url" }, help = "Endpoint URL to test") final String url, @ShellOption(value = { "proxy", "--proxy" }, help = "Proxy address to use when testing the endpoint url", defaultValue = StringUtils.EMPTY) final String proxy, @ShellOption(value = { "timeout", "--timeout" }, help = "Timeout to use in milliseconds when testing the url", defaultValue = "5000") final int timeout) {
    try {
        LOGGER.info("Trying to connect to [{}]", url);
        val conn = createConnection(url, proxy);
        LOGGER.info("Setting connection timeout to [{}]", timeout);
        conn.setConnectTimeout(timeout);
        try (val reader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8);
            val in = new BufferedReader(reader)) {
            in.readLine();
            if (conn instanceof HttpURLConnection) {
                val code = ((HttpURLConnection) conn).getResponseCode();
                LOGGER.info("Response status code received: [{}]", code);
            }
            LOGGER.info("Successfully connected to url [{}]", url);
            return true;
        }
    } catch (final Exception e) {
        LOGGER.info("Could not connect to the host address [{}]", url);
        LOGGER.info("The error is: [{}]", e.getMessage());
        LOGGER.info("Here are the details:");
        LOGGER.error(consolidateExceptionMessages(e));
        testBadTlsConnection(url, proxy);
    }
    return false;
}
Also used : lombok.val(lombok.val) HttpURLConnection(java.net.HttpURLConnection) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) ShellMethod(org.springframework.shell.standard.ShellMethod)

Example 2 with ShellMethod

use of org.springframework.shell.standard.ShellMethod in project cas by apereo.

the class JasyptListProvidersCommand method listProviders.

/**
 * List providers you can use Jasypt.
 *
 * @param includeBC whether to include the BouncyCastle provider
 */
@ShellMethod(key = "jasypt-list-providers", value = "List encryption providers with PBE Ciphers you can use with Jasypt")
public void listProviders(@ShellOption(value = { "includeBC", "--includeBC" }, help = "Include Bouncy Castle provider", defaultValue = "false") final Boolean includeBC) {
    if (includeBC) {
        Security.addProvider(new BouncyCastleProvider());
    } else {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
    val providers = Security.getProviders();
    for (val provider : providers) {
        val services = provider.getServices();
        val algorithms = services.stream().filter(service -> "Cipher".equals(service.getType()) && service.getAlgorithm().contains("PBE")).map(Provider.Service::getAlgorithm).collect(Collectors.toList());
        if (!algorithms.isEmpty()) {
            LOGGER.info("Provider: Name: [{}] Class: [{}]", provider.getName(), provider.getClass().getName());
            for (val algorithm : algorithms) {
                LOGGER.info(" - Algorithm: [{}]", algorithm);
            }
        }
    }
}
Also used : lombok.val(lombok.val) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Provider(java.security.Provider) ShellMethod(org.springframework.shell.standard.ShellMethod)

Example 3 with ShellMethod

use of org.springframework.shell.standard.ShellMethod in project cas by apereo.

the class AddPropertiesToConfigurationCommand method add.

/**
 * Add properties to configuration.
 *
 * @param file  the file
 * @param group the group
 * @throws Exception the exception
 */
@ShellMethod(key = "add-properties", value = "Add properties associated with a CAS group/module to a Properties/Yaml configuration file.")
public static void add(@ShellOption(value = { "file", "--file" }, help = "Path to the CAS configuration file", defaultValue = "/etc/cas/config/cas.properties") final String file, @ShellOption(value = { "group", "--group" }, help = "Group/module whose associated settings should be added to the CAS configuration file") final String group) throws Exception {
    if (StringUtils.isBlank(file)) {
        LOGGER.warn("Configuration file must be specified");
        return;
    }
    val filePath = new File(file);
    if (filePath.exists() && (filePath.isDirectory() || !filePath.canRead() || !filePath.canWrite())) {
        LOGGER.warn("Configuration file [{}] is not readable/writable or is not a path to a file", filePath.getCanonicalPath());
        return;
    }
    val results = findProperties(group);
    LOGGER.info("Located [{}] properties matching [{}]", results.size(), group);
    switch(FilenameUtils.getExtension(filePath.getName()).toLowerCase()) {
        case "properties":
            createConfigurationFileIfNeeded(filePath);
            val props = loadPropertiesFromConfigurationFile(filePath);
            writeConfigurationPropertiesToFile(filePath, results, props);
            break;
        case "yaml":
        case "yml":
            createConfigurationFileIfNeeded(filePath);
            val yamlProps = CasCoreConfigurationUtils.loadYamlProperties(new FileSystemResource(filePath));
            writeYamlConfigurationPropertiesToFile(filePath, results, yamlProps);
            break;
        default:
            LOGGER.warn("Configuration file format [{}] is not recognized", filePath.getCanonicalPath());
    }
}
Also used : lombok.val(lombok.val) FileSystemResource(org.springframework.core.io.FileSystemResource) File(java.io.File) ShellMethod(org.springframework.shell.standard.ShellMethod)

Example 4 with ShellMethod

use of org.springframework.shell.standard.ShellMethod in project cas by apereo.

the class FindPropertiesCommand method find.

/**
 * Find property.
 *
 * @param name    the name
 * @param strict  the strict match
 * @param summary the summary
 */
@ShellMethod(key = "find", value = "Look up properties associated with a CAS group/module.")
public void find(@ShellOption(value = { "name", "--name" }, help = "Property name regex pattern", defaultValue = ".+") final String name, @ShellOption(value = { "strict-match", "--strict-match" }, help = "Whether pattern should be done in strict-mode which means " + "the matching engine tries to match the entire region for the query.") final boolean strict, @ShellOption(value = { "summary", "--summary" }, help = "Whether results should be presented in summarized mode") final boolean summary) {
    val results = find(strict, RegexUtils.createPattern(name));
    if (results.isEmpty()) {
        LOGGER.info("Could not find any results matching the criteria");
        return;
    }
    results.forEach((k, v) -> {
        if (summary) {
            LOGGER.info("[{}]=[{}]", k, v.getDefaultValue());
            val value = StringUtils.normalizeSpace(v.getShortDescription());
            if (StringUtils.isNotBlank(value)) {
                LOGGER.info("[{}]", value);
            }
        } else {
            LOGGER.info("Property: [{}]", k);
            LOGGER.info("Group: [{}]", StringUtils.substringBeforeLast(k, "."));
            LOGGER.info("Default Value: [{}]", ObjectUtils.defaultIfNull(v.getDefaultValue(), "[blank]"));
            LOGGER.info("Type: [{}]", v.getType());
            LOGGER.info("Summary: [{}]", StringUtils.normalizeSpace(v.getShortDescription()));
            LOGGER.info("Description: [{}]", StringUtils.normalizeSpace(v.getDescription()));
            LOGGER.info("Deprecated: [{}]", BooleanUtils.toStringYesNo(v.isDeprecated()));
        }
        LOGGER.info("-".repeat(SEP_LINE_LENGTH));
    });
}
Also used : lombok.val(lombok.val) ShellMethod(org.springframework.shell.standard.ShellMethod)

Example 5 with ShellMethod

use of org.springframework.shell.standard.ShellMethod in project cas by apereo.

the class ValidateRegisteredServiceCommand method validateService.

/**
 * Validate service.
 *
 * @param file      the file
 * @param directory the directory
 */
@ShellMethod(key = "validate-service", value = "Validate a given JSON/YAML service definition by path or directory")
public static void validateService(@ShellOption(value = { "file", "--file" }, help = "Path to the JSON/YAML service definition file", defaultValue = StringUtils.EMPTY) final String file, @ShellOption(value = { "directory", "--directory" }, help = "Path to the JSON/YAML service definitions directory", defaultValue = StringUtils.EMPTY) final String directory) {
    if (StringUtils.isNotBlank(file)) {
        val filePath = new File(file);
        validate(filePath);
        return;
    }
    if (StringUtils.isNotBlank(directory)) {
        val directoryPath = new File(directory);
        if (directoryPath.isDirectory()) {
            FileUtils.listFiles(directoryPath, new String[] { "json", "yml", "yaml" }, false).forEach(ValidateRegisteredServiceCommand::validate);
        }
    }
}
Also used : lombok.val(lombok.val) File(java.io.File) ShellMethod(org.springframework.shell.standard.ShellMethod)

Aggregations

lombok.val (lombok.val)18 ShellMethod (org.springframework.shell.standard.ShellMethod)18 File (java.io.File)7 CasConfigurationJasyptCipherExecutor (org.apereo.cas.configuration.support.CasConfigurationJasyptCipherExecutor)3 SneakyThrows (lombok.SneakyThrows)2 BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)2 BufferedReader (java.io.BufferedReader)1 InputStreamReader (java.io.InputStreamReader)1 Writer (java.io.Writer)1 HttpURLConnection (java.net.HttpURLConnection)1 Charset (java.nio.charset.Charset)1 Files (java.nio.file.Files)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 Provider (java.security.Provider)1 HashMap (java.util.HashMap)1 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)1 Entity (javax.persistence.Entity)1 MappedSuperclass (javax.persistence.MappedSuperclass)1 Slf4j (lombok.extern.slf4j.Slf4j)1 StringUtils (org.apache.commons.lang3.StringUtils)1