repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Batch.java
package org.infinispan.cli.commands; import org.aesh.command.Command; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.invocation.CommandInvocation; import org.infinispan.cli.commands.rest.Add; import org.infinispan.cli.commands.rest.Alter; import org.infinispan.cli.commands.rest.Availability; import org.infinispan.cli.commands.rest.Backup; import org.infinispan.cli.commands.rest.Cas; import org.infinispan.cli.commands.rest.ClearCache; import org.infinispan.cli.commands.rest.Create; import org.infinispan.cli.commands.rest.Drop; import org.infinispan.cli.commands.rest.Get; import org.infinispan.cli.commands.rest.Index; import org.infinispan.cli.commands.rest.Migrate; import org.infinispan.cli.commands.rest.Put; import org.infinispan.cli.commands.rest.Query; import org.infinispan.cli.commands.rest.Rebalance; import org.infinispan.cli.commands.rest.Remove; import org.infinispan.cli.commands.rest.Reset; import org.infinispan.cli.commands.rest.Schema; import org.infinispan.cli.commands.rest.Server; import org.infinispan.cli.commands.rest.Shutdown; import org.infinispan.cli.commands.rest.Site; import org.infinispan.cli.commands.rest.Stats; import org.infinispan.cli.commands.rest.Task; import org.infinispan.cli.commands.rest.Topology; import org.infinispan.cli.impl.ExitCodeResultHandler; /** * @author Tristan Tarrant <tristan@infinispan.org> * @since 10.0 **/ @GroupCommandDefinition( name = "batch", description = "", groupCommands = { Add.class, Alter.class, Availability.class, Backup.class, Benchmark.class, Cache.class, Cas.class, Cd.class, ClearCache.class, Config.class, Connect.class, Container.class, Counter.class, Create.class, Credentials.class, Describe.class, Disconnect.class, Drop.class, Echo.class, Encoding.class, Get.class, Index.class, Install.class, Ls.class, Migrate.class, Patch.class, Put.class, Query.class, Rebalance.class, Remove.class, Reset.class, Run.class, Schema.class, Server.class, Shutdown.class, Stats.class, Site.class, Task.class, Topology.class, User.class, Version.class }, resultHandler = ExitCodeResultHandler.class) public class Batch implements Command { @Override public CommandResult execute(CommandInvocation invocation) { return CommandResult.SUCCESS; } }
2,824
30.741573
63
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Credentials.java
package org.infinispan.cli.commands; import static org.infinispan.cli.logging.Messages.MSG; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.aesh.io.FileResource; import org.aesh.io.Resource; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.kohsuke.MetaInfServices; import org.wildfly.security.auth.server.IdentityCredentials; import org.wildfly.security.credential.PasswordCredential; import org.wildfly.security.credential.store.CredentialStore; import org.wildfly.security.credential.store.CredentialStoreException; import org.wildfly.security.credential.store.impl.KeyStoreCredentialStore; import org.wildfly.security.password.interfaces.ClearPassword; import org.wildfly.security.util.PasswordBasedEncryptionUtil; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "credentials", description = "Credential store operations", groupCommands = {Credentials.Add.class, Credentials.Remove.class, Credentials.Ls.class, Credentials.Mask.class}) public class Credentials extends CliCommand { public static final String STORE_TYPE = "pkcs12"; public static final String CREDENTIALS_PATH = "credentials.pfx"; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } static KeyStoreCredentialStore getKeyStoreCredentialStore(Path path, String type, boolean create, char[] password) throws CredentialStoreException { KeyStoreCredentialStore store = new KeyStoreCredentialStore(); final Map<String, String> map = new HashMap<>(); map.put("location", path.toAbsolutePath().toString()); map.put("keyStoreType", type); map.put("create", Boolean.toString(create)); store.initialize( map, new CredentialStore.CredentialSourceProtectionParameter( IdentityCredentials.NONE.withCredential(new PasswordCredential(ClearPassword.createRaw(ClearPassword.ALGORITHM_CLEAR, password)))), null ); return store; } static Path resourceToPath(Resource resource, String serverRoot) { if (((FileResource) resource).getFile().getParent() != null) { return Paths.get(resource.getAbsolutePath()); } else { String serverHome = System.getProperty("infinispan.server.home.path"); Path serverHomePath = serverHome == null ? Paths.get("") : Paths.get(serverHome); return serverHomePath.resolve(serverRoot).resolve("conf").resolve(((FileResource) resource).getFile().getPath()).toAbsolutePath(); } } @CommandDefinition(name = "add", description = "Adds credentials to keystores.") public static class Add extends CliCommand { @Argument(description = "Specifies an alias, or name, for the credential.", required = true) String alias; @Option(description = "Sets the path to a credential keystore and creates a new one if it does not exist.", completer = FileOptionCompleter.class, defaultValue = CREDENTIALS_PATH) Resource path; @Option(description = "Specifies a password to protect the credential keystore.", shortName = 'p') String password; @Option(description = "Sets the type of credential store. Values are either PKCS12, which is the default, or JCEKS.", shortName = 't', defaultValue = STORE_TYPE) String type; @Option(description = "Adds a credential to the keystore.", shortName = 'c') String credential; @Option(description = "Sets the path to the server root directory.", defaultValue = "server", name = "server-root", shortName = 's') String serverRoot; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { try { Path file = resourceToPath(path, serverRoot); if (password == null) { password = invocation.getPasswordInteractively(MSG.credentialToolPassword(), Files.exists(file) ? null : MSG.credentialToolPasswordConfirm()); } if (credential == null) { credential = invocation.getPasswordInteractively(MSG.credentialToolCredential(), MSG.credentialToolCredentialConfirm()); } KeyStoreCredentialStore store = getKeyStoreCredentialStore(file, type, true, password.toCharArray()); store.store(alias, new PasswordCredential(ClearPassword.createRaw(ClearPassword.ALGORITHM_CLEAR, credential.toCharArray())), null); store.flush(); return CommandResult.SUCCESS; } catch (Exception e) { throw new CommandException(e); } } } @CommandDefinition(name = "remove", description = "Deletes credentials from keystores.", aliases = "rm") public static class Remove extends CliCommand { @Argument(description = "Specifies an alias, or name, for the credential.", required = true) String alias; @Option(description = "Sets the path to a credential keystore.", completer = FileOptionCompleter.class, defaultValue = CREDENTIALS_PATH) Resource path; @Option(description = "Specifies the password that protects the credential keystore.", shortName = 'p') String password; @Option(description = "Sets the type of credential store. Values are either PKCS12, which is the default, or JCEKS.", shortName = 't', defaultValue = STORE_TYPE) String type; @Option(description = "Sets the path to the server root directory.", defaultValue = "server", name = "server-root", shortName = 's') String serverRoot; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { try { Path file = resourceToPath(path, serverRoot); if (password == null) { password = invocation.getPasswordInteractively(MSG.credentialToolPassword(), null); } KeyStoreCredentialStore store = getKeyStoreCredentialStore(file, type, false, password.toCharArray()); store.remove(alias, PasswordCredential.class, null, null); store.flush(); return CommandResult.SUCCESS; } catch (Exception e) { throw new CommandException(e); } } } @CommandDefinition(name = "ls", description = "Lists credential aliases in keystores.") public static class Ls extends CliCommand { @Option(description = "Sets the path to a credential keystore.", completer = FileOptionCompleter.class, defaultValue = CREDENTIALS_PATH) Resource path; @Option(description = "Specifies the password that protects the credential keystore.", shortName = 'p') String password; @Option(description = "Sets the type of credential store. Values are either PKCS12, which is the default, or JCEKS.", shortName = 't', defaultValue = STORE_TYPE) String type; @Option(description = "Sets the path to the server root directory.", defaultValue = "server", name = "server-root", shortName = 's') String serverRoot; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { try { Path file = resourceToPath(path, serverRoot); if (Files.exists(file)) { if (password == null) { password = invocation.getPasswordInteractively(MSG.credentialToolPassword(), null); } KeyStoreCredentialStore store = getKeyStoreCredentialStore(file, type, false, password.toCharArray()); for (String alias : store.getAliases()) { invocation.println(alias); } } return CommandResult.SUCCESS; } catch (Exception e) { throw new CommandException(e); } } } @CommandDefinition(name = "mask", description = "Masks the password for a credential keystore.") public static class Mask extends CliCommand { @Argument(description = "Specifies the password to mask.", required = true) String password; @Option(description = "Specifies a salt value for the encryption.", shortName = 's', required = true) String salt; @Option(description = "Sets the number of iterations.", shortName = 'i', required = true) Integer iterations; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { try { PasswordBasedEncryptionUtil pbe = new PasswordBasedEncryptionUtil.Builder() .picketBoxCompatibility() .salt(salt) .iteration(iterations) .encryptMode() .build(); invocation.printf("%s;%s;%d%n", pbe.encryptAndEncode(password.toCharArray()), salt, iterations); return CommandResult.SUCCESS; } catch (Exception e) { throw new CommandException(e); } } } }
10,501
40.184314
203
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/CacheAwareCommand.java
package org.infinispan.cli.commands; import java.util.Optional; import org.infinispan.cli.resources.Resource; /** * An interface for CLI commands to implement which require a cache name. * * @author Pedro Ruivo * @since 12.1 */ public interface CacheAwareCommand { Optional<String> getCacheName(Resource activeResource); }
336
17.722222
73
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/CliCommand.java
package org.infinispan.cli.commands; import org.aesh.command.Command; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.terminal.utils.ANSI; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.util.Util; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public abstract class CliCommand implements Command<ContextAwareCommandInvocation> { @Override public CommandResult execute(ContextAwareCommandInvocation invocation) throws CommandException { if (isHelp()) { invocation.println(invocation.getHelpInfo()); return CommandResult.SUCCESS; } try { return exec(invocation); } catch (CommandException e) { Throwable cause = Util.getRootCause(e); invocation.getShell().writeln(ANSI.RED_TEXT + e.getLocalizedMessage() + ANSI.DEFAULT_TEXT); if (cause != e) { invocation.getShell().writeln(ANSI.RED_TEXT + cause.getClass().getSimpleName() + ": " + cause.getLocalizedMessage() + ANSI.DEFAULT_TEXT); } return CommandResult.FAILURE; } catch (CacheConfigurationException e) { System.err.println(ANSI.RED_TEXT + e.getLocalizedMessage() + ANSI.DEFAULT_TEXT); return CommandResult.FAILURE; } catch (Throwable e) { // These are unhandled Throwable cause = Util.getRootCause(e); System.err.println(ANSI.RED_TEXT + cause.getClass().getSimpleName() +": " + cause.getLocalizedMessage() + ANSI.DEFAULT_TEXT); return CommandResult.FAILURE; } } protected abstract boolean isHelp(); protected abstract CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException; public int nesting() { return 0; } }
1,892
36.117647
149
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Run.java
package org.infinispan.cli.commands; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.concurrent.Callable; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.option.Arguments; import org.aesh.command.option.Option; import org.aesh.command.shell.Shell; import org.aesh.io.Resource; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.impl.ExitCodeResultHandler; import org.infinispan.cli.logging.Messages; import org.infinispan.commons.util.StringPropertyReplacer; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "run", description = "Reads and executes commands from one or more files", resultHandler = ExitCodeResultHandler.class) public class Run extends CliCommand { @Arguments(required = true, completer = FileOptionCompleter.class) private List<Resource> arguments; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { if (arguments != null && arguments.size() > 0) { for (Resource resource : arguments) { boolean stdin = "-".equals(resource.getName()); if (stdin) { Shell shell = invocation.getShell(); processInput("<STDIN>", shell::readLine, invocation); } else { try (BufferedReader br = new BufferedReader(new InputStreamReader(resource.read()))) { processInput(resource.getAbsolutePath(), br::readLine, invocation); } catch (IOException e) { throw Messages.MSG.batchError(resource.getAbsolutePath(), 0, "", e); } } } } return CommandResult.SUCCESS; } private void processInput(String source, Callable<String> lineSupplier, ContextAwareCommandInvocation invocation) throws CommandException { int lineCount = 0; String line = null; try { for (line = lineSupplier.call(); line != null; line = lineSupplier.call()) { lineCount++; if (!line.startsWith("#")) { invocation.executeCommand("batch " + StringPropertyReplacer.replaceProperties(line)); } } } catch (Throwable e) { throw Messages.MSG.batchError(source, lineCount, line, e); } } }
2,830
35.294872
145
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Counter.java
package org.infinispan.cli.commands; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.CounterCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.ContainerResource; import org.infinispan.cli.resources.CountersResource; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "counter", description = "Selects counters", activator = ConnectionActivator.class) public class Counter extends CliCommand { @Argument(description = "The name of the counter to select", completer = CounterCompleter.class, required = true) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { return invocation.getContext().changeResource(ContainerResource.class, CountersResource.NAME, name); } }
1,387
33.7
116
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Describe.java
package org.infinispan.cli.commands; import java.io.IOException; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.CdContextCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "describe", description = "Displays information about the specified resource", activator = ConnectionActivator.class) public class Describe extends CliCommand { @Argument(description = "The path of the resource", completer = CdContextCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { try { invocation.println(invocation.getContext().getConnection().getActiveResource().getResource(name).describe()); return CommandResult.SUCCESS; } catch (IOException e) { throw new CommandException(e); } } }
1,463
31.533333
143
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Version.java
package org.infinispan.cli.commands; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.option.Option; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.impl.KubernetesContext; import org.kohsuke.MetaInfServices; import io.fabric8.kubernetes.client.KubernetesClient; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "version", description = "Shows version information") public class Version extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { invocation.println(String.format("CLI: %s", org.infinispan.commons.util.Version.printVersion())); if (invocation.getContext().isConnected()) { invocation.println("Server: " + invocation.getContext().getConnection().getServerVersion()); } if (invocation.getContext() instanceof KubernetesContext) { KubernetesClient client = ((KubernetesContext) invocation.getContext()).getKubernetesClient(); invocation.printf("Kubernetes %s.%s\n", client.getVersion().getMajor(), client.getVersion().getMinor()); } return CommandResult.SUCCESS; } }
1,485
34.380952
113
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Disconnect.java
package org.infinispan.cli.commands; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "disconnect", description = "Disconnects from a remote server", activator = ConnectionActivator.class) public class Disconnect extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { if (invocation.getContext().isConnected()) { invocation.getContext().disconnect(); return CommandResult.SUCCESS; } else { invocation.getShell().writeln("Not connected"); return CommandResult.FAILURE; } } }
1,153
29.368421
128
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Patch.java
package org.infinispan.cli.commands; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.option.Argument; import org.aesh.command.option.Arguments; import org.aesh.command.option.Option; import org.aesh.io.Resource; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.logging.Messages; import org.infinispan.cli.patching.PatchTool; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "patch", description = "Patch operations", groupCommands = {Patch.Create.class, Patch.Describe.class, Patch.Install.class, Patch.Ls.class, Patch.Rollback.class}) public class Patch extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "create", description = "Creates a patch archive") public static class Create extends CliCommand { @Option(defaultValue = "", shortName = 'q', description = "A qualifier for this patch (e.g. `one-off`)") String qualifier; @Arguments(completer = FileOptionCompleter.class, description = "The path to the patch archive, the path to the target server and one or more paths to the source servers") List<Resource> paths; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { if (paths == null || paths.size() < 3) { throw Messages.MSG.patchCreateArgumentsRequired(); } PatchTool patchTool = new PatchTool(invocation.getShellOutput(), invocation.getShellError()); try { Path patch = Paths.get(paths.get(0).getAbsolutePath()); Path target = Paths.get(paths.get(1).getAbsolutePath()); Path sources[] = new Path[paths.size() - 2]; for (int i = 2; i < paths.size(); i++) { sources[i - 2] = Paths.get(paths.get(i).getAbsolutePath()); } patchTool.createPatch(qualifier, patch, target, sources); return CommandResult.SUCCESS; } catch (IOException e) { throw new CommandException(e); } } } @CommandDefinition(name = "describe", description = "Describes the contents of a patch archive") public static class Describe extends CliCommand { @Argument(completer = FileOptionCompleter.class, description = "The path to a patch archive") Resource patch; @Option(shortName = 'v', hasValue = false, description = "List the contents of the patch including all the actions that will be performed") boolean verbose; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { if (patch == null) { throw Messages.MSG.patchArchiveArgumentRequired(); } PatchTool patchTool = new PatchTool(invocation.getShellOutput(), invocation.getShellError()); try { patchTool.describePatch(Paths.get(patch.getAbsolutePath()), verbose); return CommandResult.SUCCESS; } catch (IOException e) { throw new CommandException(e); } } } @CommandDefinition(name = "install", description = "Installs a patch archive") public static class Install extends CliCommand { @Argument(completer = FileOptionCompleter.class, description = "The path to a patch archive") Resource patch; @Option(completer = FileOptionCompleter.class, description = "The path to the server on which the patch will be installed.") Resource server; @Option(hasValue = false, name = "dry-run", description = "Only list the actions that will be performed without executing them.") boolean dryRun; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { if (patch == null) { throw Messages.MSG.patchArchiveArgumentRequired(); } PatchTool patchTool = new PatchTool(invocation.getShellOutput(), invocation.getShellError()); try { patchTool.installPatch(Paths.get(patch.getAbsolutePath()), CLI.getServerHome(server), dryRun); return CommandResult.SUCCESS; } catch (IOException e) { throw new CommandException(e); } } } @CommandDefinition(name = "ls", description = "Lists the patches installed on this server", aliases = "list") public static class Ls extends CliCommand { @Option(completer = FileOptionCompleter.class, description = "The path to the server installation.") Resource server; @Option(shortName = 'v', hasValue = false, description = "List the contents of all installed patches.") boolean verbose; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { PatchTool patchTool = new PatchTool(invocation.getShellOutput(), invocation.getShellError()); patchTool.listPatches(CLI.getServerHome(server), verbose); return CommandResult.SUCCESS; } } @CommandDefinition(name = "rollback", description = "Rolls back the latest patch installed on this server.") public static class Rollback extends CliCommand { @Option(completer = FileOptionCompleter.class, description = "The path to the server installation.") Resource server; @Option(hasValue = false, name = "dry-run", description = "Only list the actions that will be performed without executing them.") boolean dryRun; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { PatchTool patchTool = new PatchTool(invocation.getShellOutput(), invocation.getShellError()); try { patchTool.rollbackPatch(CLI.getServerHome(server), dryRun); return CommandResult.SUCCESS; } catch (IOException e) { throw new CommandException(e); } } } }
7,633
35.879227
192
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Quit.java
package org.infinispan.cli.commands; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.option.Option; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "quit", description = "Exits the CLI", aliases = {"exit", "bye"}) public class Quit extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { invocation.getContext().disconnect(); invocation.stop(); return CommandResult.SUCCESS; } }
901
26.333333
91
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Help.java
package org.infinispan.cli.commands; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.invocation.CommandInvocation; import org.aesh.command.man.AeshFileDisplayer; import org.aesh.command.man.FileParser; import org.aesh.command.man.TerminalPage; import org.aesh.command.man.parser.ManFileParser; import org.aesh.command.option.Arguments; import org.aesh.command.settings.ManProvider; import org.aesh.command.shell.Shell; import org.aesh.readline.terminal.formatting.TerminalString; import org.aesh.readline.util.Parser; import org.aesh.terminal.utils.ANSI; import org.aesh.terminal.utils.Config; import org.infinispan.cli.completers.HelpCompleter; import org.infinispan.cli.impl.CliManProvider; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.kohsuke.MetaInfServices; @MetaInfServices(Command.class) @CommandDefinition(name = "help", description = "Displays help for commands") public class Help extends AeshFileDisplayer { @Arguments(completer = HelpCompleter.class) private final List<String> manPages; private final ManFileParser fileParser; private final ManProvider manProvider; public Help() { super(); this.manProvider = new CliManProvider(); manPages = new ArrayList<>(); fileParser = new ManFileParser(); } @Override public FileParser getFileParser() { return fileParser; } @Override public void displayBottom() throws IOException { if (getSearchStatus() == TerminalPage.Search.SEARCHING) { clearBottomLine(); writeToConsole("/" + getSearchWord()); } else if (getSearchStatus() == TerminalPage.Search.NOT_FOUND) { clearBottomLine(); writeToConsole(ANSI.INVERT_BACKGROUND + "Pattern not found (press RETURN)" + ANSI.DEFAULT_TEXT); } else if (getSearchStatus() == TerminalPage.Search.NO_SEARCH || getSearchStatus() == TerminalPage.Search.RESULT) { writeToConsole(ANSI.INVERT_BACKGROUND); writeToConsole("Manual page " + fileParser.getName() + " line " + getTopVisibleRow() + " (press h for help or q to quit)" + ANSI.DEFAULT_TEXT); } } @Override public CommandResult execute(CommandInvocation commandInvocation) throws CommandException, InterruptedException { Shell shell = commandInvocation.getShell(); if (manPages == null || manPages.size() == 0) { shell.writeln("Call `help <command>` where command is one of:"); List<TerminalString> commandNames = ((ContextAwareCommandInvocation) commandInvocation).getContext().getRegistry() .getAllCommandNames().stream().map(n -> new TerminalString(n)).collect(Collectors.toList()); //then we print out the completions shell.write(Parser.formatDisplayListTerminalString(commandNames, shell.size().getHeight(), shell.size().getWidth())); //then on the next line we write the line again shell.writeln(""); return CommandResult.SUCCESS; } if (manPages.size() <= 0) { shell.write("No manual entry for " + manPages.get(0) + Config.getLineSeparator()); return CommandResult.SUCCESS; } if (manProvider == null) { shell.write("No manual provider defined"); return CommandResult.SUCCESS; } InputStream inputStream = manProvider.getManualDocument(manPages.get(0)); if (inputStream != null) { setCommandInvocation(commandInvocation); try { fileParser.setInput(inputStream); afterAttach(); } catch (IOException ex) { throw new CommandException(ex); } } return CommandResult.SUCCESS; } }
3,968
36.443396
126
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Install.java
package org.infinispan.cli.commands; import static org.infinispan.cli.util.Utils.digest; import java.io.IOException; import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.List; import java.util.Locale; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.option.Arguments; import org.aesh.command.option.Option; import org.aesh.io.FileResource; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.impl.ExitCodeResultHandler; import org.infinispan.cli.logging.Messages; import org.infinispan.commons.maven.Artifact; import org.infinispan.commons.maven.MavenSettings; import org.infinispan.commons.util.Util; import org.kohsuke.MetaInfServices; /** * @since 14.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "install", description = "Downloads and installs artifacts into the lib folder of the server.", resultHandler = ExitCodeResultHandler.class) public class Install extends CliCommand { @Arguments(description = "Specifies one or more artifacts as URLs or Maven GAV coordinates.", required = true) List<String> artifacts; @Option(completer = FileOptionCompleter.class, description = "Sets the path to the server installation.", name = "server-home") FileResource serverHome; @Option(description = "Sets the server root directory relative to the server home.", name = "server-root", defaultValue = "server") String serverRoot = "server"; @Option(description = "Sets the path to a Maven settings file that resolves Maven artifacts. Can be either a local path or a URL.", name = "maven-settings") String mavenSettings; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Option(description = "Overwrites artifacts in the lib folder. By default installation fails if artifacts already exist.", shortName = 'o', hasValue = false) boolean overwrite; @Option(description = "Show verbose information about installation progress.", shortName = 'v', hasValue = false) boolean verbose; @Option(description = "Forces download of artifacts, ignoring any previously cached versions.", shortName = 'f', hasValue = false) boolean force; @Option(description = "Number of download retries in case artifacts do not match the supplied checksums.", shortName = 'r', defaultValue = "0") int retries; @Option(description = "Deletes all contents from the lib directory before downloading artifacts.", hasValue = false) boolean clean; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { try { StandardCopyOption[] options = overwrite ? new StandardCopyOption[]{StandardCopyOption.REPLACE_EXISTING} : new StandardCopyOption[]{}; MavenSettings.init(mavenSettings == null ? null : Artifact.fromString(mavenSettings).resolveArtifact()); Path serverLib = CLI.getServerHome(serverHome).resolve(serverRoot).resolve("lib"); if (clean) { if (verbose) { System.out.printf("Removing all files from %s%n", serverLib); } Util.recursiveFileRemove(serverLib); Files.createDirectories(serverLib); } for (String artifact : artifacts) { String[] parts = artifact.split("\\|"); String path = parts[0]; Path resolved = null; for (int retry = 0; retry <= retries; retry++) { resolved = Artifact.fromString(path).verbose(verbose).force(retry != 0 || force).resolveArtifact(); if (resolved == null) { throw Messages.MSG.artifactNotFound(path); } if (parts.length > 1) { String checksum = parts.length == 3 ? parts[2].toUpperCase(Locale.ROOT) : parts[1].toUpperCase(Locale.ROOT); String algorithm = parts.length == 3 ? parts[1].toUpperCase(Locale.ROOT) : "SHA-256"; String computed = digest(resolved, algorithm); if (!computed.equals(checksum)) { if (retry < retries) { if (verbose) { System.err.printf("%s. %s%n", Messages.MSG.checksumFailed(path, checksum, computed).getMessage(), Messages.MSG.retryDownload(retry + 1, retries)); } } else { throw Messages.MSG.checksumFailed(path, checksum, computed); } } else if (verbose) { System.out.println(Messages.MSG.checksumVerified(path)); break; } } else { break; } } String resolvedFilename = resolved.getFileName().toString(); if (resolvedFilename.endsWith(".zip")) { extractZip(resolved, serverLib, options); } else if (resolvedFilename.endsWith(".tgz") || resolvedFilename.endsWith(".tar.gz")) { extractTgz(resolved, serverLib, options); } else if (resolvedFilename.endsWith(".tar")) { extractTar(resolved, serverLib, options); } else { Files.copy(resolved, serverLib.resolve(resolved.getFileName()), options); } } return CommandResult.SUCCESS; } catch (IOException e) { throw new CommandException(e); } } private static void extractZip(Path zip, Path dest, CopyOption... options) throws IOException { try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(zip))) { for (ZipEntry zipEntry = zis.getNextEntry(); zipEntry != null; zipEntry = zis.getNextEntry()) { Path entryPath = dest.resolve(zipEntry.getName()); if (!entryPath.startsWith(dest)) { throw new IOException("Illegal relative path " + zipEntry.getName()); } if (zipEntry.isDirectory()) { Files.createDirectories(entryPath); } else { Files.createDirectories(entryPath.getParent()); Files.copy(zis, entryPath, options); } zis.closeEntry(); } } } private static void extractTgz(Path tar, Path dest, CopyOption... options) throws IOException { try (TarArchiveInputStream tis = new TarArchiveInputStream(new GZIPInputStream(Files.newInputStream(tar)))) { extractTarEntries(dest, tis, options); } } private static void extractTar(Path tar, Path dest, CopyOption... options) throws IOException { try (TarArchiveInputStream tis = new TarArchiveInputStream(Files.newInputStream(tar))) { extractTarEntries(dest, tis, options); } } private static void extractTarEntries(Path dest, TarArchiveInputStream tis, CopyOption... options) throws IOException { for (TarArchiveEntry tarEntry = tis.getNextTarEntry(); tarEntry != null; tarEntry = tis.getNextTarEntry()) { Path entryPath = dest.resolve(tarEntry.getName()); if (!entryPath.startsWith(dest)) { throw new IOException("Illegal relative path " + tarEntry.getName()); } if (tarEntry.isDirectory()) { Files.createDirectories(entryPath); } else { Files.createDirectories(entryPath.getParent()); Files.copy(tis, entryPath, options); } } } }
8,025
43.588889
173
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Clear.java
package org.infinispan.cli.commands; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.option.Option; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "clear", description = "Clears the screen", aliases = "cls") public class Clear extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { invocation.getShell().clear(); return CommandResult.SUCCESS; } }
865
26.0625
86
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Cache.java
package org.infinispan.cli.commands; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.CachesResource; import org.infinispan.cli.resources.ContainerResource; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "cache", description = "Selects a cache", activator = ConnectionActivator.class) public class Cache extends CliCommand { @Argument(description = "The name of the cache", completer = CacheCompleter.class, required = true) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { return invocation.getContext().changeResource(ContainerResource.class, CachesResource.NAME, name); } }
1,362
33.075
106
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Config.java
package org.infinispan.cli.commands; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.option.Argument; import org.aesh.command.option.Arguments; import org.aesh.command.option.Option; import org.aesh.io.Resource; import org.infinispan.cli.Context; import org.infinispan.cli.activators.ConfigConversionAvailable; import org.infinispan.cli.completers.ConfigPropertyCompleter; import org.infinispan.cli.completers.MediaTypeCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.logging.Messages; import org.infinispan.commons.configuration.io.ConfigurationResourceResolver; import org.infinispan.commons.configuration.io.ConfigurationResourceResolvers; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.configuration.io.URLConfigurationResourceResolver; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "config", description = "Configuration operations", groupCommands = {Config.Set.class, Config.Get.class, Config.Reset.class, Config.Convert.class}) public class Config extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { Context context = invocation.getContext(); context.getProperties().forEach((k, v) -> invocation.printf("%s=%s\n", k, v)); return CommandResult.SUCCESS; } @CommandDefinition(name = "set", description = "Sets a configuration property") public static class Set extends CliCommand { @Arguments(description = "The property name and value", required = true, completer = ConfigPropertyCompleter.class) List<String> args; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { Context context = invocation.getContext(); switch (args.size()) { case 1: context.setProperty(args.get(0), null); break; case 2: context.setProperty(args.get(0), args.get(1)); break; default: throw Messages.MSG.wrongArgumentCount(args.size()); } context.saveProperties(); return CommandResult.SUCCESS; } } @CommandDefinition(name = "get", description = "Gets a configuration property") public static class Get extends CliCommand { @Argument(description = "The name of the property", required = true, completer = ConfigPropertyCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { Context context = invocation.getContext(); invocation.printf("%s=%s\n", name, context.getProperty(name)); return CommandResult.SUCCESS; } } @CommandDefinition(name = "reset", description = "Resets all configuration properties to their default values") public static class Reset extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { Context context = invocation.getContext(); context.resetProperties(); context.saveProperties(); return CommandResult.SUCCESS; } } @CommandDefinition(name = "convert", description = "Converts configuration to different formats.", activator = ConfigConversionAvailable.class) public static class Convert extends CliCommand { @Argument(description = "Specifies the path to a configuration file to convert. Uses standard input (stdin) if you do not specify a path.", completer = FileOptionCompleter.class) Resource input; @Option(description = "Specifies the path to the output configuration file. Uses standard output (stdout) if you do not specify a path.", completer = FileOptionCompleter.class, shortName = 'o') Resource output; @Option(description = "Sets the format of the output configuration.", required = true, completer = MediaTypeCompleter.class, shortName = 'f') String format; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { InputStream is = null; OutputStream os = null; ConfigurationResourceResolver resolver; try { ParserRegistry registry = new ParserRegistry(); if (input == null) { is = System.in; resolver = ConfigurationResourceResolvers.DEFAULT; } else { File file = new File(input.getAbsolutePath()); is = new FileInputStream(file); resolver = new URLConfigurationResourceResolver(file.toURI().toURL()); } ConfigurationBuilderHolder holder = registry.parse(is, resolver, null); // Auto-detect type os = output == null ? System.out : new FileOutputStream(output.getAbsolutePath()); Map<String, Configuration> configurations = new HashMap<>(); for (Map.Entry<String, ConfigurationBuilder> configuration : holder.getNamedConfigurationBuilders().entrySet()) { configurations.put(configuration.getKey(), configuration.getValue().build()); } MediaType mediaType; switch (MediaTypeCompleter.MediaType.valueOf(format.toUpperCase(Locale.ROOT))) { case XML: mediaType = MediaType.APPLICATION_XML; break; case YAML: mediaType = MediaType.APPLICATION_YAML; break; case JSON: mediaType = MediaType.APPLICATION_JSON; break; default: throw new CommandException("Invalid output format: " + format); } try (ConfigurationWriter writer = ConfigurationWriter.to(os).withType(mediaType).clearTextSecrets(true).prettyPrint(true).build()) { registry.serialize(writer, holder.getGlobalConfigurationBuilder().build(), configurations); } return CommandResult.SUCCESS; } catch (FileNotFoundException | MalformedURLException e) { throw new CommandException(e); } finally { if (input != null) { Util.close(is); } if (output != null) { Util.close(os); } } } } }
8,271
38.018868
199
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Container.java
package org.infinispan.cli.commands; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.ContainerCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.ContainersResource; import org.infinispan.cli.resources.RootResource; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "container", description = "Selects a container", activator = ConnectionActivator.class) public class Container extends CliCommand { @Argument(description = "The name of the container", completer = ContainerCompleter.class, required = true) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { return invocation.getContext().changeResource(RootResource.class, ContainersResource.NAME, name); } }
1,384
33.625
114
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Encoding.java
package org.infinispan.cli.commands; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.completers.EncodingCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.commons.dataconversion.MediaType; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "encoding", description = "Gets/sets the current encoding") public class Encoding extends CliCommand { @Argument(completer = EncodingCompleter.class) String encoding; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { if (encoding != null) { invocation.getContext().setEncoding(MediaType.fromString(encoding)); } else { invocation.println(invocation.getContext().getEncoding().toString()); } return CommandResult.SUCCESS; } }
1,264
29.119048
85
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/User.java
package org.infinispan.cli.commands; import static org.infinispan.cli.logging.Messages.MSG; import java.util.List; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.aesh.command.option.OptionList; import org.infinispan.cli.commands.rest.Roles; import org.infinispan.cli.completers.EncryptionAlgorithmCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.user.UserTool; import org.infinispan.commons.dataconversion.internal.Json; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "user", description = "User operations", groupCommands = {User.Create.class, User.Describe.class, User.Remove.class, User.Password.class, User.Groups.class, User.Ls.class, User.Encrypt.class, Roles.class}) public class User extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "create", description = "Creates a user", aliases = "add") public static class Create extends CliCommand { @Argument(description = "The username for the user") String username; @Option(description = "The password for the user", shortName = 'p') String password; @Option(description = "The realm ", defaultValue = UserTool.DEFAULT_REALM_NAME, shortName = 'r') String realm; @OptionList(description = "The algorithms used to encrypt the password", shortName = 'a', completer = EncryptionAlgorithmCompleter.class) List<String> algorithms; @OptionList(description = "The groups the user should belong to", shortName = 'g') List<String> groups; @Option(description = "Whether the password should be stored in plain text (not recommended)", name = "plain-text", hasValue = false) boolean plainText; @Option(description = "The path of the users.properties file", name = "users-file", shortName = 'f') String usersFile; @Option(description = "The path of the groups.properties file", name = "groups-file", shortName = 'w') String groupsFile; @Option(description = "The server root", defaultValue = "server", name = "server-root", shortName = 's') String serverRoot; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { UserTool userTool = new UserTool(serverRoot, usersFile, groupsFile); try { while (username == null || username.isEmpty()) { username = invocation.getShell().readLine(MSG.userToolUsername()); } } catch (InterruptedException e) { return CommandResult.FAILURE; } if (password == null) { // Get the password interactively try { password = invocation.getPasswordInteractively(MSG.userToolPassword(), MSG.userToolPasswordConfirm()); } catch (InterruptedException e) { return CommandResult.FAILURE; } } userTool.createUser(username, password, realm, UserTool.Encryption.valueOf(plainText), groups, algorithms); return CommandResult.SUCCESS; } } @CommandDefinition(name = "describe", description = "Describes a user") public static class Describe extends CliCommand { @Argument(description = "The username for the user", required = true) String username; @Option(description = "The path of the users.properties file", name = "users-file", shortName = 'f') String usersFile; @Option(description = "The path of the groups.properties file", name = "groups-file", shortName = 'w') String groupsFile; @Option(description = "The server root", defaultValue = "server", name = "server-root", shortName = 's') String serverRoot; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { UserTool userTool = new UserTool(serverRoot, usersFile, groupsFile); invocation.getShell().writeln(userTool.describeUser(username)); return CommandResult.SUCCESS; } } @CommandDefinition(name = "remove", description = "Removes a user", aliases = "rm") public static class Remove extends CliCommand { @Argument(description = "The username for the user", required = true) String username; @Option(description = "The path of the users.properties file", name = "users-file", shortName = 'f') String usersFile; @Option(description = "The path of the groups.properties file", name = "groups-file", shortName = 'w') String groupsFile; @Option(description = "The server root", defaultValue = "server", name = "server-root", shortName = 's') String serverRoot; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { UserTool userTool = new UserTool(serverRoot, usersFile, groupsFile); userTool.removeUser(username); return CommandResult.SUCCESS; } } @CommandDefinition(name = "password", description = "Changes a user's password") public static class Password extends CliCommand { @Argument(description = "The username for the user", required = true) String username; @Option(description = "The password for the user", shortName = 'p') String password; @Option(description = "The realm ", defaultValue = UserTool.DEFAULT_REALM_NAME, shortName = 'r') String realm; @OptionList(description = "The algorithms used to encrypt the password", shortName = 'a', completer = EncryptionAlgorithmCompleter.class) List<String> algorithms; @Option(description = "Whether the password should be stored in plain text", name = "plain-text", hasValue = false) boolean plainText; @Option(description = "The path of the users.properties file", name = "users-file", shortName = 'f') String usersFile; @Option(description = "The path of the groups.properties file", name = "groups-file", shortName = 'w') String groupsFile; @Option(description = "The server root", defaultValue = "server", name = "server-root", shortName = 's') String serverRoot; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { if (password == null) { // Get the password interactively try { password = invocation.getPasswordInteractively(MSG.userToolPassword(), MSG.userToolPasswordConfirm()); } catch (InterruptedException e) { return CommandResult.FAILURE; } } UserTool userTool = new UserTool(serverRoot, usersFile, groupsFile); userTool.modifyUser(username, password, realm, UserTool.Encryption.valueOf(plainText), null, algorithms); return CommandResult.SUCCESS; } } @CommandDefinition(name = "groups", description = "Sets a user's groups") public static class Groups extends CliCommand { @Argument(description = "The username for the user", required = true) String username; @OptionList(description = "The groups the user should belong to", shortName = 'g', required = true) List<String> groups; @Option(description = "The path of the users.properties file", name = "users-file", shortName = 'f') String usersFile; @Option(description = "The path of the groups.properties file", name = "groups-file", shortName = 'w') String groupsFile; @Option(description = "The server root", defaultValue = "server", name = "server-root", shortName = 's') String serverRoot; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { UserTool userTool = new UserTool(serverRoot, usersFile, groupsFile); userTool.modifyUser(username, null, null, UserTool.Encryption.DEFAULT, groups, null); return CommandResult.SUCCESS; } } @CommandDefinition(name = "ls", description = "Lists all users/groups") public static class Ls extends CliCommand { @Option(description = "Whether to list all unique groups instead of users", shortName = 'g', hasValue = false) boolean groups; @Option(description = "The path of the users.properties file", name = "users-file", shortName = 'f') String usersFile; @Option(description = "The path of the groups.properties file", name = "groups-file", shortName = 'w') String groupsFile; @Option(description = "The server root", defaultValue = "server", name = "server-root", shortName = 's') String serverRoot; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { UserTool userTool = new UserTool(serverRoot, usersFile, groupsFile); List<String> items; if (groups) { items = userTool.listGroups(); } else { items = userTool.listUsers(); } invocation.getShell().writeln(Json.make(items).toString()); return CommandResult.SUCCESS; } } @CommandDefinition(name = "encrypt-all", description = "Encrypts all of the passwords in a property file.") public static class Encrypt extends CliCommand { @Option(description = "The path of the users.properties file", name = "users-file", shortName = 'f') String usersFile; @Option(description = "The path of the groups.properties file", name = "groups-file", shortName = 'w') String groupsFile; @Option(description = "The server root", defaultValue = "server", name = "server-root", shortName = 's') String serverRoot; @OptionList(description = "The algorithms used to encrypt the password", shortName = 'a', completer = EncryptionAlgorithmCompleter.class) List<String> algorithms; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { UserTool userTool = new UserTool(serverRoot, usersFile, groupsFile); userTool.encryptAll(algorithms); return CommandResult.SUCCESS; } } }
12,104
36.71028
236
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Shutdown.java
package org.infinispan.cli.commands.rest; import java.util.List; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Arguments; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.ServerCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "shutdown", description = "Stops server instances and clusters.", activator = ConnectionActivator.class, groupCommands = {Shutdown.Server.class, Shutdown.Cluster.class, Shutdown.Container.class}) public class Shutdown extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "server", description = "Stops one or more server instances.", activator = ConnectionActivator.class) public static class Server extends RestCliCommand { @Arguments(description = "Specifies server instances to stop.", completer = ServerCompleter.class) List<String> servers; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return servers == null || servers.isEmpty() ? client.server().stop() : client.cluster().stop(servers); } } @CommandDefinition(name = "cluster", description = "Stops all nodes in the cluster after storing cluster state and persisting entries if there is a cache store.", activator = ConnectionActivator.class) public static class Cluster extends RestCliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cluster().stop(); } } @CommandDefinition(name = "container", description = "Stops the data container without terminating the server process.", activator = ConnectionActivator.class) public static class Container extends RestCliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.container().shutdown(); } } }
3,591
35.653061
226
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Logging.java
package org.infinispan.cli.commands.rest; import java.util.List; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.aesh.command.option.OptionList; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.LogAppenderCompleter; import org.infinispan.cli.completers.LogLevelCompleter; import org.infinispan.cli.completers.LoggersCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "logging", description = "Inspects/Manipulates the server logging configuration", activator = ConnectionActivator.class, groupCommands = {Logging.Loggers.class, Logging.Appenders.class, Logging.Set.class, Logging.Remove.class}) public class Logging extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "list-loggers", description = "Lists available loggers", activator = ConnectionActivator.class) public static class Loggers extends RestCliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.server().logging().listLoggers(); } } @CommandDefinition(name = "list-appenders", description = "Lists available appenders", activator = ConnectionActivator.class) public static class Appenders extends RestCliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.server().logging().listAppenders(); } } @CommandDefinition(name = "remove", description = "Removes a logger", activator = ConnectionActivator.class) public static class Remove extends RestCliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Argument(required = true, completer = LoggersCompleter.class) String name; @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.server().logging().removeLogger(name); } } @CommandDefinition(name = "set", description = "Sets a logger", activator = ConnectionActivator.class) public static class Set extends RestCliCommand { @Argument(completer = LoggersCompleter.class) String name; @Option(shortName = 'l', description = "One of OFF, TRACE, DEBUG, INFO, WARN, ERROR, FATAL, ALL", completer = LogLevelCompleter.class) String level; @OptionList(shortName = 'a', description = "One or more appender names", completer = LogAppenderCompleter.class) List<String> appenders; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { String[] appendersArray = appenders != null ? appenders.toArray(new String[0]) : null; return client.server().logging().setLogger(name, level, appendersArray); } } }
4,648
35.320313
258
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Schema.java
package org.infinispan.cli.commands.rest; import java.io.File; import java.nio.file.NoSuchFileException; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.aesh.io.Resource; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.SchemaCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.logging.Messages; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.MediaType; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "schema", description = "Manipulates Protobuf schemas", activator = ConnectionActivator.class, groupCommands = {Schema.Upload.class, Schema.Remove.class, Schema.Ls.class, Schema.Get.class}) public class Schema extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "upload", description = "Uploads Protobuf schemas to the server.") public static class Upload extends RestCliCommand { @Argument(required = true, description = "The name of the schema") String name; @Option(completer = FileOptionCompleter.class, shortName = 'f', description = "The Protobuf schema file to upload.", required = true) Resource file; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) throws NoSuchFileException { if (file.exists()) { return client.schemas().put(name, RestEntity.create(MediaType.TEXT_PLAIN, new File(file.getAbsolutePath()))); } else { throw Messages.MSG.nonExistentFile(file); } } } @CommandDefinition(name = "ls", description = "Lists available Protobuf schemas.") public static class Ls extends RestCliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) { return client.schemas().names(); } } @CommandDefinition(name = "remove", aliases = "rm", description = "Deletes Protobuf schema.") public static class Remove extends RestCliCommand { @Argument(required = true, description = "The name of the schema", completer = SchemaCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) { return client.schemas().delete(name); } } @CommandDefinition(name = "get", description = "Displays the Protobuf definition of a schema.") public static class Get extends RestCliCommand { @Argument(required = true, description = "The name of the schema", completer = SchemaCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) { return client.schemas().get(name); } } }
4,765
36.234375
220
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Drop.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.completers.CounterCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "drop", description = "Drops a cache or a counter", activator = ConnectionActivator.class, groupCommands = {Drop.Cache.class, Drop.Counter.class}) public class Drop extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "cache", description = "Drop a cache", activator = ConnectionActivator.class) public static class Cache extends RestCliCommand { @Argument(required = true, completer = CacheCompleter.class, description = "The cache name") String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(name).delete(); } } @CommandDefinition(name = "counter", description = "Drop a counter", activator = ConnectionActivator.class) public static class Counter extends RestCliCommand { @Argument(required = true, completer = CounterCompleter.class, description = "The counter name") String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.counter(name).delete(); } } }
2,880
33.297619
177
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Migrate.java
package org.infinispan.cli.commands.rest; import java.io.File; import java.io.FileReader; import java.util.Map; import java.util.Properties; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.option.Option; import org.aesh.command.option.OptionGroup; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.converters.NullableIntegerConverter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.impl.StoreMigratorHelper; import org.infinispan.cli.logging.Messages; import org.infinispan.cli.resources.CacheResource; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "migrate", description = "Migration operations", groupCommands = {Migrate.Store.class, Migrate.Cluster.class}) public class Migrate extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "store", description = "Migrates store data") public static class Store extends CliCommand { @OptionGroup(shortName = 'P', description = "Sets a migration property") Map<String, String> propertyMap; @Option(completer = FileOptionCompleter.class, shortName = 'p', name = "properties", description = "Migration configuration properties") org.aesh.io.Resource propertiesFile; @Option(shortName = 'v', hasValue = false) boolean verbose; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { Properties props = new Properties(); try { if (propertiesFile != null) { props.load(new FileReader(this.propertiesFile.getAbsolutePath())); } props.putAll(propertyMap); if (props.isEmpty()) { throw Messages.MSG.missingStoreMigratorProperties(); } StoreMigratorHelper.run(props, verbose); return CommandResult.SUCCESS; } catch (Exception e) { throw new CommandException(e); } } } @GroupCommandDefinition(name = "cluster", description = "Performs data migration between clusters", groupCommands = {Migrate.ClusterConnect.class, Migrate.ClusterDisconnect.class, Migrate.ClusterSourceConnection.class, Migrate.ClusterSynchronize.class}, activator = ConnectionActivator.class) public static class Cluster extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } } @CommandDefinition(name = "connect", description = "Connects to a source cluster") public static class ClusterConnect extends RestCliCommand { @Option(completer = CacheCompleter.class, shortName = 'c', description = "The name of the cache.") String cache; @Option(completer = FileOptionCompleter.class, shortName = 'f', description = "JSON containing a 'remote-store' element with the configuration") org.aesh.io.Resource file; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { if (file == null) { throw Messages.MSG.illegalCommandArguments(); } RestEntity restEntity = RestEntity.create(new File(file.getAbsolutePath())); return client.cache(cache != null ? cache : CacheResource.cacheName(resource)).connectSource(restEntity); } } @CommandDefinition(name = "disconnect", description = "Disconnects from a source cluster") public static class ClusterDisconnect extends RestCliCommand { @Option(completer = CacheCompleter.class, shortName = 'c', description = "The name of the cache.") String cache; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache != null ? cache : CacheResource.cacheName(resource)).disconnectSource(); } } @CommandDefinition(name = "source-connection", description = "Obtains the remote store configuration if a cache is connected to another cluster") public static class ClusterSourceConnection extends RestCliCommand { @Option(completer = CacheCompleter.class, shortName = 'c', description = "The name of the cache.") String cache; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache != null ? cache : CacheResource.cacheName(resource)).sourceConnection(); } } @CommandDefinition(name = "synchronize", description = "Synchronizes data from a source to a target cluster") public static class ClusterSynchronize extends RestCliCommand { @Option(completer = CacheCompleter.class, shortName = 'c') String cache; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Option(shortName = 'b', name = "read-batch", description = "The amount of entries to process in a batch", converter = NullableIntegerConverter.class) Integer readBatch; @Option(shortName = 't', description = "The number of threads to use. Defaults to the number of cores on the server", converter = NullableIntegerConverter.class) Integer threads; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache != null ? cache : CacheResource.cacheName(resource)).synchronizeData(readBatch, threads); } } }
7,813
37.303922
295
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Put.java
package org.infinispan.cli.commands.rest; import java.io.File; import java.util.List; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.option.Arguments; import org.aesh.command.option.Option; import org.aesh.io.Resource; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.completers.EncodingCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.logging.Messages; import org.infinispan.cli.resources.CacheResource; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.MediaType; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "put", description = "Puts an entry into the cache", activator = ConnectionActivator.class) public class Put extends RestCliCommand { @Arguments(required = true) List<String> args; @Option(completer = EncodingCompleter.class, shortName = 'e') String encoding; @Option(completer = CacheCompleter.class, shortName = 'c') String cache; @Option(completer = FileOptionCompleter.class, shortName = 'f') Resource file; @Option(shortName = 'l', defaultValue = "0") long ttl; @Option(name = "max-idle", shortName = 'i', defaultValue = "0") long maxIdle; @Option(name = "if-absent", shortName = 'a') boolean ifAbsent; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) { if ((file != null) && (args.size() != 1)) { throw Messages.MSG.illegalCommandArguments(); } else if ((file == null) && (args.size() != 2)) { throw Messages.MSG.illegalCommandArguments(); } RestCacheClient cacheClient = client.cache(cache != null ? cache : CacheResource.cacheName(resource)); MediaType putEncoding = encoding != null ? MediaType.fromString(encoding) : invocation.getContext().getEncoding(); RestEntity value = file != null ? RestEntity.create(putEncoding, new File(file.getAbsolutePath())) : RestEntity.create(putEncoding, args.get(1)); if (ifAbsent) { return cacheClient.post(args.get(0), value, ttl, maxIdle); } else { return cacheClient.put(args.get(0), value, ttl, maxIdle); } } }
2,918
35.037037
158
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/AclCache.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; /** * @since 15.0 **/ @GroupCommandDefinition(name = AclCache.CMD, description = "Performs operations on principals", activator = ConnectionActivator.class, groupCommands = {AclCache.Flush.class}) public class AclCache extends CliCommand { public static final String CMD = "aclcache"; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "flush", description = "Flushes the ACL cache across the entire cluster", activator = ConnectionActivator.class) public static class Flush extends RestCliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.security().flushCache(); } } }
1,856
32.160714
174
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Add.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.impl.completer.BooleanOptionCompleter; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.CounterCompleter; import org.infinispan.cli.connection.Connection; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.CounterResource; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "add", description = "Adds/subtracts a value to/from a counter", activator = ConnectionActivator.class) public class Add extends RestCliCommand { @Argument(completer = CounterCompleter.class, description = "The name of the counter") String counter; @Option(description = "Does not display the value", completer = BooleanOptionCompleter.class) boolean quiet; @Option(description = "The delta to add/subtract from/to the value. Defaults to adding 1", defaultValue = "1") long delta; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.counter(counter != null ? counter : CounterResource.counterName(resource)).add(delta); } @Override public Connection.ResponseMode getResponseMode() { return quiet ? Connection.ResponseMode.QUIET : Connection.ResponseMode.BODY; } }
1,984
35.090909
129
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Query.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.CacheResource; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "query", description = "Queries a cache", activator = ConnectionActivator.class) public class Query extends RestCliCommand { @Argument(required = true, description = "The Ickle query") String query; @Option(completer = CacheCompleter.class) String cache; @Option(name = "max-results", defaultValue = "10") Integer maxResults; @Option(name = "offset", defaultValue = "0") Integer offset; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache != null ? cache : CacheResource.cacheName(resource)).query(query, maxResults, offset); } }
1,637
31.117647
129
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Create.java
package org.infinispan.cli.commands.rest; import java.io.File; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.aesh.command.parser.RequiredOptionException; import org.aesh.io.Resource; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.CacheConfigurationCompleter; import org.infinispan.cli.completers.CounterStorageCompleter; import org.infinispan.cli.completers.CounterTypeCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.logging.Messages; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "create", description = "Creates a cache or a counter", activator = ConnectionActivator.class, groupCommands = {Create.Cache.class, Create.Counter.class}) public class Create extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "cache", description = "Create a cache", activator = ConnectionActivator.class) public static class Cache extends RestCliCommand { @Argument(required = true) String name; @Option(completer = CacheConfigurationCompleter.class, shortName = 't') String template; @Option(completer = FileOptionCompleter.class, shortName = 'f') Resource file; @Option(defaultValue = "false", name = "volatile", shortName = 'v') boolean volatileCache; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) throws RequiredOptionException { if (template != null && file != null) { throw Messages.MSG.mutuallyExclusiveOptions("template", "file"); } if (template == null && file == null) { throw Messages.MSG.requiresOneOf("template", "file"); } RestCacheClient cache = client.cache(name); CacheContainerAdmin.AdminFlag flags[] = volatileCache ? new CacheContainerAdmin.AdminFlag[]{CacheContainerAdmin.AdminFlag.VOLATILE} : new CacheContainerAdmin.AdminFlag[]{}; if (template != null) { return cache.createWithTemplate(template, flags); } else { return cache.createWithConfiguration(RestEntity.create(new File(file.getAbsolutePath())), flags); } } } @CommandDefinition(name = "counter", description = "Create a counter", activator = ConnectionActivator.class) public static class Counter extends RestCliCommand { @Argument(required = true) String name; @Option(shortName = 't', defaultValue = "", completer = CounterTypeCompleter.class, description = "Type of counter [weak|strong]") String type; @Option(shortName = 'i', name = "initial-value", defaultValue = "0", description = "Initial value for the counter (defaults to 0)") Long initialValue; @Option(shortName = 's', defaultValue = "VOLATILE", completer = CounterStorageCompleter.class, description = "persistent state PERSISTENT | VOLATILE (default)") String storage; @Option(shortName = 'u', name = "upper-bound") Long upperBound; @Option(shortName = 'l', name = "lower-bound") Long lowerBound; @Option(shortName = 'c', name = "concurrency-level", defaultValue = "16", description = "concurrency level for weak counters, defaults to 16") Integer concurrencyLevel; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) { Json counterBody = Json.object() .set("initial-value", initialValue) .set("storage", storage) .set("name", name); if ("weak".equals(type)) { counterBody.set("concurrency-level", concurrencyLevel); } if (upperBound != null) { counterBody.set("upper-bound", upperBound); } if (lowerBound != null) { counterBody.set("lower-bound", lowerBound); } Json counter = Json.object().set(type + "-counter", counterBody); return client.counter(name).create(RestEntity.create(MediaType.APPLICATION_JSON, counter.toString())); } } }
5,818
38.317568
192
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Availability.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.AvailabilityCompleter; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.CacheResource; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * Manage a cache's Availability. * * @author Ryan Emerson * @since 13.0 */ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "availability", description = "Manage availability of clustered caches in network partitions.", activator = ConnectionActivator.class) public class Availability extends RestCliCommand { @Argument(completer = CacheCompleter.class) String cache; @Option(shortName = 'm', completer = AvailabilityCompleter.class) String mode; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) { RestCacheClient cacheClient = client.cache(cache != null ? cache : CacheResource.cacheName(resource)); return mode == null ? cacheClient.getAvailability() : cacheClient.setAvailability(AvailabilityCompleter.Availability.valueOf(mode).toString()); } }
1,829
34.882353
165
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/ClearCache.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.CacheResource; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "clearcache", description = "Clears the cache", activator = ConnectionActivator.class) public class ClearCache extends RestCliCommand { @Argument(description = "The name of the cache", completer = CacheCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(name != null ? name : CacheResource.cacheName(resource)).clear(); } }
1,434
33.166667
129
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Alter.java
package org.infinispan.cli.commands.rest; import java.io.File; import java.util.Optional; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.aesh.command.parser.RequiredOptionException; import org.aesh.io.Resource; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CacheAwareCommand; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.completers.CacheConfigurationAttributeCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.logging.Messages; import org.infinispan.cli.resources.CacheResource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 13.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "alter", description = "Alters a configuration", activator = ConnectionActivator.class, groupCommands = {Alter.Cache.class}) public class Alter extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "cache", description = "Alters a cache configuration", activator = ConnectionActivator.class) public static class Cache extends RestCliCommand implements CacheAwareCommand { @Argument(completer = CacheCompleter.class, description = "The cache name") String name; @Option(description = "The configuration attribute", completer = CacheConfigurationAttributeCompleter.class) String attribute; @Option(description = "The value for the configuration attribute") String value; @Option(completer = FileOptionCompleter.class, shortName = 'f') Resource file; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) throws RequiredOptionException { if (attribute != null && file != null) { throw Messages.MSG.mutuallyExclusiveOptions("attribute", "file"); } if (attribute == null && file == null) { throw Messages.MSG.requiresOneOf("attribute", "file"); } if (attribute != null && value == null) { throw Messages.MSG.requiresAllOf("attribute", "value"); } String n = getCacheName(resource).orElseThrow(() -> Messages.MSG.missingCacheName()); if (file != null) { return client.cache(n).updateWithConfiguration(RestEntity.create(new File(file.getAbsolutePath()))); } else { return client.cache(n).updateConfigurationAttribute(attribute, value); } } @Override public Optional<String> getCacheName(org.infinispan.cli.resources.Resource activeResource) { return name == null ? CacheResource.findCacheName(activeResource) : Optional.of(name); } } }
3,871
37.72
192
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Roles.java
package org.infinispan.cli.commands.rest; import java.util.List; import java.util.concurrent.CompletionStage; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.aesh.command.option.OptionList; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.AuthorizationPermissionCompleter; import org.infinispan.cli.completers.RolesCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.1 **/ @GroupCommandDefinition(name = "roles", description = "Manages user roles for security authorization", activator = ConnectionActivator.class, groupCommands = {Roles.Ls.class, Roles.Grant.class, Roles.Deny.class, Roles.Create.class, Roles.Remove.class, Roles.Describe.class}) public class Roles extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation commandInvocation) { commandInvocation.println(commandInvocation.getHelpInfo()); return CommandResult.SUCCESS; } @CommandDefinition(name = "ls", description = "Lists roles assigned to principals") public static class Ls extends RestCliCommand { @Argument(description = "The principal for which the roles should be listed. If unspecified all available roles are listed.") String principal; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override protected boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.security().listRoles(principal); } } @CommandDefinition(name = "grant", description = "Grants roles to principals") public static class Grant extends RestCliCommand { @Argument(description = "The principal to which the roles should be granted", required = true) String principal; @OptionList(shortName = 'r', required = true, completer = RolesCompleter.class) List<String> roles; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override protected boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.security().grant(principal, roles); } } @CommandDefinition(name = "deny", description = "Denies roles to principals") public static class Deny extends RestCliCommand { @Argument(description = "The principal to which the roles should be denied", required = true) String principal; @OptionList(shortName = 'r', required = true, completer = RolesCompleter.class) List<String> roles; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override protected boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.security().deny(principal, roles); } } @CommandDefinition(name = "create", description = "Creates a new role") public static class Create extends RestCliCommand { @Argument(description = "Provides a name for the new role", required = true) String name; @OptionList(shortName = 'p', required = true, completer = AuthorizationPermissionCompleter.class) List<String> permissions; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override protected boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.security().createRole(name, permissions); } } @CommandDefinition(name = "remove", aliases = {"rm"}, description = "Deletes an existing role.") public static class Remove extends RestCliCommand { @Argument(description = "Specifies the role to delete.", required = true, completer = RolesCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override protected boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.security().removeRole(name); } } @CommandDefinition(name = "describe", description = "Describes a role") public static class Describe extends RestCliCommand { @Argument(description = "Specifies the role to describe.", required = true, completer = RolesCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override protected boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.security().describeRole(name); } } }
5,982
33.988304
274
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Principals.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; /** * @since 15.0 **/ @GroupCommandDefinition(name = Principals.CMD, description = "Performs operations on principals", activator = ConnectionActivator.class, groupCommands = {Principals.Ls.class}) public class Principals extends CliCommand { public static final String CMD = "principals"; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "ls", description = "Lists principals", activator = ConnectionActivator.class) public static class Ls extends RestCliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.security().listPrincipals(); } } }
1,828
31.660714
175
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Task.java
package org.infinispan.cli.commands.rest; import java.io.File; import java.util.Collections; import java.util.Map; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.aesh.command.option.OptionGroup; import org.aesh.io.Resource; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.TaskCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.MediaType; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.1 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "task", description = "Executes or manipulates server-side tasks", activator = ConnectionActivator.class, groupCommands = {Task.Exec.class, Task.Upload.class}) public class Task extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "exec", description = "Executes a server-side task", activator = ConnectionActivator.class) public static class Exec extends RestCliCommand { @Argument(completer = TaskCompleter.class, required = true) String taskName; @OptionGroup(shortName = 'P', description = "Task parameters") Map<String, String> parameters; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) { return client.tasks().exec(taskName, parameters == null ? Collections.emptyMap() : parameters); } } @CommandDefinition(name = "upload", description = "Uploads a new script task to the server", activator = ConnectionActivator.class) public static class Upload extends RestCliCommand { @Argument(description = "The task name", required = true) String taskName; @Option(completer = FileOptionCompleter.class, shortName = 'f', required = true) Resource file; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) { return client.tasks().uploadScript(taskName, RestEntity.create(MediaType.TEXT_PLAIN, new File(file.getAbsolutePath()))); } } }
3,486
36.494624
190
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Cas.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.impl.completer.BooleanOptionCompleter; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.CounterCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.CounterResource; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestCounterClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "cas", description = "Compares and sets counter values", activator = ConnectionActivator.class) public class Cas extends RestCliCommand { @Argument(completer = CounterCompleter.class) String counter; @Option(description = "Does not display the value", completer = BooleanOptionCompleter.class) boolean quiet; @Option(required = true, description = "The expected value") long expect; @Option(required = true, description = "The new value") long value; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { RestCounterClient cc = counter != null ? client.counter(counter) : client.counter(CounterResource.counterName(resource)); if (quiet) { return cc.compareAndSet(expect, value); } else { return cc.compareAndSwap(expect, value); } } }
1,971
33
129
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Site.java
package org.infinispan.cli.commands.rest; import static org.infinispan.cli.logging.Messages.MSG; import java.io.IOException; import java.util.Optional; import java.util.concurrent.CompletionStage; import java.util.function.Supplier; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Option; import org.aesh.command.parser.RequiredOptionException; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CacheAwareCommand; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.completers.SiteCompleter; import org.infinispan.cli.completers.XSiteStateTransferModeCompleter; import org.infinispan.cli.connection.Connection; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.CacheResource; import org.infinispan.cli.resources.ContainerResource; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestCacheManagerClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.configuration.cache.XSiteStateTransferMode; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "site", description = "Manages backup sites", activator = ConnectionActivator.class, groupCommands = { Site.Status.class, Site.BringOnline.class, Site.TakeOffline.class, Site.PushSiteState.class, Site.CancelPushState.class, Site.CancelReceiveState.class, Site.PushSiteStatus.class, Site.ClearPushStateStatus.class, Site.View.class, Site.Name.class, Site.StateTransferMode.class, Site.IsRelayNode.class, Site.RelayNodes.class } ) public class Site extends CliCommand { private static final Supplier<RequiredOptionException> MISSING_CACHE_OR_GLOBAL = () -> MSG.requiresOneOf("cache", "all-caches"); @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "status", description = "Shows site status", activator = ConnectionActivator.class) public static class Status extends RestCliCommand implements CacheAwareCommand { @Option(shortName = 'c', completer = CacheCompleter.class, description = "The cache name.") String cache; @Option(shortName = 'a', name = "all-caches", hasValue = false, description = "Invoke operation in all caches.") boolean allCaches; @Option(shortName = 's', completer = SiteCompleter.class, description = "The remote backup name.") String site; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) throws RequiredOptionException { checkMutualExclusiveCacheAndGlobal(cache, allCaches); if (allCaches) { RestCacheManagerClient cm = restCacheManagerClient(client, resource); return site == null ? cm.backupStatuses() : cm.backupStatus(site); } RestCacheClient c = restCacheClient(client, resource, cache); return site == null ? c.xsiteBackups() : c.backupStatus(site); } @Override public Optional<String> getCacheName(Resource activeResource) { return cache == null ? CacheResource.findCacheName(activeResource) : Optional.of(cache); } } @CommandDefinition(name = "bring-online", description = "Brings a site online", activator = ConnectionActivator.class) public static class BringOnline extends RestCliCommand implements CacheAwareCommand { @Option(shortName = 'c', completer = CacheCompleter.class, description = "The cache name.") String cache; @Option(shortName = 'a', name = "all-caches", hasValue = false, description = "Invoke operation in all caches.") boolean allCaches; @Option(required = true, shortName = 's', completer = SiteCompleter.class, description = "The remote backup name.") String site; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) throws RequiredOptionException { checkMutualExclusiveCacheAndGlobal(cache, allCaches); return allCaches ? restCacheManagerClient(client, resource).bringBackupOnline(site) : restCacheClient(client, resource, cache).bringSiteOnline(site); } @Override public Optional<String> getCacheName(Resource activeResource) { return cache == null ? CacheResource.findCacheName(activeResource) : Optional.of(cache); } } @CommandDefinition(name = "take-offline", description = "Takes a site offline", activator = ConnectionActivator.class) public static class TakeOffline extends RestCliCommand implements CacheAwareCommand { @Option(shortName = 'c', completer = CacheCompleter.class, description = "The cache name.") String cache; @Option(shortName = 'a', name = "all-caches", hasValue = false, description = "Invoke operation in all caches.") boolean allCaches; @Option(required = true, shortName = 's', completer = SiteCompleter.class, description = "The remote backup name.") String site; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) throws RequiredOptionException { checkMutualExclusiveCacheAndGlobal(cache, allCaches); return allCaches ? restCacheManagerClient(client, resource).takeOffline(site) : restCacheClient(client, resource, cache).takeSiteOffline(site); } @Override public Optional<String> getCacheName(Resource activeResource) { return cache == null ? CacheResource.findCacheName(activeResource) : Optional.of(cache); } } @CommandDefinition(name = "push-site-state", description = "Starts pushing state to a site", activator = ConnectionActivator.class) public static class PushSiteState extends RestCliCommand implements CacheAwareCommand { @Option(shortName = 'c', completer = CacheCompleter.class, description = "The cache name.") String cache; @Option(shortName = 'a', name = "all-caches", hasValue = false, description = "Invoke operation in all caches.") boolean allCaches; @Option(required = true, shortName = 's', completer = SiteCompleter.class, description = "The remote backup name.") String site; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) throws RequiredOptionException { checkMutualExclusiveCacheAndGlobal(cache, allCaches); return allCaches ? restCacheManagerClient(client, resource).pushSiteState(site) : restCacheClient(client, resource, cache).pushSiteState(site); } @Override public Optional<String> getCacheName(Resource activeResource) { return cache == null ? CacheResource.findCacheName(activeResource) : Optional.of(cache); } } @CommandDefinition(name = "cancel-push-state", description = "Cancels pushing state to a site", activator = ConnectionActivator.class) public static class CancelPushState extends RestCliCommand implements CacheAwareCommand { @Option(shortName = 'c', completer = CacheCompleter.class, description = "The cache name.") String cache; @Option(shortName = 'a', name = "all-caches", hasValue = false, description = "Invoke operation in all caches.") boolean allCaches; @Option(required = true, shortName = 's', completer = SiteCompleter.class, description = "The remote backup name.") String site; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) throws RequiredOptionException { checkMutualExclusiveCacheAndGlobal(cache, allCaches); return allCaches ? restCacheManagerClient(client, resource).cancelPushState(site) : restCacheClient(client, resource, cache).cancelPushState(site); } @Override public Optional<String> getCacheName(Resource activeResource) { return cache == null ? CacheResource.findCacheName(activeResource) : Optional.of(cache); } } @CommandDefinition(name = "cancel-receive-state", description = "Cancels receiving state to a site", activator = ConnectionActivator.class) public static class CancelReceiveState extends RestCliCommand implements CacheAwareCommand { @Option(required = true, shortName = 'c', completer = CacheCompleter.class, description = "The cache name.") String cache; @Option(required = true, shortName = 's', completer = SiteCompleter.class, description = "The remote backup name.") String site; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache).cancelReceiveState(site); } @Override public Optional<String> getCacheName(Resource activeResource) { return Optional.ofNullable(cache); } } @CommandDefinition(name = "push-site-status", description = "Shows the status of pushing to a site", activator = ConnectionActivator.class) public static class PushSiteStatus extends RestCliCommand implements CacheAwareCommand { @Option(required = true, shortName = 'c', completer = CacheCompleter.class, description = "The cache name.") String cache; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache).pushStateStatus(); } @Override public Optional<String> getCacheName(Resource activeResource) { return Optional.ofNullable(cache); } } @CommandDefinition(name = "clear-push-site-status", description = "Clears the push state status", activator = ConnectionActivator.class) public static class ClearPushStateStatus extends RestCliCommand implements CacheAwareCommand { @Option(required = true, shortName = 'c', completer = CacheCompleter.class, description = "The cache name.") String cache; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache).clearPushStateStatus(); } @Override public Optional<String> getCacheName(Resource activeResource) { return Optional.ofNullable(cache); } } @CommandDefinition(name = "view", description = "Prints the global sites view", activator = ConnectionActivator.class) public static class View extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { try { Connection connection = invocation.getContext().getConnection(); connection.refreshServerInfo(); invocation.println(connection.getSitesView().toString()); return CommandResult.SUCCESS; } catch (IOException e) { throw new CommandException(e); } } } @CommandDefinition(name = "name", description = "Prints the local site name", activator = ConnectionActivator.class) public static class Name extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { try { Connection connection = invocation.getContext().getConnection(); connection.refreshServerInfo(); invocation.println(connection.getLocalSiteName()); return CommandResult.SUCCESS; } catch (IOException e) { throw new CommandException(e); } } } @GroupCommandDefinition(name = "state-transfer-mode", description = "Controls the cross-site state transfer mode.", activator = ConnectionActivator.class, groupCommands = { GetStateTransferMode.class, SetStateTransferMode.class }) public static class StateTransferMode extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } } @CommandDefinition(name = "get", description = "Retrieves the cross-site state transfer mode.", activator = ConnectionActivator.class) public static class GetStateTransferMode extends RestCliCommand implements CacheAwareCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Option(shortName = 'c', completer = CacheCompleter.class, description = "The cache name.") String cache; @Option(shortName = 's', required = true, completer = SiteCompleter.class, description = "The remote backup name.") String site; @Override public boolean isHelp() { return help; } @Override public Optional<String> getCacheName(Resource activeResource) { return cache == null ? CacheResource.findCacheName(activeResource) : Optional.of(cache); } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { String cacheName = getCacheName(resource).orElseThrow(MSG::illegalContext); return client.cache(cacheName).xSiteStateTransferMode(site); } } @CommandDefinition(name = "set", description = "Sets the cross-site state transfer mode.", activator = ConnectionActivator.class) public static class SetStateTransferMode extends RestCliCommand implements CacheAwareCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Option(shortName = 'c', completer = CacheCompleter.class, description = "The cache name.") String cache; @Option(shortName = 's', required = true, completer = SiteCompleter.class, description = "The remote backup name.") String site; @Option(shortName = 'm', required = true, completer = XSiteStateTransferModeCompleter.class, description = "The state transfer mode to set.") protected String mode; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { String cacheName = getCacheName(resource).orElseThrow(MSG::illegalContext); return client.cache(cacheName).xSiteStateTransferMode(site, XSiteStateTransferMode.valueOf(mode.toUpperCase())); } @Override public Optional<String> getCacheName(Resource activeResource) { return cache == null ? CacheResource.findCacheName(activeResource) : Optional.of(cache); } } @CommandDefinition(name = "relay-nodes", description = "Returns the list of relay nodes.", activator = ConnectionActivator.class) public static class RelayNodes extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { try { Connection connection = invocation.getContext().getConnection(); connection.refreshServerInfo(); invocation.println(String.valueOf(connection.getRelayNodes())); return CommandResult.SUCCESS; } catch (IOException e) { throw new CommandException(e); } } } @CommandDefinition(name = "is-relay-node", description = "Returns true if the node handles relay messages between clusters.", activator = ConnectionActivator.class) public static class IsRelayNode extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { try { Connection connection = invocation.getContext().getConnection(); connection.refreshServerInfo(); invocation.println(String.valueOf(connection.isRelayNode())); return CommandResult.SUCCESS; } catch (IOException e) { throw new CommandException(e); } } } private static void checkMutualExclusiveCacheAndGlobal(String cache, boolean global) { if (cache != null && global) { throw MSG.mutuallyExclusiveOptions("cache", "all-caches"); } } private static RestCacheManagerClient restCacheManagerClient(RestClient client, Resource resource) { return ContainerResource.findContainerName(resource).map(client::cacheManager).orElseThrow(MSG::illegalContext); } private static RestCacheClient restCacheClient(RestClient client, Resource resource, String cacheName) throws RequiredOptionException { return cacheName == null ? CacheResource.findCacheName(resource).map(client::cache).orElseThrow(MISSING_CACHE_OR_GLOBAL) : client.cache(cacheName); } }
20,580
38.73166
167
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Connections.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; /** * @since 15.0 **/ @GroupCommandDefinition(name = Connections.CMD, description = "Performs operations on connections", activator = ConnectionActivator.class, groupCommands = {Connections.Ls.class}) public class Connections extends CliCommand { public static final String CMD = "connections"; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "ls", description = "Lists connections", activator = ConnectionActivator.class) public static class Ls extends RestCliCommand { @Option(shortName = 'g', hasValue = false, overrideRequired = true) protected boolean global; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.server().listConnections(global); } } }
1,946
32
178
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Remove.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.CacheResource; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "remove", description = "Removes an entry from the cache", aliases = "rm", activator = ConnectionActivator.class) public class Remove extends RestCliCommand { @Argument(required = true) String key; @Option(completer = CacheCompleter.class) String cache; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache != null ? cache : CacheResource.cacheName(resource)).remove(key); } }
1,471
30.319149
139
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Connector.java
package org.infinispan.cli.commands.rest; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletionStage; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.aesh.command.option.OptionList; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.ConnectorCompleter; import org.infinispan.cli.completers.IpFilterRuleCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.logging.Messages; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.IpFilterRule; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.1 **/ @GroupCommandDefinition(name = Connector.CMD, description = "Performs operations on protocol connectors", activator = ConnectionActivator.class, groupCommands = {Connector.Ls.class, Connector.Describe.class, Connector.Start.class, Connector.Stop.class, Connector.IpFilter.class}) public class Connector extends CliCommand { public static final String CMD = "connector"; public static final String TYPE = "type"; public static final String NAME = "name"; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "ls", description = "Lists connectors", activator = ConnectionActivator.class) public static class Ls extends RestCliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.server().connectorNames(); } } @CommandDefinition(name = "describe", description = "Describes a connector", activator = ConnectionActivator.class) public static class Describe extends RestCliCommand { @Argument(required = true, completer = ConnectorCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.server().connector(name); } } @CommandDefinition(name = "start", description = "Starts a connector", activator = ConnectionActivator.class) public static class Start extends RestCliCommand { @Argument(required = true, completer = ConnectorCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.server().connectorStart(name); } } @CommandDefinition(name = "stop", description = "Stops a connector", activator = ConnectionActivator.class) public static class Stop extends RestCliCommand { @Argument(required = true, completer = ConnectorCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.server().connectorStop(name); } } @GroupCommandDefinition(name = "ipfilter", description = "Manages connector IP filters", activator = ConnectionActivator.class, groupCommands = {IpFilter.Ls.class, IpFilter.Clear.class, IpFilter.Set.class}) public static class IpFilter extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override protected boolean isHelp() { return help; } @Override protected CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { return CommandResult.FAILURE; } @CommandDefinition(name = "ls", description = "List all IP filters on a connector", activator = ConnectionActivator.class) public static class Ls extends RestCliCommand { @Argument(required = true, completer = ConnectorCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.server().connectorIpFilters(name); } } @CommandDefinition(name = "clear", description = "Removes all IP Filters from a connector", activator = ConnectionActivator.class) public static class Clear extends RestCliCommand { @Argument(required = true, completer = ConnectorCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.server().connectorIpFiltersClear(name); } } @CommandDefinition(name = "set", description = "Sets IP Filters on a connector", activator = ConnectionActivator.class) public static class Set extends RestCliCommand { @Argument(required = true, completer = ConnectorCompleter.class) String name; @OptionList(description = "One or more filter rules as \"[ACCEPT|REJECT]/CIDR\"", completer = IpFilterRuleCompleter.class, required = true) List<String> rules; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { List<IpFilterRule> filterRules = new ArrayList<>(rules.size()); for (String rule : rules) { int i = rule.indexOf('/'); if (i < 0) { throw Messages.MSG.illegalFilterRule(rule); } IpFilterRule.RuleType ruleType = IpFilterRule.RuleType.valueOf(rule.substring(0, i)); filterRules.add(new IpFilterRule(ruleType, rule.substring(i + 1))); } return client.server().connectorIpFilterSet(name, filterRules); } } } }
7,893
35.37788
279
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/DataSource.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.DataSourceCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 13.0 **/ @GroupCommandDefinition(name = DataSource.CMD, description = "Performs operations on data sources", activator = ConnectionActivator.class, groupCommands = {DataSource.Ls.class, DataSource.Test.class}) public class DataSource extends CliCommand { public static final String CMD = "datasource"; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "ls", description = "Lists data sources", activator = ConnectionActivator.class) public static class Ls extends RestCliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.server().dataSourceNames(); } } @CommandDefinition(name = "test", description = "Tests a data source", activator = ConnectionActivator.class) public static class Test extends RestCliCommand { @Argument(required = true, description = "The name of the data source", completer = DataSourceCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.server().dataSourceTest(name); } } }
2,716
33.392405
200
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Reset.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.CounterCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.CounterResource; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "reset", description = "Resets a counter to its initial value", activator = ConnectionActivator.class) public class Reset extends RestCliCommand { @Argument(completer = CounterCompleter.class) String counter; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.counter(counter == null ? CounterResource.counterName(resource) : counter).reset(); } }
1,427
33
129
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Index.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 14.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "index", description = "Performs operations on indexes", activator = ConnectionActivator.class, groupCommands = {Index.Reindex.class, Index.Clear.class, Index.Stats.class, Index.Metamodel.class, Index.UpdateIndex.class, Index.ClearStats.class}) public class Index extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation commandInvocation) { commandInvocation.println(commandInvocation.getHelpInfo()); return CommandResult.SUCCESS; } @CommandDefinition(name = "reindex", description = "Reindexes a cache.", activator = ConnectionActivator.class) public static class Reindex extends RestCliCommand { @Argument(description = "Specifies which cache to reindex.", completer = CacheCompleter.class, required = true) String cache; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache).reindex(); } } @CommandDefinition(name = "clear", description = "Clears a cache index.", activator = ConnectionActivator.class) public static class Clear extends RestCliCommand { @Argument(description = "Specifies which cache index to clear.", completer = CacheCompleter.class, required = true) String cache; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache).clearIndex(); } } @CommandDefinition(name = "update-schema", description = "Update index schema for a given cache.", activator = ConnectionActivator.class) public static class UpdateIndex extends RestCliCommand { @Argument(description = "Specifies which cache to update its index schema.", completer = CacheCompleter.class, required = true) String cache; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache).updateIndexSchema(); } } @CommandDefinition(name = "metamodel", description = "Displays the index metamodel for a cache.", activator = ConnectionActivator.class) public static class Metamodel extends RestCliCommand { @Argument(description = "Specifies which cache statistics to display.", completer = CacheCompleter.class, required = true) String cache; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache).indexMetamodel(); } } @CommandDefinition(name = "stats", description = "Displays indexing and search statistics for a cache.", activator = ConnectionActivator.class) public static class Stats extends RestCliCommand { @Argument(description = "Specifies which cache statistics to display.", completer = CacheCompleter.class, required = true) String cache; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache).searchStats(); } } @CommandDefinition(name = "clear-stats", description = "Clears cache indexing and search statistics.", activator = ConnectionActivator.class) public static class ClearStats extends RestCliCommand { @Argument(description = "Specifies which cache statistics to clear.", completer = CacheCompleter.class, required = true) String cache; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache).clearSearchStats(); } } }
5,961
35.802469
275
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Stats.java
package org.infinispan.cli.commands.rest; import static org.infinispan.cli.logging.Messages.MSG; import java.io.IOException; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.CdContextCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.CacheResource; import org.infinispan.cli.resources.ContainerResource; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "stats", description = "Shows cache and container statistics", activator = ConnectionActivator.class) public class Stats extends RestCliCommand { @Argument(description = "The path of the resource", completer = CdContextCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Option(hasValue = false) protected boolean reset; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource activeResource) { try { Resource resource = activeResource.getResource(name); if (resource instanceof CacheResource) { return reset ? client.cache(resource.getName()).statsReset() : client.cache(resource.getName()).stats(); } else if (resource instanceof ContainerResource) { return reset ? client.cacheManager(resource.getName()).statsReset() : client.cacheManager(resource.getName()).stats(); } else { if (reset) { throw MSG.cannotResetIndividualStat(); } String name = resource.getName(); throw MSG.invalidResource(name.isEmpty() ? "/" : name); } } catch (IOException e) { throw new RuntimeException(e); } } }
2,316
35.203125
135
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Rebalance.java
package org.infinispan.cli.commands.rest; import static org.infinispan.cli.logging.Messages.MSG; import java.io.IOException; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.CdContextCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.CacheResource; import org.infinispan.cli.resources.ContainerResource; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Ryan Emerson * @since 13.0 */ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "rebalance", description = "Manage rebalance behaviour", activator = ConnectionActivator.class, groupCommands = {Rebalance.Enable.class, Rebalance.Disable.class}) public class Rebalance extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "enable", description = "Enable rebalancing", activator = ConnectionActivator.class) public static class Enable extends RestCliCommand { @Argument(description = "The path of the resource", completer = CdContextCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource activeResource) { try { Resource resource = activeResource.getResource(name); if (resource instanceof CacheResource) { return client.cache(resource.getName()).enableRebalancing(); } else if (resource instanceof ContainerResource) { return client.cacheManager(resource.getName()).enableRebalancing(); } else { String name = resource.getName(); throw MSG.invalidResource(name.isEmpty() ? "/" : name); } } catch (IOException e) { throw new RuntimeException(e); } } } @CommandDefinition(name = "disable", description = "Disable rebalancing", activator = ConnectionActivator.class) public static class Disable extends RestCliCommand { @Argument(description = "The path of the resource", completer = CdContextCompleter.class) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource activeResource) { try { Resource resource = activeResource.getResource(name); if (resource instanceof CacheResource) { return client.cache(resource.getName()).disableRebalancing(); } else if (resource instanceof ContainerResource) { return client.cacheManager(resource.getName()).disableRebalancing(); } else { String name = resource.getName(); throw MSG.invalidResource(name.isEmpty() ? "/" : name); } } catch (IOException e) { throw new RuntimeException(e); } } } }
4,130
36.554545
193
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Backup.java
package org.infinispan.cli.commands.rest; import java.io.File; import java.time.LocalDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.aesh.command.option.OptionList; import org.aesh.io.Resource; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.BackupCompleter; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.completers.CacheConfigurationCompleter; import org.infinispan.cli.completers.CounterCompleter; import org.infinispan.cli.completers.SchemaCompleter; import org.infinispan.cli.completers.TaskCompleter; import org.infinispan.cli.connection.Connection; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.util.Version; import org.kohsuke.MetaInfServices; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.schedulers.Schedulers; /** * @author Ryan Emerson * @since 12.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "backup", description = "Manages container backup creation and restoration", activator = ConnectionActivator.class, groupCommands = {Backup.Create.class, Backup.Delete.class, Backup.Get.class, Backup.ListBackups.class, Backup.Restore.class}) public class Backup extends CliCommand { public static final String CACHES = "caches"; public static final String TEMPLATES = "templates"; public static final String COUNTERS = "counters"; public static final String PROTO_SCHEMAS = "proto-schemas"; public static final String TASKS = "tasks"; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "delete", description = "Delete a backup on the server", activator = ConnectionActivator.class) public static class Delete extends AbstractBackupCommand { @Argument(description = "The name of the backup", completer = BackupCompleter.class, required = true) String name; @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) { String container = invocation.getContext().getConnection().getActiveContainer().getName(); invocation.printf("Deleting backup %s%n", name); return client.cacheManager(container).deleteBackup(this.name); } } @CommandDefinition(name = "get", description = "Get a backup from the server", activator = ConnectionActivator.class) public static class Get extends AbstractBackupCommand { public static final String NO_CONTENT = "no-content"; @Argument(description = "The name of the backup", completer = BackupCompleter.class, required = true) String name; @Option(description = "No content is downloaded, but the command only returns once the backup has finished", hasValue = false, name = NO_CONTENT) boolean noContent; @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) { String container = invocation.getContext().getConnection().getActiveContainer().getName(); invocation.printf("Downloading backup %s%n", name); // Poll the backup's availability every 500 milliseconds with a maximum of 100 attempts return Flowable.timer(500, TimeUnit.MILLISECONDS, Schedulers.trampoline()) .repeat(100) .flatMapSingle(Void -> Single.fromCompletionStage(client.cacheManager(container).getBackup(name, noContent))) .takeUntil(rsp -> rsp.getStatus() != 202) .lastOrErrorStage(); } @Override public Connection.ResponseMode getResponseMode() { return noContent ? Connection.ResponseMode.QUIET : Connection.ResponseMode.FILE; } } @CommandDefinition(name = "ls", description = "List all backups on the server", activator = ConnectionActivator.class) public static class ListBackups extends AbstractBackupCommand { @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) { String container = invocation.getContext().getConnection().getActiveContainer().getName(); return client.cacheManager(container).getBackupNames(); } } @CommandDefinition(name = "create", description = "Create a backup on the server", activator = ConnectionActivator.class) public static class Create extends AbstractResourceCommand { @Option(shortName = 'd', description = "The directory on the server to be used for creating and storing the backup") String dir; @Option(shortName = 'n', description = "The name of the backup") String name; @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) { // If the backup name has not been specified generate one based upon the Infinispan version and timestamp String backupName = name != null ? name : String.format("%s-%tY%2$tm%2$td%2$tH%2$tM%2$tS", Version.getBrandName(), LocalDateTime.now()); invocation.printf("Creating backup '%s'%n", backupName); String container = invocation.getContext().getConnection().getActiveContainer().getName(); return client.cacheManager(container).createBackup(backupName, dir, createResourceMap()); } } @CommandDefinition(name = "restore", description = "Restore a backup", activator = ConnectionActivator.class) public static class Restore extends AbstractResourceCommand { @Argument(description = "The path of the backup file ", completer = FileOptionCompleter.class, required = true) Resource path; @Option(shortName = 'n', description = "Defines a name for the restore request.") String name; @Option(shortName = 'u', description = "Indicates that the path is a local file which must be uploaded to the server", hasValue = false, name = "upload-backup") boolean upload; @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, org.infinispan.cli.resources.Resource resource) { Map<String, List<String>> resources = createResourceMap(); // If the restore name has not been specified generate one based upon the Infinispan version and timestamp String restoreName = name != null ? name : String.format("%s-%tY%2$tm%2$td%2$tH%2$tM%2$tS", Version.getBrandName(), LocalDateTime.now()); String container = invocation.getContext().getConnection().getActiveContainer().getName(); if (upload) { invocation.printf("Uploading backup '%s' and restoring%n", path.getAbsolutePath()); File file = new File(path.getAbsolutePath()); return client.cacheManager(container).restore(restoreName, file, resources).thenCompose(rsp -> pollRestore(restoreName, container, client, rsp)); } else { invocation.printf("Restoring from backup '%s'%n", path.getAbsolutePath()); return client.cacheManager(container).restore(restoreName, path.getAbsolutePath(), resources).thenCompose(rsp -> pollRestore(restoreName, container, client, rsp)); } } } private static CompletionStage<RestResponse> pollRestore(String restoreName, String container, RestClient c, RestResponse rsp) { if (rsp.getStatus() != 202) { return CompletableFuture.completedFuture(rsp); } // Poll the restore progress every 500 milliseconds with a maximum of 100 attempts return Flowable.timer(500, TimeUnit.MILLISECONDS, Schedulers.trampoline()) .repeat(100) .flatMapSingle(Void -> Single.fromCompletionStage(c.cacheManager(container).getRestore(restoreName))) .takeUntil(r -> r.getStatus() != 202) .lastOrErrorStage(); } private abstract static class AbstractBackupCommand extends RestCliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } } private abstract static class AbstractResourceCommand extends AbstractBackupCommand { @OptionList(description = "Comma separated list of caches to include, '*' indicates all available", completer = CacheCompleter.class, name = CACHES) List<String> caches; @OptionList(description = "Comma separated list of cache templates to include, '*' indicates all available", completer = CacheConfigurationCompleter.class, name = TEMPLATES) List<String> templates; @OptionList(description = "Comma separated list of counters to include, '*' indicates all available", completer = CounterCompleter.class, name = COUNTERS) List<String> counters; @OptionList(description = "Comma separated list of proto schemas to include, '*' indicates all available", completer = SchemaCompleter.class, name = PROTO_SCHEMAS) List<String> protoSchemas; @OptionList(description = "Comma separated list of tasks to include, '*' indicates all available", completer = TaskCompleter.class, name = TASKS) List<String> tasks; public Map<String, List<String>> createResourceMap() { Map<String, List<String>> resourceMap = new HashMap<>(); if (caches != null) { resourceMap.put(CACHES, caches); } if (templates != null) { resourceMap.put(TEMPLATES, templates); } if (counters != null) { resourceMap.put(COUNTERS, counters); } if (protoSchemas != null) { resourceMap.put(PROTO_SCHEMAS, protoSchemas); } if (tasks != null) { resourceMap.put(TASKS, tasks); } return resourceMap; } } }
11,053
46.239316
175
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Topology.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.CacheResource; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; @MetaInfServices(Command.class) @GroupCommandDefinition(name = "topology", description = "Manages the cluster topology.", activator = ConnectionActivator.class, groupCommands = {Topology.SetStable.class}) public class Topology extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override protected boolean isHelp() { return help; } @Override protected CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "set-stable", description = "Set the current topology as stable.", activator = ConnectionActivator.class) public static class SetStable extends RestCliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Option(shortName = 'f', hasValue = false, overrideRequired = true) protected boolean force; @Argument(description = "The cache name to mark topology stable.", completer = CacheCompleter.class) String cacheName; @Override protected boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) throws Exception { return client.cache(cacheName != null ? cacheName : CacheResource.cacheName(resource)).markTopologyStable(force); } } }
2,376
36.140625
149
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/RestCliCommand.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.shell.Shell; import org.aesh.readline.terminal.formatting.Color; import org.aesh.readline.terminal.formatting.TerminalColor; import org.aesh.readline.terminal.formatting.TerminalString; import org.infinispan.cli.Context; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.connection.Connection; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.util.Util; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ abstract class RestCliCommand extends CliCommand { protected abstract CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) throws Exception; @Override protected final CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { Shell shell = invocation.getShell(); Context context = invocation.getContext(); try { String response = context.getConnection().execute((c, r) -> { try { return exec(invocation, c, r); } catch (Exception e) { throw new RuntimeException(e); } }, getResponseMode()); if (response != null && !response.isEmpty()) { shell.writeln(response); } invocation.getContext().refreshPrompt(); return CommandResult.SUCCESS; } catch (Exception e) { TerminalString error = new TerminalString(Util.getRootCause(e).getLocalizedMessage(), new TerminalColor(Color.RED, Color.DEFAULT, Color.Intensity.BRIGHT)); shell.writeln(error.toString()); invocation.getContext().refreshPrompt(); return CommandResult.FAILURE; } } public Connection.ResponseMode getResponseMode() { return Connection.ResponseMode.BODY; } }
2,168
37.052632
164
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Get.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.connection.Connection; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.CacheResource; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "get", description = "Gets an entry from the cache", activator = ConnectionActivator.class, aliases = "cat") public class Get extends RestCliCommand { @Argument(required = true) String key; @Option(completer = CacheCompleter.class, shortName = 'c') String cache; @Option(shortName = 'x', hasValue = false) boolean extended; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.cache(cache != null ? cache : CacheResource.cacheName(resource)).get(key, null, extended); } @Override public Connection.ResponseMode getResponseMode() { return extended ? Connection.ResponseMode.HEADERS : Connection.ResponseMode.BODY; } }
1,769
31.777778
134
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/rest/Server.java
package org.infinispan.cli.commands.rest; import java.util.concurrent.CompletionStage; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.connection.Connection; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ @MetaInfServices(Command.class) @GroupCommandDefinition(name = "server", description = "Obtains information about the server", activator = ConnectionActivator.class, groupCommands = {Connector.class, DataSource.class, Server.Report.class, Server.HeapDump.class, Connections.class, Principals.class, AclCache.class}) public class Server extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation commandInvocation) { commandInvocation.println(commandInvocation.getHelpInfo()); return CommandResult.SUCCESS; } @CommandDefinition(name = "report", description = "Obtains an aggregate report from the server", activator = ConnectionActivator.class) public static class Report extends RestCliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.server().report(); } @Override public Connection.ResponseMode getResponseMode() { return Connection.ResponseMode.FILE; } } @CommandDefinition(name = "heap-dump", description = "Generates a JVM heap dump on the server", activator = ConnectionActivator.class) public static class HeapDump extends RestCliCommand { @Option(shortName = 'l', hasValue = false, description = "Dump only live objects, i.e. objects that are reachable from others.") protected boolean live; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override protected CompletionStage<RestResponse> exec(ContextAwareCommandInvocation invocation, RestClient client, Resource resource) { return client.server().heapDump(live); } } }
2,961
34.686747
283
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/kubernetes/Create.java
package org.infinispan.cli.commands.kubernetes; import static org.infinispan.cli.commands.kubernetes.Kube.DEFAULT_CLUSTER_NAME; import static org.infinispan.cli.commands.kubernetes.Kube.INFINISPAN_CLUSTER_CRD; import java.util.Map; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.aesh.command.option.OptionGroup; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.completers.EncryptionCompleter; import org.infinispan.cli.completers.ExposeCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.impl.KubernetesContext; import org.infinispan.cli.logging.Messages; import io.fabric8.kubernetes.api.model.GenericKubernetesResource; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.client.KubernetesClient; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ @GroupCommandDefinition( name = "create", description = "Creates resources.", groupCommands = { Create.Cluster.class, }) public class Create extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @CommandDefinition(name = "cluster", description = "Creates a cluster") public static class Cluster extends CliCommand { @Option(shortName = 'n', description = "Specifies the namespace where the cluster is created. Uses the default namespace if you do not specify one.") String namespace; @Option(shortName = 'r', description = "Specifies the number of replicas. Defaults to 1.", defaultValue = "1") int replicas; @Option(shortName = 'v', description = "Specifies the server version. If omitted, the latest available version will be used.") String version; @Option(name = "expose-type", completer = ExposeCompleter.class, description = "Makes the service available on the network through a LoadBalancer, NodePort, or Route.") String exposeType; @Option(name = "expose-port", defaultValue = "0", description = "Sets the network port where the service is available. You must set a port if the expose type is LoadBalancer or NodePort.") int exposePort; @Option(name = "expose-host", description = "Optionally sets the hostname if the expose type is Route.") String exposeHost; @Option(name = "encryption-type", completer = EncryptionCompleter.class, description = "The type of encryption: one of None, Secret, Service") String encryptionType; @Option(name = "encryption-secret", description = "The name of the secret containing the TLS certificate") String encryptionSecret; @Argument(description = "Defines the cluster name. Defaults to '" + DEFAULT_CLUSTER_NAME + "'", defaultValue = DEFAULT_CLUSTER_NAME) String name; @OptionGroup(shortName = 'P', description = "Sets a spec property. Use the '.' as separator for child nodes") Map<String, String> specProperties; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { KubernetesClient client = KubernetesContext.getClient(invocation); namespace = Kube.getNamespaceOrDefault(client, namespace); GenericKubernetesResource infinispan = new GenericKubernetesResource(); infinispan.setKind(INFINISPAN_CLUSTER_CRD.getKind()); ObjectMeta metadata = new ObjectMeta(); metadata.setName(name); metadata.setNamespace(namespace); infinispan.setMetadata(metadata); GenericKubernetesResource spec = new GenericKubernetesResource(); infinispan.setAdditionalProperty("spec", spec); spec.setAdditionalProperty("replicas", replicas); if (version != null) { spec.setAdditionalProperty("version", version); } if (exposeType != null) { GenericKubernetesResource expose = new GenericKubernetesResource(); spec.setAdditionalProperty("expose", expose); expose.setAdditionalProperty("type", exposeType); switch (ExposeCompleter.Expose.valueOf(exposeType)) { case LoadBalancer: if (exposePort == 0) { throw Messages.MSG.exposeTypeRequiresPort(exposeType); } else { expose.setAdditionalProperty("port", exposePort); } break; case NodePort: if (exposePort == 0) { throw Messages.MSG.exposeTypeRequiresPort(exposeType); } else { expose.setAdditionalProperty("nodePort", exposePort); } break; } if (exposeHost != null) { expose.setAdditionalProperty("host", exposeHost); } } if (encryptionType != null) { GenericKubernetesResource security = new GenericKubernetesResource(); spec.setAdditionalProperty("security", security); GenericKubernetesResource encryption = new GenericKubernetesResource(); security.setAdditionalProperty("endpointEncryption", encryption); encryption.setAdditionalProperty("type", encryptionType); if (EncryptionCompleter.Encryption.valueOf(encryptionType) == EncryptionCompleter.Encryption.Secret) { if (encryptionSecret != null) { encryption.setAdditionalProperty("certSecretName", encryptionSecret); } else { throw Messages.MSG.encryptionTypeRequiresSecret(encryptionType); } } } if (specProperties != null) { specProperties.forEach((k, v) -> Kube.setProperty(spec, v, k.split("\\."))); } client.genericKubernetesResources(INFINISPAN_CLUSTER_CRD).inNamespace(namespace).create(infinispan); return CommandResult.SUCCESS; } } }
6,639
41.564103
194
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/kubernetes/Shell.java
package org.infinispan.cli.commands.kubernetes; import static org.infinispan.cli.commands.kubernetes.Kube.DEFAULT_CLUSTER_NAME; import static org.infinispan.cli.commands.kubernetes.Kube.INFINISPAN_CLUSTER_CRD; import java.net.InetAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermissions; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.aesh.io.Resource; import org.aesh.readline.terminal.formatting.Color; import org.aesh.readline.terminal.formatting.TerminalColor; import org.aesh.readline.terminal.formatting.TerminalString; import org.infinispan.cli.commands.CLI; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.impl.KubeShell; import org.infinispan.cli.impl.KubernetesContext; import org.infinispan.cli.logging.Messages; import org.infinispan.commons.util.Util; import io.fabric8.kubernetes.api.model.ContainerPort; import io.fabric8.kubernetes.api.model.GenericKubernetesResource; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.Secret; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.LocalPortForward; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ @CommandDefinition(name = "shell", description = "Initiates an interactive shell with a service.") public class Shell extends CliCommand { @Option(shortName = 'n', description = "Specifies the namespace where the cluster is running. Uses the default namespace if you do not specify one.") String namespace; @Option(shortName = 'p', name = "pod-name", description = "Specifies to which pod you connect.") String podName; @Option(shortName = 'u', name = "username", description = "The username to use when connecting") String username; @Option(completer = FileOptionCompleter.class, shortName = 'k', name = "keystore", description = "A keystore containing a client certificate to authenticate with the server") Resource keystore; @Option(shortName = 'w', name = "keystore-password", description = "The password for the keystore") String keystorePassword; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Argument(description = "Specifies the name of the service to connect to. Defaults to '" + DEFAULT_CLUSTER_NAME + "'", defaultValue = DEFAULT_CLUSTER_NAME) String name; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { KubernetesClient client = KubernetesContext.getClient(invocation); namespace = Kube.getNamespaceOrDefault(client, namespace); GenericKubernetesResource infinispan = client.genericKubernetesResources(INFINISPAN_CLUSTER_CRD).inNamespace(namespace).withName(name).get(); if (infinispan == null) { throw Messages.MSG.noSuchService(name, namespace); } String endpointSecretName = Kube.getProperty(infinispan, "spec", "security", "endpointSecretName"); String certSecretName = Kube.getProperty(infinispan, "spec", "security", "endpointEncryption", "certSecretName"); Pod pod; if (podName == null) { pod = client.pods().inNamespace(namespace).withLabel("infinispan_cr", name).list() .getItems().stream().filter(p -> "running".equalsIgnoreCase(p.getStatus().getPhase())).findFirst().orElse(null); } else { pod = client.pods().inNamespace(namespace).withName(podName).get(); } if (pod == null) { throw Messages.MSG.noRunningPodsInService(name); } // Port forwarding mode List<ContainerPort> ports = pod.getSpec().getContainers().get(0).getPorts(); // Find the `infinispan` port ContainerPort containerPort = ports.stream().filter(p -> "infinispan".equals(p.getName())).findFirst().get(); try (LocalPortForward portForward = client.pods().inNamespace(namespace).withName(pod.getMetadata().getName()).portForward(containerPort.getContainerPort())) { StringBuilder connection = new StringBuilder(); List<String> args = new ArrayList<>(); if (certSecretName != null) { connection.append("https://"); Secret secret = Kube.getSecret(client, namespace, certSecretName); final byte[] cert; final String suffix; if (secret.getData().containsKey("keystore.p12")) { cert = Base64.getDecoder().decode(secret.getData().get("keystore.p12")); suffix = ".p12"; String password = new String(Base64.getDecoder().decode(secret.getData().get("password"))); args.add("-s"); args.add(password); } else { cert = new String(Base64.getDecoder().decode(secret.getData().get("tls.crt"))).getBytes(StandardCharsets.UTF_8); suffix = ".pem"; } Path certPath = Files.createTempFile("clitrust", suffix, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); Files.write(certPath, cert); args.add("-t"); args.add(certPath.toString()); args.add("--hostname-verifier"); args.add(".*"); if (keystore != null) { args.add("-k"); args.add(keystore.getAbsolutePath()); args.add("-w"); args.add(keystorePassword); } } else { connection.append("http://"); } if (endpointSecretName != null) { Secret secret = Kube.getSecret(client, namespace, endpointSecretName); Map<String, String> credentials = Kube.decodeOpaqueSecrets(secret); if (username == null) { if (credentials.size() != 1) { throw Messages.MSG.usernameRequired(); } else { Map.Entry<String, String> entry = credentials.entrySet().iterator().next(); connection.append(entry.getKey()); connection.append(':'); connection.append(entry.getValue()); connection.append('@'); } } else { connection.append(username); if (credentials.containsKey(username)) { connection.append(':'); connection.append(credentials.get(username)); } connection.append('@'); } } InetAddress localAddress = portForward.getLocalAddress(); if (localAddress.getAddress().length == 4) { connection.append(localAddress.getHostAddress()); } else { connection.append('[').append(localAddress.getHostAddress()).append(']'); } connection.append(':'); connection.append(portForward.getLocalPort()); args.add("-c"); args.add(connection.toString()); Messages.CLI.debugf("cli %s", args); CLI.main(new KubeShell(), args.toArray(new String[0]), System.getProperties(), false); return CommandResult.SUCCESS; } catch (Throwable t) { TerminalString error = new TerminalString(Util.getRootCause(t).getLocalizedMessage(), new TerminalColor(Color.RED, Color.DEFAULT, Color.Intensity.BRIGHT)); invocation.getShell().writeln(error.toString()); return CommandResult.FAILURE; } } }
7,881
44.560694
177
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/kubernetes/Install.java
package org.infinispan.cli.commands.kubernetes; import java.util.List; import java.util.Optional; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.option.Option; import org.aesh.command.option.OptionList; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.impl.KubernetesContext; import org.infinispan.cli.logging.Messages; import org.infinispan.commons.util.Version; import io.fabric8.kubernetes.api.model.GenericKubernetesResource; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.client.KubernetesClient; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ @CommandDefinition(name = "install", description = "Installs the Operator.") public class Install extends CliCommand { @Option(shortName = 'n', description = "Specifies a namespace for the Operator. Defaults to installing the Operator in the default Operator namespace.") String namespace; @Option(shortName = 'c', description = "Selects the channel to install and subscribes to upgrades for that release stream. If not specified, the latest stable channel is installed.") String channel; @Option(defaultValue = "false", name = "manual", shortName = 'm', description = "Requires approval before applying upgrades from the Operator subscription. Defaults to automatic approval.") boolean manual; @Option(description = "Specifies the CatalogSource for the Operator subscription. Selects an environment-dependent CatalogSource by default.") String source; @Option(name = "source-namespace", description = "Specifies the namespace of the subscription source. Selects an environment-dependent namespace by default.") String sourceNamespace; @OptionList(name = "target-namespaces", description = "Specifies the namespaces that the Operator watches. You must set a target namespace if you install the Operator in a specific namespace.") List<String> targetNamespaces; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { if (namespace != null && (targetNamespaces == null || targetNamespaces.isEmpty())) { throw Messages.MSG.noTargetNamespaces(); } KubernetesClient client = KubernetesContext.getClient(invocation); if (source == null) { // Determine whether this is OpenShift or K8S+OLM List<GenericKubernetesResource> sources = client.genericKubernetesResources(Kube.OPERATOR_CATALOGSOURCE_CRD).inAnyNamespace().list().getItems(); Optional<GenericKubernetesResource> catalog = sources.stream().filter(cs -> Version.getProperty("infinispan.olm.k8s.source").equals(cs.getMetadata().getName())).findFirst(); if (!catalog.isPresent()) { catalog = sources.stream().filter(cs -> Version.getProperty("infinispan.olm.openshift.source").equals(cs.getMetadata().getName())).findFirst(); } if (catalog.isPresent()) { GenericKubernetesResource catalogSource = catalog.get(); source = catalogSource.getMetadata().getName(); sourceNamespace = catalogSource.getMetadata().getNamespace(); } else { throw Messages.MSG.noCatalog(); } } String olmName = Version.getProperty("infinispan.olm.name"); if (namespace == null) { namespace = Kube.defaultOperatorNamespace(client); } else { // Non-global, we need to create an operator group GenericKubernetesResource group = new GenericKubernetesResource(); group.setKind(Kube.OPERATOR_OPERATORGROUP_CRD.getKind()); ObjectMeta groupMetadata = new ObjectMeta(); groupMetadata.setName(olmName); groupMetadata.setNamespace(namespace); group.setMetadata(groupMetadata); GenericKubernetesResource groupSpec = new GenericKubernetesResource(); groupSpec.setAdditionalProperty("targetNamespaces", targetNamespaces); group.setAdditionalProperty("spec", groupSpec); client.genericKubernetesResources(Kube.OPERATOR_OPERATORGROUP_CRD).inNamespace(namespace).createOrReplace(group); } GenericKubernetesResource subscription = new GenericKubernetesResource(); subscription.setKind(Kube.OPERATOR_SUBSCRIPTION_CRD.getKind()); ObjectMeta subscriptionMetadata = new ObjectMeta(); subscriptionMetadata.setName(olmName); subscriptionMetadata.setNamespace(namespace); subscription.setMetadata(subscriptionMetadata); GenericKubernetesResource subscriptionSpec = new GenericKubernetesResource(); subscriptionSpec.setAdditionalProperty("name", olmName); subscriptionSpec.setAdditionalProperty("installPlanApproval", manual ? "Manual" : "Automatic"); subscriptionSpec.setAdditionalProperty("source", source); subscriptionSpec.setAdditionalProperty("sourceNamespace", sourceNamespace); if (channel != null) { subscriptionSpec.setAdditionalProperty("channel", channel); } subscription.setAdditionalProperty("spec", subscriptionSpec); client.genericKubernetesResources(Kube.OPERATOR_SUBSCRIPTION_CRD).inNamespace(namespace).createOrReplace(subscription); return CommandResult.SUCCESS; } }
5,502
48.133929
196
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/kubernetes/Kube.java
package org.infinispan.cli.commands.kubernetes; import java.io.StringReader; import java.util.Base64; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import org.aesh.command.Command; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.invocation.CommandInvocation; import org.infinispan.cli.commands.Version; import org.infinispan.cli.logging.Messages; import org.infinispan.commons.configuration.io.NamingStrategy; import org.infinispan.commons.configuration.io.PropertyReplacer; import org.infinispan.commons.configuration.io.URLConfigurationResourceResolver; import org.infinispan.commons.configuration.io.yaml.YamlConfigurationReader; import io.fabric8.kubernetes.api.model.GenericKubernetesResource; import io.fabric8.kubernetes.api.model.Namespace; import io.fabric8.kubernetes.api.model.Secret; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ @GroupCommandDefinition( name = "kube", description = "Kubernetes commands.", groupCommands = { Create.class, Install.class, Shell.class, Get.class, Delete.class, Uninstall.class, Version.class }) public class Kube implements Command { public static final String DEFAULT_CLUSTER_NAME = "infinispan"; static final CustomResourceDefinitionContext INFINISPAN_CLUSTER_CRD = new CustomResourceDefinitionContext.Builder() .withName("infinispans.infinispan.org") .withGroup("infinispan.org") .withKind("Infinispan") .withPlural("infinispans") .withScope("Namespaced") .withVersion("v1") .build(); static final CustomResourceDefinitionContext OPERATOR_CATALOGSOURCE_CRD = new CustomResourceDefinitionContext.Builder() .withGroup("operators.coreos.com") .withKind("CatalogSource") .withPlural("catalogsources") .withScope("Namespaced") .withVersion("v1alpha1") .build(); static final CustomResourceDefinitionContext OPERATOR_CLUSTERSERVICEVERSION_CRD = new CustomResourceDefinitionContext.Builder() .withGroup("operators.coreos.com") .withKind("ClusterServiceVersion") .withPlural("clusterserviceversions") .withScope("Namespaced") .withVersion("v1alpha1") .build(); static final CustomResourceDefinitionContext OPERATOR_SUBSCRIPTION_CRD = new CustomResourceDefinitionContext.Builder() .withGroup("operators.coreos.com") .withKind("Subscription") .withPlural("subscriptions") .withScope("Namespaced") .withVersion("v1alpha1") .build(); static final CustomResourceDefinitionContext OPERATOR_OPERATORGROUP_CRD = new CustomResourceDefinitionContext.Builder() .withGroup("operators.coreos.com") .withKind("OperatorGroup") .withPlural("operatorgroups") .withScope("Namespaced") .withVersion("v1") .build(); public static <T> T getProperty(GenericKubernetesResource item, String... names) { Map<String, Object> properties = item.getAdditionalProperties(); for (int i = 0; i < names.length - 1; i++) { properties = (Map<String, Object>) properties.get(names[i]); if (properties == null) { return null; } } return (T) properties.get(names[names.length - 1]); } public static void setProperty(GenericKubernetesResource item, String value, String... names) { for (int i = 0; i < names.length - 1; i++) { Map<String, Object> properties = item.getAdditionalProperties(); if (properties.containsKey(names[i])) { item = (GenericKubernetesResource) properties.get(names[i]); } else { GenericKubernetesResource child = new GenericKubernetesResource(); item.setAdditionalProperty(names[i], child); item = child; } } item.setAdditionalProperty(names[names.length - 1], value); } @Override public CommandResult execute(CommandInvocation invocation) { invocation.getShell().write(invocation.getHelpInfo()); return CommandResult.FAILURE; } static Secret getSecret(KubernetesClient client, String namespace, String name) { try { return client.secrets().inNamespace(namespace).withName(name).get(); } catch (KubernetesClientException e) { return null; } } static Map<String, String> decodeOpaqueSecrets(Secret secret) { if (secret == null) { return Collections.emptyMap(); } String opaqueIdentities = secret.getData().get("identities.yaml"); String yaml = new String(Base64.getDecoder().decode(opaqueIdentities)); YamlConfigurationReader reader = new YamlConfigurationReader(new StringReader(yaml), new URLConfigurationResourceResolver(null), new Properties(), PropertyReplacer.DEFAULT, NamingStrategy.KEBAB_CASE); Map<String, Object> identities = reader.asMap(); List<Map<String, String>> credentialsList = (List<Map<String, String>>) identities.get("credentials"); Map<String, String> res = new LinkedHashMap<>(identities.size()); for (Map<String, String> credentials : credentialsList) { res.put(credentials.get("username"), credentials.get("password")); } return res; } static String getNamespaceOrDefault(KubernetesClient client, String namespace) { String ns = namespace != null ? namespace : client.getConfiguration().getNamespace(); if (ns == null) { throw Messages.MSG.noDefaultNamespace(); } return ns; } static String defaultOperatorNamespace(KubernetesClient client) { // Global installation: determine the namespace List<Namespace> namespaces = client.namespaces().list().getItems(); Optional<Namespace> ns = namespaces.stream().filter(n -> "openshift-operators".equals(n.getMetadata().getName())).findFirst(); if (!ns.isPresent()) { ns = namespaces.stream().filter(n -> "operators".equals(n.getMetadata().getName())).findFirst(); } if (ns.isPresent()) { return ns.get().getMetadata().getName(); } else { throw Messages.MSG.noDefaultOperatorNamespace(); } } }
6,667
38.455621
206
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/kubernetes/Delete.java
package org.infinispan.cli.commands.kubernetes; import static org.infinispan.cli.commands.kubernetes.Kube.DEFAULT_CLUSTER_NAME; import static org.infinispan.cli.commands.kubernetes.Kube.INFINISPAN_CLUSTER_CRD; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.impl.KubernetesContext; import org.kohsuke.MetaInfServices; import io.fabric8.kubernetes.client.KubernetesClient; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ @GroupCommandDefinition( name = "delete", description = "Deletes resources.", groupCommands = { Delete.Cluster.class, }) public class Delete extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @MetaInfServices(Command.class) @CommandDefinition(name = "cluster", description = "Deletes a cluster") public static class Cluster extends CliCommand { @Option(shortName = 'n', description = "Specifies the namespace of the cluster to delete. Uses the default namespace if you do not specify one.") String namespace; @Argument(description = "Specifies the name of the cluster to delete. Defaults to '" + DEFAULT_CLUSTER_NAME + "'", defaultValue = DEFAULT_CLUSTER_NAME) String name; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { KubernetesClient client = KubernetesContext.getClient(invocation); client.genericKubernetesResources(INFINISPAN_CLUSTER_CRD).inNamespace(Kube.getNamespaceOrDefault(client, namespace)).withName(name).delete(); return CommandResult.SUCCESS; } } }
2,467
33.277778
157
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/kubernetes/Get.java
package org.infinispan.cli.commands.kubernetes; import static org.infinispan.cli.commands.kubernetes.Kube.INFINISPAN_CLUSTER_CRD; import java.io.PrintStream; import java.util.List; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.option.Option; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.impl.KubernetesContext; import org.kohsuke.MetaInfServices; import io.fabric8.kubernetes.api.model.GenericKubernetesResource; import io.fabric8.kubernetes.api.model.GenericKubernetesResourceList; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.Secret; import io.fabric8.kubernetes.client.KubernetesClient; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ @GroupCommandDefinition( name = "get", description = "Displays resources.", groupCommands = { Get.Clusters.class, }) public class Get extends CliCommand { @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { // This command serves only to wrap the sub-commands invocation.println(invocation.getHelpInfo()); return CommandResult.FAILURE; } @MetaInfServices(Command.class) @CommandDefinition(name = "clusters", description = "Get clusters") public static class Clusters extends CliCommand { @Option(shortName = 'n', description = "Specifies the namespace where the cluster is running. Uses the default namespace if you do not specify one.") String namespace; @Option(name = "all-namespaces", shortName = 'A', description = "Displays the requested object(s) across all namespaces.") boolean allNamespaces; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Option(shortName = 's', hasValue = false, description = "Displays all secrets that the cluster uses.") protected boolean secrets; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { KubernetesClient client = KubernetesContext.getClient(invocation); GenericKubernetesResourceList resource = allNamespaces ? client.genericKubernetesResources(INFINISPAN_CLUSTER_CRD).inAnyNamespace().list() : client.genericKubernetesResources(INFINISPAN_CLUSTER_CRD).inNamespace(Kube.getNamespaceOrDefault(client, namespace)).list(); List<GenericKubernetesResource> items = resource.getItems(); PrintStream out = invocation.getShellOutput(); out.printf("%-32s %-16s %-9s %-16s%n", "NAME", "NAMESPACE", "STATUS", "SECRETS"); items.forEach(item -> { String n = item.getMetadata().getName(); String ns = item.getMetadata().getNamespace(); List<Pod> pods = client.pods().inNamespace(ns).withLabel("infinispan_cr", n).list().getItems(); long running = pods.stream().map(p -> p.getStatus()).filter(s -> "Running".equalsIgnoreCase(s.getPhase())).count(); out.printf("%-32s %-16s %-9s", n, ns, running + "/" + pods.size()); if (secrets) { String secretName = Kube.getProperty(item, "spec", "security", "endpointSecretName"); Secret secret = Kube.getSecret(client, ns, secretName); Kube.decodeOpaqueSecrets(secret).entrySet().forEach(c -> out.printf("%n%-60s%-16s %-16s", "", c.getKey(), c.getValue())); out.println(); } else { out.printf(" %-16s%n", "******"); } }); return CommandResult.SUCCESS; } } }
4,042
38.252427
155
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/kubernetes/Uninstall.java
package org.infinispan.cli.commands.kubernetes; import java.util.Map; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.option.Option; import org.infinispan.cli.commands.CliCommand; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.impl.KubernetesContext; import org.infinispan.cli.logging.Messages; import org.infinispan.commons.util.Version; import io.fabric8.kubernetes.api.model.GenericKubernetesResource; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.Resource; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ @CommandDefinition(name = "uninstall", description = "Removes the Operator.") public class Uninstall extends CliCommand { @Option(shortName = 'n', description = "Specifies the namespace where the Operator is installed, if you did not install it globally.") String namespace; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { KubernetesClient client = KubernetesContext.getClient(invocation); if (namespace == null) { namespace = Kube.defaultOperatorNamespace(client); } else { // We need to remove the operator group client.genericKubernetesResources(Kube.OPERATOR_OPERATORGROUP_CRD).inNamespace(namespace).withName(Version.getProperty("infinispan.olm.name")).delete(); } // Obtain the CSV for the subscription Resource<GenericKubernetesResource> subscription = client.genericKubernetesResources(Kube.OPERATOR_SUBSCRIPTION_CRD).inNamespace(namespace).withName(Version.getProperty("infinispan.olm.name")); GenericKubernetesResource sub = subscription.get(); if (sub == null) { throw Messages.MSG.noOperatorSubscription(namespace); } Map<String, Object> status = (Map<String, Object>) sub.getAdditionalProperties().get("status"); String csv = (String) status.get("installedCSV"); boolean deleted = subscription.delete().size() > 0; if (deleted) { // Now delete the CSV deleted = client.genericKubernetesResources(Kube.OPERATOR_CLUSTERSERVICEVERSION_CRD).inNamespace(namespace).withName(csv).delete().size() > 0; return deleted ? CommandResult.SUCCESS : CommandResult.FAILURE; } else { return CommandResult.FAILURE; } } }
2,588
40.095238
199
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/connection/RegexHostnameVerifier.java
package org.infinispan.cli.connection; import java.util.regex.Pattern; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; /** * @since 13.0 **/ public class RegexHostnameVerifier implements HostnameVerifier { private final Pattern pattern; public RegexHostnameVerifier(String pattern) { this.pattern = Pattern.compile(pattern); } @Override public boolean verify(String hostname, SSLSession session) { return pattern.matcher(hostname).matches(); } }
507
21.086957
64
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/connection/ConnectionFactory.java
package org.infinispan.cli.connection; import org.infinispan.cli.impl.SSLContextSettings; import org.infinispan.commons.util.ServiceFinder; public final class ConnectionFactory { public static Connection getConnection(String connectionString, SSLContextSettings sslContext) { for (Connector connector : ServiceFinder.load(Connector.class)) { Connection connection = connector.getConnection(connectionString, sslContext); if (connection != null) { return connection; } } return null; } }
553
29.777778
99
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/connection/Connector.java
package org.infinispan.cli.connection; import org.infinispan.cli.impl.SSLContextSettings; /** * Connector. * * @author tst * @since 5.2 */ public interface Connector { Connection getConnection(String connectionString, SSLContextSettings sslContext); }
262
17.785714
84
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/connection/Connection.java
package org.infinispan.cli.connection; import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.function.BiFunction; import org.infinispan.cli.resources.Resource; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.MediaType; public interface Connection extends Closeable { void connect() throws IOException; void connect(String username, String password) throws IOException; String getURI(); String execute(BiFunction<RestClient, Resource, CompletionStage<RestResponse>> op, ResponseMode responseMode) throws IOException; Resource getActiveResource(); void setActiveResource(Resource resource); Resource getActiveContainer(); Collection<String> getAvailableCaches(String container); Collection<String> getAvailableContainers(); Collection<String> getAvailableCounters(String container) throws IOException; Collection<String> getAvailableCacheConfigurations(String container); Collection<String> getAvailableSchemas(String container) throws IOException; Collection<String> getAvailableServers(String container) throws IOException; Collection<String> getAvailableSites(String container, String cache) throws IOException; Collection<String> getAvailableTasks(String container) throws IOException; Iterable<Map<String, String>> getCacheKeys(String container, String cache) throws IOException; Iterable<Map<String, String>> getCacheKeys(String container, String cache, int limit) throws IOException; Iterable<Map<String, String>> getCacheEntries(String container, String cache, int limit, boolean metadata) throws IOException; Iterable<String> getCounterValue(String container, String counter) throws IOException; boolean isConnected(); String describeContainer(String container) throws IOException; String describeCache(String container, String cache) throws IOException; String describeKey(String container, String cache, String key) throws IOException; String describeConfiguration(String container, String configuration) throws IOException; String describeCounter(String container, String counter) throws IOException; String describeTask(String container, String taskName) throws IOException; String getConnectionInfo(); String getServerVersion(); Collection<String> getClusterNodes(); Collection<String> getAvailableLogAppenders() throws IOException; Collection<String> getAvailableLoggers() throws IOException; Collection<String> getBackupNames(String container) throws IOException; Collection<String> getSitesView(); String getLocalSiteName(); boolean isRelayNode(); Collection<String> getRelayNodes(); Collection<String> getConnectorNames() throws IOException; MediaType getEncoding(); void setEncoding(MediaType encoding); void refreshServerInfo() throws IOException; Collection<String> getDataSourceNames() throws IOException; Collection<String> getCacheConfigurationAttributes(String name); String getUsername(); Collection<String> getRoles() throws IOException; enum ResponseMode {QUIET, BODY, FILE, HEADERS} }
3,299
29.841121
132
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/connection/rest/RestConnection.java
package org.infinispan.cli.connection.rest; import static org.infinispan.cli.logging.Messages.MSG; import static org.infinispan.cli.util.TransformingIterable.SINGLETON_MAP_VALUE; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.AccessDeniedException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiFunction; import java.util.function.Supplier; import java.util.stream.Collectors; import org.infinispan.cli.connection.Connection; import org.infinispan.cli.resources.ContainerResource; import org.infinispan.cli.resources.ContainersResource; import org.infinispan.cli.resources.Resource; import org.infinispan.cli.util.JsonReaderIterable; import org.infinispan.cli.util.TransformingIterable; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.RestTaskClient.ResultType; import org.infinispan.client.rest.configuration.AuthenticationConfiguration; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.client.rest.configuration.ServerConfiguration; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.util.Util; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class RestConnection implements Connection, Closeable { private static final String PROTOBUF_METADATA_CACHE_NAME = "___protobuf_metadata"; private final RestClientConfigurationBuilder builder; private Resource activeResource; private MediaType encoding = MediaType.TEXT_PLAIN; private Collection<String> availableConfigurations; private Collection<String> availableContainers; private Collection<String> availableCaches; private Collection<String> clusterMembers; private RestClient client; private boolean connected; private String serverVersion; private String serverInfo; private List<String> sitesView; private String localSite; private boolean relayNode; private List<String> relayNodes; private final Path workingDir; public RestConnection(RestClientConfigurationBuilder builder) { this.builder = builder; this.workingDir = Paths.get(System.getProperty("user.dir", "")); } @Override public String getURI() { if (client != null) { return client.getConfiguration().toURI(); } else { return null; } } @Override public void close() throws IOException { Util.close(client); } @Override public void connect() throws IOException { client = RestClient.forConfiguration(builder.build()); AuthenticationConfiguration authentication = client.getConfiguration().security().authentication(); if (authentication.enabled() && authentication.username() != null && authentication.password() == null && !"Bearer".equals(authentication.mechanism())) { throw new AccessDeniedException(""); } connectInternal(); } @Override public void connect(String username, String password) throws IOException { builder.security().authentication().enable().username(username).password(password); client = RestClient.forConfiguration(builder.build()); connectInternal(); } private void connectInternal() throws IOException { serverVersion = (String) parseBody(fetch(() -> client.server().info()), Map.class).get("version"); connected = true; availableContainers = parseBody(fetch(() -> client.cacheManagers()), List.class); activeResource = Resource.getRootResource(this) .getChild(ContainersResource.NAME, availableContainers.iterator().next()); refreshServerInfo(); } private RestResponse fetch(Supplier<CompletionStage<RestResponse>> responseFutureSupplier) throws IOException { return fetch(responseFutureSupplier.get()); } private RestResponse fetch(CompletionStage<RestResponse> responseFuture) throws IOException { try { return responseFuture.toCompletableFuture().get(10, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } catch (ExecutionException e) { throw MSG.connectionFailed(e.getMessage()); } catch (TimeoutException e) { throw new IOException(e); } } private Map<String, List<String>> parseHeaders(RestResponse response) throws IOException { response = handleResponseStatus(response); if (response != null) { return response.headers(); } else { return Collections.emptyMap(); } } private <T> T parseBody(RestResponse response, Class<T> returnClass) throws IOException { response = handleResponseStatus(response); if (response != null) { if (returnClass == InputStream.class) { return (T) response.getBodyAsStream(); } else if (returnClass == String.class) { if (MediaType.APPLICATION_JSON.equals(response.contentType())) { Json json = Json.read(response.getBody()); return (T) json.toPrettyString(); } else { return (T) response.getBody(); } } else { if (returnClass == Map.class) { return (T) Json.read(response.getBody()).asMap(); } if (returnClass == List.class) { return (T) Json.read(response.getBody()).asList(); } } } return null; } private RestResponse handleResponseStatus(RestResponse response) throws IOException { switch (response.getStatus()) { case 200: case 201: case 202: return response; case 204: return null; case 401: throw MSG.unauthorized(response.getBody()); case 403: throw MSG.forbidden(response.getBody()); case 404: throw MSG.notFound(response.getBody()); default: throw MSG.error(response.getBody()); } } @Override public MediaType getEncoding() { return encoding; } @Override public void setEncoding(MediaType encoding) { this.encoding = encoding; } @Override public String execute(BiFunction<RestClient, Resource, CompletionStage<RestResponse>> op, ResponseMode responseMode) throws IOException { RestResponse r = fetch(op.apply(client, activeResource)); return executeInternal(responseMode, r); } private String executeInternal(ResponseMode responseMode, RestResponse r) throws IOException { StringBuilder sb = new StringBuilder(); switch (responseMode) { case BODY: String body = parseBody(r, String.class); if (body != null) { sb.append(body); } break; case FILE: String contentDisposition = parseHeaders(r).get("Content-Disposition").get(0); String filename = Util.unquote(contentDisposition.split("filename=")[1]); Path file = workingDir.resolve(filename); try (OutputStream os = Files.newOutputStream(file); InputStream is = parseBody(r, InputStream.class)) { byte[] buffer = new byte[8 * 1024]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } sb.append(MSG.downloadedFile(filename)); } case QUIET: break; case HEADERS: sb.append(Json.make(parseHeaders(r)).toPrettyString()); break; default: throw new IllegalArgumentException(responseMode.name()); } refreshServerInfo(); return sb.toString(); } @Override public Resource getActiveResource() { return activeResource; } @Override public void setActiveResource(Resource resource) { this.activeResource = resource; } @Override public ContainerResource getActiveContainer() { return activeResource.findAncestor(ContainerResource.class); } @Override public Collection<String> getAvailableCaches(String container) { return availableCaches; } @Override public Collection<String> getAvailableContainers() { return availableContainers; } @Override public Collection<String> getAvailableCounters(String container) throws IOException { return parseBody(fetch(() -> client.counters()), List.class); } @Override public Collection<String> getAvailableCacheConfigurations(String container) { return availableConfigurations; } @Override public Collection<String> getAvailableSchemas(String container) throws IOException { TransformingIterable<Map<String, String>, String> i = new TransformingIterable<>(getCacheKeys(container, PROTOBUF_METADATA_CACHE_NAME), SINGLETON_MAP_VALUE); List<String> list = new ArrayList<>(); i.forEach(list::add); return list; } @Override public Collection<String> getAvailableServers(String container) throws IOException { return (List<String>) parseBody(fetch(() -> client.cacheManager(container).info()), Map.class).get("cluster_members"); } @Override public Collection<String> getAvailableTasks(String container) throws IOException { List<Map<String, String>> list = parseBody(fetch(() -> client.tasks().list(ResultType.ALL)), List.class); return list.stream().map(i -> i.get("name")).collect(Collectors.toList()); } @Override public Collection<String> getAvailableSites(String container, String cache) throws IOException { Map<String, String> sites = parseBody(fetch(() -> client.cache(cache).xsiteBackups()), Map.class); return sites == null ? Collections.emptyList() : sites.keySet(); } @Override public Iterable<Map<String, String>> getCacheKeys(String container, String cache) throws IOException { return new JsonReaderIterable(parseBody(fetch(() -> client.cache(cache).keys()), InputStream.class)); } @Override public Iterable<Map<String, String>> getCacheKeys(String container, String cache, int limit) throws IOException { return new JsonReaderIterable(parseBody(fetch(() -> client.cache(cache).keys(limit)), InputStream.class)); } @Override public Iterable<Map<String, String>> getCacheEntries(String container, String cache, int limit, boolean metadata) throws IOException { return new JsonReaderIterable(parseBody(fetch(() -> client.cache(cache).entries(limit, metadata)), InputStream.class)); } @Override public Iterable<String> getCounterValue(String container, String counter) throws IOException { return Collections.singletonList(parseBody(fetch(() -> client.counter(counter).get()), String.class)); } @Override public Collection<String> getRoles() throws IOException { return parseBody(fetch(() -> client.security().listRoles(null)), List.class); } @Override public boolean isConnected() { return connected; } @Override public String describeContainer(String container) throws IOException { return parseBody(fetch(() -> client.cacheManager(container).info()), String.class); } @Override public String describeCache(String container, String cache) throws IOException { return parseBody(fetch(() -> client.cache(cache).configuration()), String.class); } @Override public String describeKey(String container, String cache, String key) throws IOException { Map<String, List<String>> headers = parseHeaders(fetch(() -> client.cache(cache).head(key))); return Json.make(headers).toPrettyString(); } @Override public String describeConfiguration(String container, String counter) { return null; // TODO } @Override public String describeCounter(String container, String counter) throws IOException { return parseBody(fetch(() -> client.counter(counter).configuration()), String.class); } @Override public String describeTask(String container, String taskName) throws IOException { List<Map<String, Object>> list = parseBody(fetch(() -> client.tasks().list(ResultType.ALL)), List.class); Optional<Map<String, Object>> task = list.stream().filter(i -> taskName.equals(i.get("name"))).findFirst(); return task.map(Object::toString).orElseThrow(() -> MSG.noSuchResource(taskName)); } @Override public Collection<String> getAvailableLogAppenders() throws IOException { Map<String, Object> map = parseBody(fetch(() -> client.server().logging().listAppenders()), Map.class); return map.keySet(); } @Override public Collection<String> getAvailableLoggers() throws IOException { List<Map<String, Object>> list = parseBody(fetch(() -> client.server().logging().listLoggers()), List.class); return list.stream().map(i -> i.get("name").toString()).collect(Collectors.toList()); } @Override public Collection<String> getClusterNodes() { return clusterMembers; } @Override public String getConnectionInfo() { return serverInfo; } @Override public String getServerVersion() { return serverVersion; } @Override public Collection<String> getBackupNames(String container) throws IOException { return parseBody(fetch(client.cacheManager(container).getBackupNames()), List.class); } @Override public Collection<String> getSitesView() { return sitesView; } @Override public String getLocalSiteName() { return localSite; } @Override public boolean isRelayNode() { return relayNode; } @Override public Collection<String> getRelayNodes() { return relayNodes; } @Override public Collection<String> getConnectorNames() throws IOException { return parseBody(fetch(client.server().connectorNames()), List.class); } @Override public Collection<String> getDataSourceNames() throws IOException { return parseBody(fetch(client.server().dataSourceNames()), List.class); } @Override public Collection<String> getCacheConfigurationAttributes(String name) { try { return name == null ? Collections.emptyList() : parseBody(fetch(client.cache(name).configurationAttributes()), List.class); } catch (IOException e) { return Collections.emptyList(); } } @Override public void refreshServerInfo() throws IOException { try { ContainerResource container = getActiveContainer(); String containerName = container.getName(); Map cacheManagerInfo = parseBody(fetch(() -> client.cacheManager(containerName).info()), Map.class); List<Map<String, Object>> definedCaches = (List<Map<String, Object>>) cacheManagerInfo.get("defined_caches"); availableCaches = new ArrayList<>(); definedCaches.forEach(m -> availableCaches.add((String) m.get("name"))); availableCaches.remove(PROTOBUF_METADATA_CACHE_NAME); List configurationList = parseBody(fetch(() -> client.cacheManager(containerName).cacheConfigurations()), List.class); availableConfigurations = new ArrayList<>(configurationList.size()); for (Object item : configurationList) { availableConfigurations.add(((Map<String, String>) item).get("name")); } String nodeAddress = (String) cacheManagerInfo.get("node_address"); String clusterName = (String) cacheManagerInfo.get("cluster_name"); localSite = (String) cacheManagerInfo.get("local_site"); sitesView = new ArrayList<>((Collection<String>) cacheManagerInfo.get("sites_view")); Collections.sort(sitesView); relayNode = cacheManagerInfo.containsKey("relay_node") ? (boolean) cacheManagerInfo.get("relay_node") : false; relayNodes = (List<String>) cacheManagerInfo.get("relay_nodes_address"); clusterMembers = (Collection<String>) cacheManagerInfo.get("cluster_members"); if (nodeAddress != null) { serverInfo = nodeAddress + "@" + clusterName; } else { ServerConfiguration serverConfiguration = client.getConfiguration().servers().get(0); serverInfo = serverConfiguration.host() + ":" + serverConfiguration.port(); } } catch (IllegalStateException e) { // Cannot refresh if there is no container selected } } @Override public String getUsername() { return builder.build().security().authentication().username(); } RestClientConfigurationBuilder getBuilder() { return builder; } public String toString() { return serverInfo; } }
17,295
35.489451
163
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/connection/rest/RestConnector.java
package org.infinispan.cli.connection.rest; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.infinispan.cli.connection.Connection; import org.infinispan.cli.connection.Connector; import org.infinispan.cli.impl.SSLContextSettings; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.client.rest.configuration.SslConfigurationBuilder; import org.infinispan.commons.util.Version; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices public class RestConnector implements Connector { private final Pattern HOST_PORT = Pattern.compile("(\\[[0-9A-Fa-f:]+\\]|[^:/?#]*)(?::(\\d*))"); @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(URLDecoder.decode(split[0], StandardCharsets.UTF_8.name())); if (split.length == 2) { builder.security().authentication().password(URLDecoder.decode(split[1], StandardCharsets.UTF_8.name())); } } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } builder.header("User-Agent", Version.getBrandName()+" CLI " + Version.getBrandVersion()); return new RestConnection(builder); } catch (Throwable e) { return null; } } }
3,096
42.619718
126
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/printers/PrettyPrinter.java
package org.infinispan.cli.printers; import java.io.Closeable; import java.util.Iterator; import java.util.Map; import org.aesh.command.shell.Shell; /** * @since 14.0 **/ public interface PrettyPrinter extends Closeable { enum PrettyPrintMode { TABLE, JSON, CSV } static PrettyPrinter forMode(PrettyPrintMode mode, Shell shell, PrettyRowPrinter rowPrinter) { switch (mode) { case TABLE: return new TablePrettyPrinter(shell, rowPrinter); case JSON: return new JsonPrettyPrinter(shell); case CSV: return new CsvPrettyPrinter(shell, rowPrinter); default: throw new IllegalArgumentException(mode.name()); } } void printItem(Map<String, String> item); default void print(Iterator<String> it) { it.forEachRemaining(i -> printItem(Map.of("", i))); } default void print(Iterable<Map<String, String>> it) { it.forEach(this::printItem); } }
994
22.139535
97
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/printers/JsonPrettyPrinter.java
package org.infinispan.cli.printers; import java.io.IOException; import java.util.Map; import org.aesh.command.shell.Shell; /** * @since 14.0 **/ public class JsonPrettyPrinter extends AbstractPrettyPrinter { private boolean commaRow; protected JsonPrettyPrinter(Shell shell) { super(shell); shell.writeln("["); } @Override public void printItem(Map<String, String> item) { if (commaRow) { shell.writeln(","); } else { commaRow = true; } boolean simple = item.size() == 1; if (!simple) { shell.write("{"); } boolean commaCol = false; for (Map.Entry<String, String> column : item.entrySet()) { if (commaCol) { shell.writeln(", "); } else { commaCol = true; } if (!simple) { shell.write(column.getKey()); shell.write(": "); } shell.write('"'); shell.write(column.getValue()); shell.write('"'); } if (!simple) { shell.write("}"); } } @Override public void close() throws IOException { shell.writeln(""); shell.writeln("]"); } }
1,206
20.553571
64
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/printers/TablePrettyPrinter.java
package org.infinispan.cli.printers; import java.io.IOException; import java.util.Map; import org.aesh.command.shell.Shell; /** * @since 14.0 **/ public class TablePrettyPrinter implements PrettyPrinter { private final Shell shell; private final PrettyRowPrinter rowPrinter; private boolean header = true; public TablePrettyPrinter(Shell shell, PrettyRowPrinter rowPrinter) { this.shell = shell; this.rowPrinter = rowPrinter; } @Override public void printItem(Map<String, String> item) { int cols = item.size(); if (rowPrinter.showHeader() && header) { for (int row = 0; row < 2; row++) { for (int col = 0; col < cols; col++) { if (col > 0) { shell.write(row == 0 ? "|" : "+"); } if (row == 0) { String format = "%-" + rowPrinter.columnWidth(col) + "s"; shell.write(String.format(format, rowPrinter.columnHeader(col))); } else { shell.write("-".repeat(rowPrinter.columnWidth(col))); } } shell.writeln(""); } header = false; } int[] colsWrap = new int[cols]; int remaining = cols; do { int i = 0; for (Map.Entry<String, String> col : item.entrySet()) { if (i > 0) { shell.write("|"); } String v = rowPrinter.formatColumn(i, col.getValue()); int width = rowPrinter.columnWidth(i); String format = "%-" + width + "s"; if (i < 4) { int offset = colsWrap[i]; if (offset < 0) { // We've already printed the whole value v = ""; } else { int lf = v.indexOf("\n", offset) - offset; if (lf < 0 || lf > width) { // No LFs inside the range if (v.length() - offset <= width) { // The rest of the value fits v = v.substring(offset); colsWrap[i] = -1; remaining--; } else { // Just print characters that fit skipping any that we've already printed v = v.substring(offset, offset + width); colsWrap[i] += width; } } else { // LF inside the range, just print up to it v = v.substring(offset, offset + lf); colsWrap[i] += lf + 1; } } shell.write(String.format(format, v)); } else { if (colsWrap[i] == 0) { shell.write(String.format(format, v)); colsWrap[i] = -1; remaining--; } else { shell.write(" ".repeat(width)); } } i++; } shell.writeln(""); } while (remaining > 0); } @Override public void close() throws IOException { } }
3,191
31.571429
97
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/printers/PrettyRowPrinter.java
package org.infinispan.cli.printers; /** * @since 14.0 **/ public interface PrettyRowPrinter { boolean showHeader(); String columnHeader(int column); int columnWidth(int column); String formatColumn(int column, String value); }
247
14.5
49
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/printers/CacheEntryRowPrinter.java
package org.infinispan.cli.printers; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.Duration; /** * @since 14.0 **/ public class CacheEntryRowPrinter implements PrettyRowPrinter { private final DateFormat df; private final int[] colWidths; public CacheEntryRowPrinter(int width, int columns) { this.df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); this.colWidths = new int[columns]; switch (columns) { case 1: // Key colWidths[0] = width; break; case 2: // Key, Value if (width <= 20) { // Not enough width, ignore it colWidths[0] = 6; colWidths[1] = 13; } else { colWidths[0] = Math.min(width / 3, 15); colWidths[1] = width - colWidths[0] - 1; } break; case 7: // Key, Value, Metadata if (width <= 80) { // Not enough width, ignore it colWidths[0] = 6; colWidths[1] = 13; } else { colWidths[0] = Math.min((width - 75) / 3, 15); colWidths[1] = width - 75 - colWidths[0]; } colWidths[2] = 6; colWidths[3] = 6; colWidths[4] = 19; colWidths[5] = 19; colWidths[6] = 19; break; default: throw new IllegalArgumentException("Illegal number of columns: " + columns); } } @Override public boolean showHeader() { return true; } @Override public String columnHeader(int column) { switch (column) { case 0: return "Key"; case 1: return "Value"; case 2: return "TTL"; case 3: return "Idle"; case 4: return "Created"; case 5: return "LastUsed"; case 6: return "Expires"; default: throw new IllegalArgumentException(); } } @Override public int columnWidth(int column) { return colWidths[column]; } @Override public String formatColumn(int column, String value) { if (column < 2) { return value; // Key, value: return as-is } else { long l = Long.parseLong(value); if (l < 0) { // Immortal entry return "\u221E"; } else { if (column < 4) { // TTL, MaxIdle: return as a duration return Duration.ofSeconds(l).toString().substring(2).toLowerCase(); } else { // Create, last used, expires: return as date/time return df.format(l); } } } } }
2,754
26.009804
88
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/printers/CsvPrettyPrinter.java
package org.infinispan.cli.printers; import java.io.IOException; import java.util.Map; import org.aesh.command.shell.Shell; /** * @since 14.0 **/ public class CsvPrettyPrinter extends AbstractPrettyPrinter { private final PrettyRowPrinter rowPrinter; private boolean header = true; protected CsvPrettyPrinter(Shell shell, PrettyRowPrinter rowPrinter) { super(shell); this.rowPrinter = rowPrinter; } @Override public void printItem(Map<String, String> item) { if (header) { shell.write("# "); boolean comma = false; for (int i = 0; i < item.size(); i++) { if (comma) { shell.write(","); } else { comma = true; } shell.write(rowPrinter.columnHeader(i)); } shell.writeln(""); header = false; } boolean comma = false; for (Map.Entry<String, String> column : item.entrySet()) { if (comma) { shell.write(","); } else { comma = true; } shell.write('"'); shell.write(column.getValue().replace("\"","\\\"")); shell.write('"'); } shell.writeln(""); } @Override public void close() throws IOException { } }
1,292
22.944444
73
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/printers/AbstractPrettyPrinter.java
package org.infinispan.cli.printers; import org.aesh.command.shell.Shell; /** * @since 14.0 **/ public abstract class AbstractPrettyPrinter implements PrettyPrinter { protected final Shell shell; protected AbstractPrettyPrinter(Shell shell) { this.shell = shell; } }
287
18.2
70
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/printers/DefaultRowPrinter.java
package org.infinispan.cli.printers; /** * @since 14.0 **/ public class DefaultRowPrinter implements PrettyRowPrinter { private final int[] colWidths; public DefaultRowPrinter(int width, int columns) { this.colWidths = new int[columns]; int effectiveWidth = width - columns + 1; int columnWidth = effectiveWidth / columns; for (int i = 0; i < columns - 1; i++) { colWidths[i] = columnWidth; effectiveWidth -= columnWidth; } // The last column gets the remaining width colWidths[columns - 1] = effectiveWidth; } @Override public boolean showHeader() { return false; } @Override public String columnHeader(int column) { return ""; // TODO } @Override public int columnWidth(int column) { return colWidths[column]; } @Override public String formatColumn(int column, String value) { return value; } }
934
21.804878
60
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/AeshDelegatingShell.java
package org.infinispan.cli.impl; import org.aesh.readline.ShellImpl; import org.aesh.terminal.Connection; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ public class AeshDelegatingShell extends ShellImpl { private final Connection connection; public AeshDelegatingShell(Connection connection) { super(connection); this.connection = connection; } public Connection getConnection() { return connection; } }
477
20.727273
57
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/CliMode.java
package org.infinispan.cli.impl; public enum CliMode { INTERACTIVE, BATCH, KUBERNETES }
98
11.375
32
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/CliCommandNotFoundHandler.java
package org.infinispan.cli.impl; import org.aesh.command.CommandNotFoundHandler; import org.aesh.command.shell.Shell; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class CliCommandNotFoundHandler implements CommandNotFoundHandler { @Override public void handleCommandNotFound(String line, Shell shell) { shell.writeln("Command not found"); } }
404
24.3125
74
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/CliManProvider.java
package org.infinispan.cli.impl; import java.io.InputStream; import org.aesh.command.settings.ManProvider; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class CliManProvider implements ManProvider { @Override public InputStream getManualDocument(String commandName) { return this.getClass().getClassLoader().getResourceAsStream("help/" + commandName + ".adoc"); } }
427
24.176471
99
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/CliRuntimeRunner.java
package org.infinispan.cli.impl; import java.io.IOException; import org.aesh.command.CommandException; import org.aesh.command.CommandNotFoundException; import org.aesh.command.CommandRuntime; import org.aesh.command.parser.CommandLineParserException; import org.aesh.command.validator.CommandValidatorException; import org.aesh.command.validator.OptionValidatorException; public class CliRuntimeRunner { private final String commandName; private final CommandRuntime runtime; private String[] args; public CliRuntimeRunner(String commandName, CommandRuntime runtime) { this.commandName = commandName; this.runtime = runtime; } public CliRuntimeRunner args(String[] args) { this.args = args; return this; } public int execute() { StringBuilder sb = new StringBuilder(commandName); if (args.length > 0) { sb.append(" "); if (args.length == 1) { sb.append(args[0]); } else { for (String arg : args) { if (arg.indexOf(' ') >= 0) { sb.append('"').append(arg).append("\" "); } else { sb.append(arg).append(' '); } } } } try { runtime.executeCommand(sb.toString()); return ExitCodeResultHandler.exitCode; } catch (CommandNotFoundException e) { System.err.println("Command not found: " + sb); return 1; } catch (CommandException | CommandLineParserException | CommandValidatorException | OptionValidatorException e) { showHelpIfNeeded(runtime, commandName, e); return 1; } catch (InterruptedException | IOException e) { System.err.println(e.getMessage()); return 1; } } private static void showHelpIfNeeded(CommandRuntime runtime, String commandName, Exception e) { if (e != null) { System.err.println(e.getMessage()); } System.err.println(runtime.commandInfo(commandName)); } }
2,036
30.338462
120
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/ContextImpl.java
package org.infinispan.cli.impl; import java.io.Closeable; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.file.AccessDeniedException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Properties; import java.util.Set; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.invocation.CommandInvocation; import org.aesh.command.registry.CommandRegistry; import org.aesh.command.shell.Shell; import org.aesh.io.FileResource; import org.aesh.readline.AeshContext; import org.aesh.readline.Prompt; import org.aesh.readline.ReadlineConsole; import org.aesh.terminal.utils.ANSI; import org.infinispan.cli.Context; import org.infinispan.cli.connection.Connection; import org.infinispan.cli.connection.ConnectionFactory; import org.infinispan.cli.logging.Messages; import org.infinispan.cli.resources.CacheKeyResource; import org.infinispan.cli.resources.Resource; import org.infinispan.cli.util.SystemUtils; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.util.Util; import org.infinispan.commons.util.Version; /** * ContextImpl. * * @author Tristan Tarrant * @since 5.2 */ public class ContextImpl implements Context, AeshContext, Closeable { private static final String CONFIG_FILE = "cli.properties"; private Connection connection; private final Properties properties; private org.aesh.io.Resource cwd; private ReadlineConsole console; private SSLContextSettings sslContext; private CommandRegistry<? extends CommandInvocation> registry; private final Path configPath; public ContextImpl(Properties defaults) { this.properties = new Properties(defaults); String userDir = properties.getProperty("user.dir"); cwd = userDir != null ? new FileResource(userDir) : null; String cliDir = properties.getProperty("cli.dir"); if (cliDir == null) { cliDir = System.getenv("ISPN_CLI_DIR"); } if (cliDir != null) { configPath = Paths.get(cliDir); } else { configPath = Paths.get(SystemUtils.getAppConfigFolder(Version.getBrandName().toLowerCase().replace(' ', '_'))); } Path configFile = configPath.resolve(CONFIG_FILE); if (Files.exists(configFile)) { try (Reader r = Files.newBufferedReader(configFile)) { properties.load(r); } catch (IOException e) { System.err.println(Messages.MSG.configLoadFailed(configFile.toString())); } } } @Override public Path getConfigPath() { return configPath; } @Override public boolean isConnected() { return connection != null && connection.isConnected(); } @Override public void setProperty(String key, String value) { if (value == null) { properties.remove(key); } else { properties.setProperty(key, value); } } @Override public String getProperty(String key) { return properties.getProperty(key); } @Override public String getProperty(Property property) { return properties.getProperty(property.propertyName()); } @Override public Properties getProperties() { return properties; } @Override public void resetProperties() { properties.clear(); } @Override public void saveProperties() { Path configFile = configPath.resolve(CONFIG_FILE); try { Files.createDirectories(configPath); try (Writer w = Files.newBufferedWriter(configFile)) { properties.store(w, null); } } catch (IOException e) { System.err.println(Messages.MSG.configStoreFailed(configFile.toString())); } } @Override public void setSslContext(SSLContextSettings sslContext) { this.sslContext = sslContext; } @Override public Connection connect(Shell shell, String connectionString) { disconnect(); connection = ConnectionFactory.getConnection(connectionString, sslContext); // Attempt a connection. If we receive an exception we might need credentials try { connection.connect(); } catch (AccessDeniedException accessDenied) { try { Util.close(connection); String username = connection.getUsername(); String password = null; if (shell != null) { if (username == null) { username = shell.readLine(Messages.MSG.username()); } password = username.isEmpty() ? "" : shell.readLine(new Prompt(Messages.MSG.password(), '*')); } else { java.io.Console sysConsole = System.console(); if (sysConsole != null) { if (username == null) { username = sysConsole.readLine(Messages.MSG.username()); } password = username.isEmpty() ? "" : new String(sysConsole.readPassword(Messages.MSG.password())); } else { } } connection.connect(username, password); } catch (Exception e) { disconnect(); showError(shell, e); } } catch (IOException e) { disconnect(); showError(shell, e); } refreshPrompt(); return connection; } private void showError(Shell shell, Throwable t) { if (shell != null) { shell.writeln(t.getMessage()); } else { System.err.println(t.getMessage()); } } @Override public Connection connect(Shell shell, String connectionString, String username, String password) { disconnect(); connection = ConnectionFactory.getConnection(connectionString, sslContext); try { connection.connect(username, password); } catch (IOException e) { disconnect(); if (shell != null) { shell.writeln(ANSI.RED_TEXT + e.getLocalizedMessage() + ANSI.DEFAULT_TEXT); } else { System.err.println(e.getLocalizedMessage()); } } refreshPrompt(); return connection; } private void buildPrompt(Resource resource, StringBuilder builder) { if (resource != null) { if (resource.getParent() != null) { buildPrompt(resource.getParent(), builder); } builder.append("/").append(resource.getName()); } } public void refreshPrompt() { if (console != null) { if (connection != null) { StringBuilder prompt = new StringBuilder(); prompt.append("[").append(ANSI.GREEN_TEXT).append(connection.getConnectionInfo()).append(ANSI.DEFAULT_TEXT); buildPrompt(connection.getActiveResource(), prompt); prompt.append("]> "); console.setPrompt(prompt.toString()); } else { console.setPrompt("[" + ANSI.YELLOW_TEXT + "disconnected" + ANSI.DEFAULT_TEXT + "]> "); } } } @Override public CommandResult changeResource(Class<? extends Resource> fromResource, String resourceType, String name) throws CommandException { try { Resource resource; if (fromResource != null) { resource = connection.getActiveResource().findAncestor(fromResource).getChild(resourceType, name); } else { resource = connection.getActiveResource().getResource(name); } if (!(resource instanceof CacheKeyResource)) { connection.setActiveResource(resource); } refreshPrompt(); return CommandResult.SUCCESS; } catch (IOException e) { throw new CommandException(e); } } @Override public void disconnect() { Util.close(connection); connection = null; refreshPrompt(); } @Override public MediaType getEncoding() { return connection.getEncoding(); } @Override public void setEncoding(MediaType encoding) { connection.setEncoding(encoding); } @Override public void setConsole(ReadlineConsole console) { this.console = console; refreshPrompt(); } @Override public CommandRegistry<? extends CommandInvocation> getRegistry() { return registry; } @Override public void setRegistry(CommandRegistry<? extends CommandInvocation> registry) { this.registry = registry; } @Override public Connection getConnection() { return connection; } @Override public org.aesh.io.Resource getCurrentWorkingDirectory() { return cwd; } @Override public void setCurrentWorkingDirectory(org.aesh.io.Resource cwd) { this.cwd = cwd; } @Override public Set<String> exportedVariableNames() { return Collections.emptySet(); } @Override public String exportedVariable(String key) { return null; } @Override public void close() { disconnect(); } }
9,057
28.698361
138
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/CliAliasManager.java
package org.infinispan.cli.impl; import java.io.File; import java.io.IOException; import org.aesh.command.registry.CommandRegistry; import org.aesh.readline.alias.AliasManager; public class CliAliasManager extends AliasManager { private final CommandRegistry registry; public CliAliasManager(File aliasFile, boolean persistAlias, CommandRegistry registry) throws IOException { super(aliasFile, persistAlias); this.registry = registry; } @Override public boolean verifyNoNewAliasConflict(String aliasName) { if(registry != null && registry.contains(aliasName)) return false; else return true; } }
717
23.758621
73
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/ContextAwareCommandInvocationProvider.java
package org.infinispan.cli.impl; import java.util.Objects; import org.aesh.command.invocation.CommandInvocation; import org.aesh.command.invocation.CommandInvocationProvider; import org.infinispan.cli.Context; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class ContextAwareCommandInvocationProvider implements CommandInvocationProvider { private final Context context; public ContextAwareCommandInvocationProvider(Context context) { Objects.requireNonNull(context); this.context = context; } @Override public CommandInvocation enhanceCommandInvocation(CommandInvocation commandInvocation) { return new ContextAwareCommandInvocation(commandInvocation, context); } }
750
27.884615
91
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/ExitCodeResultHandler.java
package org.infinispan.cli.impl; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.result.ResultHandler; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.1 **/ public class ExitCodeResultHandler implements ResultHandler { static int exitCode; @Override public void onSuccess() { exitCode = 0; } @Override public void onFailure(CommandResult result) { exitCode = 1; } @Override public void onValidationFailure(CommandResult result, Exception exception) { exitCode = 1; } @Override public void onExecutionFailure(CommandResult result, CommandException exception) { exitCode = 1; } }
732
20.558824
85
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/KubeShell.java
package org.infinispan.cli.impl; import java.io.Console; import java.io.IOException; import java.nio.charset.Charset; import org.aesh.readline.Prompt; import org.aesh.readline.terminal.Key; import org.aesh.readline.tty.terminal.TerminalConnection; import org.aesh.readline.util.Parser; import org.aesh.terminal.utils.ANSI; public class KubeShell extends AeshDelegatingShell { public KubeShell() throws IOException { super(new TerminalConnection(Charset.defaultCharset(), System.in, System.out)); } @Override public void write(String out, boolean paging) { System.out.print(out); } @Override public void writeln(String out, boolean paging) { System.out.println(out); } @Override public void write(int[] out) { Console console = System.console(); if (console != null) { console.writer().write(Parser.fromCodePoints(out)); console.writer().flush(); } } @Override public void write(char out) { System.out.println(out); } @Override public String readLine() { return readLine(new Prompt()); } @Override public String readLine(Prompt prompt) { Console console = System.console(); if (console != null) { if (prompt != null) { console.writer().print(Parser.fromCodePoints(prompt.getANSI())); console.writer().flush(); if (prompt.isMasking()) { return new String(console.readPassword()); } } return console.readLine(); } return null; } @Override public Key read() { return read(null); } @Override public Key read(Prompt prompt) { Console console = System.console(); if (console != null) { try { if (prompt != null) { console.writer().print(Parser.fromCodePoints(prompt.getANSI())); console.writer().flush(); } int input = console.reader().read(); return Key.getKey(new int[]{input}); } catch (IOException e) { e.printStackTrace(); } } return null; } @Override public void clear() { Console console = System.console(); if (console != null) { console.writer().write(Parser.fromCodePoints(ANSI.CLEAR_SCREEN)); } } }
2,357
23.821053
85
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/ShellOutputStreamAdapter.java
package org.infinispan.cli.impl; import java.io.OutputStream; import org.aesh.command.shell.Shell; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ public class ShellOutputStreamAdapter extends OutputStream { final Shell shell; public ShellOutputStreamAdapter(Shell shell) { this.shell = shell; } @Override public void write(int b) { shell.write(Character.toString((char)b)); } }
448
18.521739
60
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/ContextAwareQuitHandler.java
package org.infinispan.cli.impl; import org.aesh.command.settings.QuitHandler; import org.infinispan.cli.Context; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class ContextAwareQuitHandler implements QuitHandler { private final Context context; public ContextAwareQuitHandler(Context context) { this.context = context; } @Override public void quit() { context.disconnect(); } }
456
19.772727
61
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/CliShell.java
package org.infinispan.cli.impl; import java.io.IOException; import java.nio.charset.Charset; import org.aesh.readline.tty.terminal.TerminalConnection; /** * @since 14.0 **/ public class CliShell extends AeshDelegatingShell { public CliShell() throws IOException { super(new TerminalConnection(Charset.defaultCharset(), System.in, System.out)); } }
366
21.9375
85
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/SSLContextSettings.java
package org.infinispan.cli.impl; import java.security.GeneralSecurityException; import java.security.SecureRandom; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class SSLContextSettings { private final SSLContext sslContext; private final KeyManager[] keyManagers; private final TrustManager[] trustManagers; private final SecureRandom random; private final HostnameVerifier hostnameVerifier; private SSLContextSettings(String protocol, KeyManager[] keyManagers, TrustManager[] trustManagers, SecureRandom random, HostnameVerifier hostnameVerifier) throws GeneralSecurityException { this.sslContext = SSLContext.getInstance(protocol); this.keyManagers = keyManagers; this.trustManagers = trustManagers; this.random = random; this.hostnameVerifier = hostnameVerifier; sslContext.init(keyManagers, trustManagers, random); } public SSLContext getSslContext() { return sslContext; } public KeyManager[] getKeyManagers() { return keyManagers; } public TrustManager[] getTrustManagers() { return trustManagers; } public SecureRandom getRandom() { return random; } public HostnameVerifier getHostnameVerifier() { return hostnameVerifier; } public static SSLContextSettings getInstance(String protocol, KeyManager[] keyManagers, TrustManager[] trustManagers, SecureRandom random, HostnameVerifier hostnameVerifier) { try { return new SSLContextSettings(protocol, keyManagers, trustManagers, random, hostnameVerifier); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } }
1,839
29.666667
192
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/KubernetesContext.java
package org.infinispan.cli.impl; import java.util.Properties; import org.infinispan.cli.logging.Messages; import org.infinispan.commons.util.Util; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientBuilder; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ public class KubernetesContext extends ContextImpl { private final KubernetesClient kubernetesClient; public KubernetesContext(Properties defaults, KubernetesClient client) { super(defaults); this.kubernetesClient = client; } public KubernetesContext(Properties defaults) { this(defaults, new KubernetesClientBuilder().build()); } public static KubernetesClient getClient(ContextAwareCommandInvocation invocation) { if (invocation.getContext() instanceof KubernetesContext) { return ((KubernetesContext)invocation.getContext()).kubernetesClient; } else { throw Messages.MSG.noKubernetes(); } } public KubernetesClient getKubernetesClient() { return kubernetesClient; } @Override public void disconnect() { Util.close(kubernetesClient); super.disconnect(); } }
1,222
25.586957
87
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/StoreMigratorHelper.java
package org.infinispan.cli.impl; import java.util.Properties; import org.infinispan.tools.store.migrator.StoreMigrator; /** * @since 15.0 **/ public class StoreMigratorHelper { public static void run(Properties props, boolean verbose) throws Exception { new StoreMigrator(props).run(verbose); } }
314
20
79
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/ContextAwareCommandInvocation.java
package org.infinispan.cli.impl; import java.io.IOException; import java.io.PrintStream; import org.aesh.command.CommandException; import org.aesh.command.CommandNotFoundException; import org.aesh.command.Executor; import org.aesh.command.invocation.CommandInvocation; import org.aesh.command.invocation.CommandInvocationConfiguration; import org.aesh.command.parser.CommandLineParserException; import org.aesh.command.shell.Shell; import org.aesh.command.validator.CommandValidatorException; import org.aesh.command.validator.OptionValidatorException; import org.aesh.readline.Prompt; import org.aesh.readline.action.KeyAction; import org.infinispan.cli.Context; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class ContextAwareCommandInvocation implements CommandInvocation<ContextAwareCommandInvocation> { private final CommandInvocation invocation; private final Context context; private final Shell shell; public ContextAwareCommandInvocation(CommandInvocation commandInvocation, Context context) { this.invocation = commandInvocation; this.context = context; this.shell = commandInvocation.getShell(); } @Override public Shell getShell() { return shell; } @Override public void setPrompt(Prompt prompt) { invocation.setPrompt(prompt); } @Override public Prompt getPrompt() { return invocation.getPrompt(); } @Override public String getHelpInfo(String commandName) { return invocation.getHelpInfo(commandName); } @Override public String getHelpInfo() { return invocation.getHelpInfo(); } @Override public void stop() { invocation.stop(); } @Override public CommandInvocationConfiguration getConfiguration() { return invocation.getConfiguration(); } @Override public KeyAction input() throws InterruptedException { return invocation.input(); } @Override public String inputLine() throws InterruptedException { return invocation.inputLine(); } @Override public String inputLine(Prompt prompt) throws InterruptedException { return invocation.inputLine(prompt); } @Override public void executeCommand(String input) throws CommandNotFoundException, CommandLineParserException, OptionValidatorException, CommandValidatorException, CommandException, InterruptedException, IOException { invocation.executeCommand(input); } @Override public Executor<ContextAwareCommandInvocation> buildExecutor(String line) throws CommandNotFoundException, CommandLineParserException, OptionValidatorException, CommandValidatorException, IOException { return invocation.buildExecutor(line); } @Override public void print(String msg) { invocation.print(msg); } @Override public void println(String msg) { invocation.println(msg); } public void printf(String format, Object... args) { invocation.print(String.format(format, args)); } @Override public void print(String msg, boolean paging) { invocation.print(msg, paging); } @Override public void println(String msg, boolean paging) { invocation.println(msg, paging); } public Context getContext() { return context; } public PrintStream getShellOutput() { return System.out; } public PrintStream getShellError() { return System.err; } public String getPasswordInteractively(String prompt, String confirmPrompt) throws InterruptedException { String password = null; while (password == null || password.isEmpty()) { password = shell.readLine(new Prompt(prompt, '*')); } if (confirmPrompt != null) { String confirm = null; while (confirm == null || !confirm.equals(password)) { confirm = shell.readLine(new Prompt(confirmPrompt, '*')); } } return password; } }
3,964
26.534722
211
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/StreamShell.java
package org.infinispan.cli.impl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import org.aesh.command.shell.Shell; import org.aesh.readline.Prompt; import org.aesh.readline.terminal.Key; import org.aesh.readline.util.Parser; import org.aesh.terminal.tty.Size; import org.infinispan.commons.util.Util; /** * @since 14.0 **/ public class StreamShell implements Shell { private final BufferedReader in; private final PrintStream out; public StreamShell() { this(System.in, System.out); } public StreamShell(InputStream in, PrintStream out) { this.in = new BufferedReader(new InputStreamReader(in)); this.out = out; } @Override public void write(String msg, boolean paging) { out.print(msg); } @Override public void writeln(String msg, boolean paging) { out.println(msg); } @Override public void write(int[] cp) { out.print(Parser.fromCodePoints(cp)); out.flush(); } @Override public void write(char c) { out.print(c); } @Override public String readLine() throws InterruptedException { try { String line = in.readLine(); if (line == null) { Util.close(in); } return line; } catch (IOException e) { return null; } } @Override public String readLine(Prompt prompt) throws InterruptedException { return readLine(); } @Override public Key read() throws InterruptedException { try { int input = in.read(); return Key.getKey(new int[]{input}); } catch (IOException e) { throw new RuntimeException(e); } } @Override public Key read(Prompt prompt) throws InterruptedException { return read(); } @Override public boolean enableAlternateBuffer() { return false; } @Override public boolean enableMainBuffer() { return false; } @Override public Size size() { return new Size(0, 0); } @Override public void clear() { } }
2,151
19.495238
70
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/impl/PromptBuilder.java
package org.infinispan.cli.impl; import java.text.SimpleDateFormat; import java.util.Date; import org.aesh.readline.terminal.formatting.Color; import org.aesh.terminal.utils.ANSI; import org.infinispan.cli.Context; /** * @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * @author Mike Brock * @author Tristan Tarrant */ public class PromptBuilder { public static String promptExpressionParser(Context context, String input) { StringBuilder builder = new StringBuilder(); char[] expr = input.toCharArray(); Color c = null; int i = 0; int start = 0; for (; i < expr.length; i++) { switch (expr[i]) { case '$': builder.append(new String(expr, start, i - start)); start = ++i; while (i != expr.length && Character.isJavaIdentifierPart(expr[i]) && expr[i] != 27) { i++; } String var = new String(expr, start, i - start); String val = context.getProperty(var); if (val != null) { builder.append(val); } start = i; break; case '\\': if (i + 1 < expr.length) { /** * Handle escape codes here. */ switch (expr[++i]) { case '\\': builder.append(new String(expr, start, i - start - 1)); builder.append("\\"); start = i + 1; break; case 'w': builder.append(new String(expr, start, i - start - 1)); builder.append(context.getCurrentWorkingDirectory().getAbsolutePath()); start = i + 1; break; case 'W': builder.append(new String(expr, start, i - start - 1)); String v = context.getCurrentWorkingDirectory().getAbsolutePath(); builder.append(v.substring(v.lastIndexOf('/') + 1)); start = i + 1; break; case 'd': builder.append(new String(expr, start, i - start - 1)); builder.append(new SimpleDateFormat("EEE MMM dd").format(new Date())); start = i + 1; break; case 't': builder.append(new String(expr, start, i - start - 1)); builder.append(new SimpleDateFormat("HH:mm:ss").format(new Date())); start = i + 1; break; case 'T': builder.append(new String(expr, start, i - start - 1)); builder.append(new SimpleDateFormat("hh:mm:ss").format(new Date())); start = i + 1; break; case '@': builder.append(new String(expr, start, i - start - 1)); builder.append(new SimpleDateFormat("KK:mmaa").format(new Date())); start = i + 1; break; case '$': builder.append(new String(expr, start, i - start - 1)); builder.append("\\$"); start = i + 1; break; case 'r': builder.append(new String(expr, start, i - start - 1)); builder.append("\r"); start = i + 1; break; case 'n': builder.append(new String(expr, start, i - start - 1)); builder.append("\n"); start = i + 1; break; case 'c': if (i + 1 < expr.length) { switch (expr[++i]) { case '{': boolean nextNodeColor = false; builder.append(new String(expr, start, i - start - 2)); start = i; while (i < input.length() && input.charAt(i) != '}') i++; if (i == input.length() && input.charAt(i) != '}') { builder.append(new String(expr, start, i - start)); } else { String color = new String(expr, start + 1, i - start - 1); start = ++i; Capture: while (i < expr.length) { switch (expr[i]) { case '\\': if (i + 1 < expr.length && expr[i + 1] == 'c') { if ((i + 2 < expr.length) && expr[i + 2] == '{') { nextNodeColor = true; } break Capture; } default: i++; } } for (Color sc : Color.values()) { if (sc.name().equalsIgnoreCase(color.trim())) { c = sc; break; } } switch (c) { case RED: builder.append(ANSI.RED_TEXT); break; case BLUE: builder.append(ANSI.BLUE_TEXT); break; case CYAN: builder.append(ANSI.CYAN_TEXT); break; case GREEN: builder.append(ANSI.GREEN_TEXT); break; case YELLOW: builder.append(ANSI.YELLOW_TEXT); break; case WHITE: builder.append(ANSI.WHITE_TEXT); break; case MAGENTA: builder.append(ANSI.MAGENTA_TEXT); break; case BLACK: builder.append(ANSI.BLACK_TEXT); break; case DEFAULT: builder.append(ANSI.DEFAULT_TEXT); break; } builder.append(promptExpressionParser(context, new String(expr, start, i - start))); builder.append(ANSI.RESET); if (nextNodeColor) { start = i--; } else { start = i += 2; } } break; default: start = i += 2; } } } } } } if (start < expr.length && i > start) { builder.append(new String(expr, start, i - start)); } return builder.toString(); } }
8,570
43.640625
120
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/benchmark/HotRodBenchmark.java
package org.infinispan.cli.benchmark; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.commons.util.Util; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.infra.Blackhole; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ @State(Scope.Thread) public class HotRodBenchmark { RemoteCacheManager cm; RemoteCache cache; @Param("hotrod://127.0.0.1") public String uri; @Param("benchmark") public String cacheName; @Param("16") public int keySize; @Param("1000") public int valueSize; @Param("1000") public int keySetSize; byte[] value; List<byte[]> keySet; AtomicInteger nextIndex; @Setup public void setup() { cm = new RemoteCacheManager(uri); cache = cm.getCache(cacheName); if (cache == null) { throw new IllegalArgumentException("Could not find cache " + cacheName); } value = new byte[valueSize]; keySet = new ArrayList<>(keySetSize); Random r = new Random(17); // We always use the same seed to make things repeatable for (int i = 0; i < keySetSize; i++) { byte[] key = new byte[keySize]; r.nextBytes(key); keySet.add(key); cache.put(key, value); } nextIndex = new AtomicInteger(); } @Benchmark public void get(Blackhole bh) { bh.consume(cache.get(nextKey())); } @Benchmark public void put() { cache.put(nextKey(), value); } @TearDown public void teardown() { Util.close(cm); } private byte[] nextKey() { return keySet.get(nextIndex.getAndIncrement() % keySetSize); } }
2,070
23.364706
89
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/benchmark/BenchmarkOutputFormat.java
package org.infinispan.cli.benchmark; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.aesh.command.shell.Shell; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.results.BenchmarkResult; import org.openjdk.jmh.results.IterationResult; import org.openjdk.jmh.results.Result; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.results.format.ResultFormatFactory; import org.openjdk.jmh.results.format.ResultFormatType; import org.openjdk.jmh.runner.IterationType; import org.openjdk.jmh.runner.format.OutputFormat; import org.openjdk.jmh.runner.options.TimeValue; import org.openjdk.jmh.runner.options.VerboseMode; import org.openjdk.jmh.util.Utils; public class BenchmarkOutputFormat implements OutputFormat { final VerboseMode verbose; final Shell out; public BenchmarkOutputFormat(Shell out, VerboseMode verbose) { this.out = out; this.verbose = verbose; } @Override public void print(String s) { if (verbose != VerboseMode.SILENT) { out.write(s); } } @Override public void println(String s) { // Hack to filter out unwanted messages if (verbose != VerboseMode.SILENT && !s.contains("on-forked runs")) { out.writeln(s); } } @Override public void flush() { } @Override public void verbosePrintln(String s) { if (verbose == VerboseMode.EXTRA) { out.writeln(s); } } @Override public void write(int b) { out.write(new String(Character.toChars(b))); } @Override public void write(byte[] b) { // Unused } @Override public void close() { } @Override public void startBenchmark(BenchmarkParams params) { if (verbose == VerboseMode.SILENT) { return; } IterationParams warmup = params.getWarmup(); if (warmup.getCount() > 0) { out.writeln("# Warmup: " + warmup.getCount() + " iterations, " + warmup.getTime() + " each" + (warmup.getBatchSize() <= 1 ? "" : ", " + warmup.getBatchSize() + " calls per op")); } else { out.writeln("# Warmup: <none>"); } IterationParams measurement = params.getMeasurement(); if (measurement.getCount() > 0) { out.writeln("# Measurement: " + measurement.getCount() + " iterations, " + measurement.getTime() + " each" + (measurement.getBatchSize() <= 1 ? "" : ", " + measurement.getBatchSize() + " calls per op")); } else { out.writeln("# Measurement: <none>"); } TimeValue timeout = params.getTimeout(); boolean timeoutWarning = (timeout.convertTo(TimeUnit.NANOSECONDS) <= measurement.getTime().convertTo(TimeUnit.NANOSECONDS)) || (timeout.convertTo(TimeUnit.NANOSECONDS) <= warmup.getTime().convertTo(TimeUnit.NANOSECONDS)); out.writeln("# Timeout: " + timeout + " per iteration" + (timeoutWarning ? ", ***WARNING: The timeout might be too low!***" : "")); out.write("# Threads: " + params.getThreads() + " " + getThreadsString(params.getThreads())); if (!params.getThreadGroupLabels().isEmpty()) { int[] tg = params.getThreadGroups(); List<String> labels = new ArrayList<>(params.getThreadGroupLabels()); String[] ss = new String[tg.length]; for (int cnt = 0; cnt < tg.length; cnt++) { ss[cnt] = tg[cnt] + "x \"" + labels.get(cnt) + "\""; } int groupCount = params.getThreads() / Utils.sum(tg); out.write(" (" + groupCount + " " + getGroupsString(groupCount) + "; " + Utils.join(ss, ", ") + " in each group)"); } out.writeln(params.shouldSynchIterations() ? ", will synchronize iterations" : (params.getMode() == Mode.SingleShotTime) ? "" : ", ***WARNING: Synchronize iterations are disabled!***"); out.writeln("# Benchmark mode: " + params.getMode().longLabel()); out.writeln("# Benchmark: " + params.getBenchmark()); if (!params.getParamsKeys().isEmpty()) { StringBuilder sb = new StringBuilder(); boolean isFirst = true; for (String k : params.getParamsKeys()) { if (isFirst) { isFirst = false; } else { sb.append(", "); } sb.append(k).append(" = ").append(params.getParam(k)); } out.writeln("# Parameters: (" + sb.toString() + ")"); } } @Override public void iteration(BenchmarkParams benchmarkParams, IterationParams params, int iteration) { if (verbose == VerboseMode.SILENT) { return; } switch (params.getType()) { case WARMUP: out.write(String.format("Warmup %3d: ", iteration)); break; case MEASUREMENT: out.write(String.format("Iteration %3d: ", iteration)); break; default: throw new IllegalStateException("Unknown iteration type: " + params.getType()); } flush(); } protected static String getThreadsString(int t) { if (t > 1) { return "threads"; } else { return "thread"; } } protected static String getGroupsString(int g) { if (g > 1) { return "groups"; } else { return "group"; } } @Override public void iterationResult(BenchmarkParams benchmParams, IterationParams params, int iteration, IterationResult data) { if (verbose == VerboseMode.SILENT) { return; } StringBuilder sb = new StringBuilder(); sb.append(data.getPrimaryResult().toString()); if (params.getType() == IterationType.MEASUREMENT) { int prefixLen = String.format("Iteration %3d: ", iteration).length(); Map<String, Result> secondary = data.getSecondaryResults(); if (!secondary.isEmpty()) { sb.append("\n"); int maxKeyLen = 0; for (Map.Entry<String, Result> res : secondary.entrySet()) { maxKeyLen = Math.max(maxKeyLen, res.getKey().length()); } for (Map.Entry<String, Result> res : secondary.entrySet()) { sb.append(String.format("%" + prefixLen + "s", "")); sb.append(String.format(" %-" + (maxKeyLen + 1) + "s %s", res.getKey() + ":", res.getValue())); sb.append("\n"); } } } out.write(String.format("%s%n", sb)); flush(); } @Override public void endBenchmark(BenchmarkResult result) { out.writeln(""); if (result != null) { { Result r = result.getPrimaryResult(); String s = r.extendedInfo(); if (!s.trim().isEmpty()) { out.writeln("Result \"" + result.getParams().getBenchmark() + "\":"); out.writeln(s); } } for (Result r : result.getSecondaryResults().values()) { String s = r.extendedInfo(); if (!s.trim().isEmpty()) { out.writeln("Secondary result \"" + result.getParams().getBenchmark() + ":" + r.getLabel() + "\":"); out.writeln(s); } } out.writeln(""); } } @Override public void startRun() { // do nothing } @Override public void endRun(Collection<RunResult> runResults) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(baos, true, StandardCharsets.UTF_8.name()); ResultFormatFactory.getInstance(ResultFormatType.TEXT, printStream).writeOut(runResults); println(baos.toString()); } catch (UnsupportedEncodingException e) { // Not going to happen } } }
8,140
31.434263
137
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/benchmark/HttpBenchmark.java
package org.infinispan.cli.benchmark; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Random; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.RestURI; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.CacheException; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.util.Util; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.infra.Blackhole; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ @State(Scope.Thread) public class HttpBenchmark { private static final long BIG_DELAY_NANOS = TimeUnit.DAYS.toNanos(1); RestClient client; RestCacheClient cache; @Param("http://127.0.0.1") public String uri; @Param("benchmark") public String cacheName; @Param("") public String cacheTemplate; @Param("16") public int keySize; @Param("1000") public int valueSize; @Param("1000") public int keySetSize; RestEntity value; List<String> keySet; AtomicInteger nextIndex; @Setup public void setup() { RestURI uri = RestURI.create(this.uri); RestClientConfigurationBuilder builder = uri.toConfigurationBuilder(); client = RestClient.forConfiguration(builder.build()); cache = client.cache(cacheName); try (RestResponse response = uncheckedAwait(cache.exists())) { switch (response.getStatus()) { case RestResponse.OK: case RestResponse.NO_CONTENT: break; case RestResponse.NOT_FOUND: Util.close(client); throw new IllegalArgumentException("Could not find cache '" + cacheName+"'"); case RestResponse.UNAUTHORIZED: Util.close(client); throw new SecurityException(response.getBody()); default: Util.close(client); throw new RuntimeException(response.getBody()); } } value = RestEntity.create(MediaType.APPLICATION_OCTET_STREAM, new byte[valueSize]); keySet = new ArrayList<>(keySetSize); Random r = new Random(17); // We always use the same seed to make things repeatable byte[] keyBytes = new byte[keySize / 2]; for (int i = 0; i < keySetSize; i++) { r.nextBytes(keyBytes); String key = Util.toHexString(keyBytes); keySet.add(key); cache.put(key, value); } nextIndex = new AtomicInteger(); } @Benchmark public void get(Blackhole bh) { try(RestResponse response = uncheckedAwait(cache.get(nextKey()))) { bh.consume(response.getBody()); } } @Benchmark public void put() { Util.close(uncheckedAwait(cache.put(nextKey(), value))); } @TearDown public void teardown() { Util.close(client); } private String nextKey() { return keySet.get(nextIndex.getAndIncrement() % keySetSize); } public static <T> T uncheckedAwait(CompletionStage<T> future) { try { return Objects.requireNonNull(future, "Completable Future must be non-null.").toCompletableFuture().get(BIG_DELAY_NANOS, TimeUnit.NANOSECONDS); } catch (java.util.concurrent.TimeoutException e) { throw new IllegalStateException("This should never happen!", e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CacheException(e); } catch (ExecutionException e) { throw new CacheException(e); } } }
4,154
30.961538
152
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/benchmark/RespBenchmark.java
package org.infinispan.cli.benchmark; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.commons.util.Util; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.infra.Blackhole; import io.lettuce.core.RedisClient; import io.lettuce.core.api.sync.RedisCommands; import io.lettuce.core.codec.ByteArrayCodec; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 15.0 **/ @State(Scope.Thread) public class RespBenchmark { RedisClient client; RedisCommands<byte[], byte[]> connection; @Param("redis://127.0.0.1:11222") public String uri; @Param("16") public int keySize; @Param("1000") public int valueSize; @Param("1000") public int keySetSize; byte[] value; List<byte[]> keySet; AtomicInteger nextIndex; @Setup public void setup() { client = RedisClient.create(uri); connection = client.connect(ByteArrayCodec.INSTANCE).sync(); value = new byte[valueSize]; keySet = new ArrayList<>(keySetSize); Random r = new Random(17); // We always use the same seed to make things repeatable for (int i = 0; i < keySetSize; i++) { byte[] key = new byte[keySize]; r.nextBytes(key); keySet.add(key); connection.set(key, value); } nextIndex = new AtomicInteger(); } @Benchmark public void get(Blackhole bh) { bh.consume(connection.get(nextKey())); } @Benchmark public void put() { connection.set(nextKey(), value); } @TearDown public void teardown() { Util.close(client); } private byte[] nextKey() { return keySet.get(nextIndex.getAndIncrement() % keySetSize); } }
1,997
23.365854
89
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/activators/ContextAwareCommandActivator.java
package org.infinispan.cli.activators; import org.aesh.command.activator.CommandActivator; import org.infinispan.cli.Context; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public interface ContextAwareCommandActivator extends CommandActivator { void setContext(Context context); }
322
23.846154
72
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/activators/ConnectionActivator.java
package org.infinispan.cli.activators; import org.aesh.command.impl.internal.ParsedCommand; import org.infinispan.cli.Context; public class ConnectionActivator implements ContextAwareCommandActivator { private Context context; @Override public boolean isActivated(ParsedCommand command) { // In batch mode context is null return context == null || context.isConnected(); } @Override public void setContext(Context context) { this.context = context; } }
497
22.714286
74
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/activators/ContextAwareCommandActivatorProvider.java
package org.infinispan.cli.activators; import java.util.Objects; import org.aesh.command.activator.CommandActivator; import org.aesh.command.activator.CommandActivatorProvider; import org.infinispan.cli.Context; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class ContextAwareCommandActivatorProvider implements CommandActivatorProvider { private final Context context; public ContextAwareCommandActivatorProvider(Context context) { Objects.requireNonNull(context); this.context = context; } @Override public CommandActivator enhanceCommandActivator(CommandActivator commandActivator) { if (commandActivator instanceof ContextAwareCommandActivator) { ((ContextAwareCommandActivator) commandActivator).setContext(context); } return commandActivator; } }
859
27.666667
87
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/activators/DisabledActivator.java
package org.infinispan.cli.activators; import org.aesh.command.activator.CommandActivator; import org.aesh.command.impl.internal.ParsedCommand; /** * An activator which is used for marking commands which are not yet implemented * * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class DisabledActivator implements CommandActivator { @Override public boolean isActivated(ParsedCommand command) { return false; } }
468
25.055556
80
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/activators/ConfigConversionAvailable.java
package org.infinispan.cli.activators; import org.aesh.command.activator.CommandActivator; import org.aesh.command.impl.internal.ParsedCommand; import org.infinispan.commons.util.Util; /** * @since 14.0 **/ public class ConfigConversionAvailable implements CommandActivator { @Override public boolean isActivated(ParsedCommand command) { try { Util.loadClass("org.infinispan.configuration.parsing.ParserRegistry", this.getClass().getClassLoader()); return true; } catch (Exception e) { return false; } } }
564
25.904762
113
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/patching/PatchInfo.java
package org.infinispan.cli.patching; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.dataconversion.internal.JsonSerialization; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ public class PatchInfo implements JsonSerialization { private static final String BRAND_NAME = "brandName"; private static final String SOURCE_VERSION = "sourceVersion"; private static final String TARGET_VERSION = "targetVersion"; private static final String QUALIFIER = "qualifier"; private static final String CREATION_DATE = "creationDate"; private static final String INSTALLATION_DATE = "installationDate"; private static final String OPERATIONS = "operations"; private final Date creationDate; private Date installationDate; private final String brandName; private final String sourceVersion; private final String targetVersion; private final String qualifier; private final List<PatchOperation> operations; public PatchInfo(String brandName, String sourceVersion, String targetVersion, String qualifier) { this(brandName, sourceVersion, targetVersion, qualifier, new Date(), null, new ArrayList<>()); } PatchInfo(String brandName, String sourceVersion, String targetVersion, String qualifier, Date creationDate, Date installationDate, List<PatchOperation> operations) { this.brandName = brandName; this.sourceVersion = sourceVersion; this.targetVersion = targetVersion; this.qualifier = qualifier; this.creationDate = creationDate; this.installationDate = installationDate; this.operations = operations; } public String getQualifier() { return qualifier; } public String getBrandName() { return brandName; } public String getSourceVersion() { return sourceVersion; } public String getTargetVersion() { return targetVersion; } public List<PatchOperation> getOperations() { return operations; } public Date getCreationDate() { return creationDate; } public Date getInstallationDate() { return installationDate; } public void setInstallationDate(Date installationDate) { this.installationDate = installationDate; } public String toString() { return brandName + " patch target=" + targetVersion + (qualifier.isEmpty() ? "" : "(" + qualifier + ")") + " source=" + sourceVersion + " created=" + creationDate + (installationDate != null ? " installed=" + installationDate : ""); } public static PatchInfo fromJson(Json json) { Json brandName = json.at(BRAND_NAME); Json sourceVersion = json.at(SOURCE_VERSION); Json targetVersion = json.at(TARGET_VERSION); Json qualifier = json.at(QUALIFIER); Json creationDate = json.at(CREATION_DATE); Json installationDate = json.at(INSTALLATION_DATE); Json operations = json.at(OPERATIONS); String brandValue = brandName != null ? brandName.asString() : null; String sourceValue = sourceVersion != null ? sourceVersion.asString() : null; String targetValue = targetVersion != null ? targetVersion.asString() : null; String qualifierValue = qualifier != null ? qualifier.asString() : null; Date creationValue = creationDate != null ? creationDate.isNull() ? null : new Date(creationDate.asLong()) : null; Date installationValue = installationDate != null ? installationDate.isNull() ? null : new Date(installationDate.asLong()) : null; List<PatchOperation> operationsValue = operations != null ? operations.asJsonList().stream().map(PatchOperation::fromJson).collect(Collectors.toList()) : null; return new PatchInfo(brandValue, sourceValue, targetValue, qualifierValue, creationValue, installationValue, operationsValue); } @Override public Json toJson() { return Json.object() .set(BRAND_NAME, brandName) .set(SOURCE_VERSION, sourceVersion) .set(TARGET_VERSION, targetVersion) .set(QUALIFIER, qualifier) .set(CREATION_DATE, creationDate != null ? creationDate.getTime() : null) .set(INSTALLATION_DATE, installationDate != null ? installationDate.getTime() : null) .set(OPERATIONS, Json.make(operations)); } }
4,448
37.686957
238
java