Mercurial > hg > thermostat-ng > agent
changeset 2653:f2abfc4cfc93
Clean up some unneeded code in Launcher
Reviewed-by: jerboaa
Review-thread: http://icedtea.classpath.org/pipermail/thermostat/2017-May/023131.html
line wrap: on
line diff
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/Launcher.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/main/java/com/redhat/thermostat/launcher/Launcher.java Wed May 17 18:12:02 2017 -0400 @@ -49,23 +49,21 @@ public interface Launcher { /** - * Invoked in order to start a command, either when Thermostat starts, or within - * the thermostat shell. Equivalent to calling run(null, inShell). + * Invoked in order to start a command when Thermostat starts. + * Equivalent to calling run(null, inShell). * @param args the name of the command and any arguments to it - * @param inShell whether invoked from within the thermostat shell */ - void run(String[] args, boolean inShell); + void run(String[] args); /** - * Invoked in order to start a command, either when Thermostat starts, or within - * the thermostat shell. If the command being run happens to be a AbstractStateNotifyingCommand, + * Invoked in order to start a command when Thermostat starts. + * If the command being run happens to be a AbstractStateNotifyingCommand, * and the argument is non-null, the listeners will be added to the command for * life cycle notifications. Otherwise, the argument is ignored. * @param args the name of the command and any arguments to it * @param listeners the collection of listeners to be added to the command - * @param inShell whether invoked from within the thermostat shell */ - void run(String[] args, Collection<ActionListener<ApplicationState>> listeners, boolean inShell); + void run(String[] args, Collection<ActionListener<ApplicationState>> listeners); }
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/Activator.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/main/java/com/redhat/thermostat/launcher/internal/Activator.java Wed May 17 18:12:02 2017 -0400 @@ -36,6 +36,13 @@ package com.redhat.thermostat.launcher.internal; +import java.io.File; +import java.io.IOException; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + import com.redhat.thermostat.common.ActionEvent; import com.redhat.thermostat.common.ActionListener; import com.redhat.thermostat.common.ExitStatus; @@ -48,23 +55,10 @@ import com.redhat.thermostat.common.cli.CommandRegistry; import com.redhat.thermostat.common.cli.CommandRegistryImpl; import com.redhat.thermostat.common.cli.CompleterService; -import com.redhat.thermostat.common.config.ClientPreferences; import com.redhat.thermostat.common.config.experimental.ConfigurationInfoSource; import com.redhat.thermostat.launcher.BundleManager; import com.redhat.thermostat.launcher.Launcher; -import com.redhat.thermostat.launcher.internal.CurrentEnvironment.CurrentEnvironmentChangeListener; import com.redhat.thermostat.shared.config.CommonPaths; -import com.redhat.thermostat.shared.config.SSLConfiguration; -import com.redhat.thermostat.storage.core.DbService; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.osgi.framework.ServiceRegistration; -import org.osgi.util.tracker.ServiceTracker; -import org.osgi.util.tracker.ServiceTrackerCustomizer; - -import java.io.File; -import java.io.IOException; public class Activator implements BundleActivator { @@ -80,18 +74,14 @@ private ServiceRegistration pluginConfReg; private ServiceRegistration commandGroupMetaReg; private BundleContext context; - private CurrentEnvironment env; - RegisterLauncherAction(BundleContext context, CurrentEnvironment env) { + RegisterLauncherAction(BundleContext context) { this.context = context; - this.env = env; } @Override public void dependenciesAvailable(DependencyProvider services) { CommonPaths paths = services.get(CommonPaths.class); - ClientPreferences prefs = new ClientPreferences(paths); - SSLConfiguration sslConf = services.get(SSLConfiguration.class); String commandsDir = new File(paths.getSystemConfigurationDirectory(), "commands").toString(); CommandInfoSource builtInCommandSource = @@ -120,7 +110,7 @@ // Register Launcher service since FrameworkProvider is waiting for it blockingly. LauncherImpl launcher = new LauncherImpl(context, new CommandContextFactory(context), - bundleService, commands, env, prefs, paths, sslConf); + bundleService, commands, paths); launcherReg = context.registerService(Launcher.class.getName(), launcher, null); bundleManReg = context.registerService(BundleManager.class, bundleService, null); ExitStatus exitStatus = new ExitStatusImpl(ExitStatus.EXIT_SUCCESS); @@ -141,27 +131,20 @@ } private MultipleServiceTracker launcherDepsTracker; - private MultipleServiceTracker shellTracker; private CommandRegistry registry; - private ShellCommand shellCommand; private TabCompletion tabCompletion; - @SuppressWarnings("rawtypes") private MultipleServiceTracker commandInfoSourceTracker; - private ServiceTracker dbServiceTracker; - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({ "rawtypes" }) @Override public void start(final BundleContext context) throws Exception { - CurrentEnvironment environment = new CurrentEnvironment(Environment.CLI); - Class[] launcherDeps = new Class[]{ CommonPaths.class, - SSLConfiguration.class, }; registry = new CommandRegistryImpl(context); - RegisterLauncherAction registerLauncherAction = new RegisterLauncherAction(context, environment); + RegisterLauncherAction registerLauncherAction = new RegisterLauncherAction(context); launcherDepsTracker = new MultipleServiceTracker(context, launcherDeps, registerLauncherAction); launcherDepsTracker.open(); @@ -187,36 +170,6 @@ }); final HelpCommand helpCommand = new HelpCommand(); - environment.addListener(new CurrentEnvironmentChangeListener() { - @Override - public void enviornmentChanged(Environment oldEnv, Environment newEnv) { - helpCommand.setEnvironment(newEnv); - } - }); - helpCommand.setEnvironment(environment.getCurrent()); - - final Class<?>[] shellClasses = new Class[] { - CommonPaths.class, - ConfigurationInfoSource.class, - }; - shellTracker = new MultipleServiceTracker(context, shellClasses, new Action() { - @Override - public void dependenciesAvailable(DependencyProvider services) { - CommonPaths paths = services.get(CommonPaths.class); - ConfigurationInfoSource config = services.get(ConfigurationInfoSource.class); - shellCommand = new ShellCommand(context, paths, config); - shellCommand.setTabCompletion(tabCompletion); - shellCommand.setCompleterServiceRegistry(completerServiceRegistry); - registry.registerCommand("shell", shellCommand); - } - - @Override - public void dependenciesUnavailable() { - registry.unregisterCommand("shell"); - } - }); - shellTracker.open(); - final HelpCommandCompleterService helpCommandCompleterService = new HelpCommandCompleterService(); final Class<?>[] helpCommandClasses = new Class<?>[] { CommandInfoSource.class, @@ -228,9 +181,6 @@ CommandInfoSource infoSource = services.get(CommandInfoSource.class); helpCommand.setCommandInfoSource(infoSource); helpCommandCompleterService.bindCommandInfoSource(infoSource); - if (shellCommand != null) { - shellCommand.setCommandInfoSource(infoSource); - } CommandGroupMetadataSource commandGroupMetadataSource = services.get(CommandGroupMetadataSource.class); helpCommand.setCommandGroupMetadataSource(commandGroupMetadataSource); @@ -241,36 +191,10 @@ helpCommand.setCommandInfoSource(null); helpCommand.setCommandGroupMetadataSource(null); helpCommandCompleterService.unbindCommandInfoSource(); - if (shellCommand != null) { - shellCommand.setCommandInfoSource(null); - } } }); commandInfoSourceTracker.open(); - dbServiceTracker = new ServiceTracker(context, DbService.class.getName(), new ServiceTrackerCustomizer() { - @Override - public Object addingService(ServiceReference serviceReference) { - if (shellCommand != null) { - DbService dbService = (DbService) context.getService(serviceReference); - shellCommand.dbServiceAvailable(dbService); - } - return context.getService(serviceReference); - } - - @Override - public void modifiedService(ServiceReference serviceReference, Object o) { - //Do nothing - } - - @Override - public void removedService(ServiceReference serviceReference, Object o) { - if (shellCommand != null) { - shellCommand.dbServiceUnavailable(); - } - } - }); - dbServiceTracker.open(); registry.registerCommand("help", helpCommand); context.registerService(CompleterService.class.getName(), helpCommandCompleterService, null); @@ -287,9 +211,6 @@ if (completerServiceRegistry != null) { completerServiceRegistry.stop(); } - if (shellTracker != null) { - shellTracker.close(); - } registry.unregisterCommands(); } }
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/BasicCommandInfo.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/main/java/com/redhat/thermostat/launcher/internal/BasicCommandInfo.java Wed May 17 18:12:02 2017 -0400 @@ -37,9 +37,7 @@ package com.redhat.thermostat.launcher.internal; import java.util.List; -import java.util.Set; -import com.redhat.thermostat.launcher.internal.PluginConfiguration.CommandGroupMetadata; import org.apache.commons.cli.Options; import com.redhat.thermostat.launcher.BundleInformation; @@ -53,11 +51,10 @@ private final String usage; private final List<PluginConfiguration.Subcommand> subcommands; private final Options options; - private final Set<Environment> environments; private final List<BundleInformation> bundles; public BasicCommandInfo(String name, String summary, String description, List<String> commandGroups, String usage, - Options options, List<PluginConfiguration.Subcommand> subcommands, Set<Environment> environments, List<BundleInformation> bundles) { + Options options, List<PluginConfiguration.Subcommand> subcommands, List<BundleInformation> bundles) { this.name = name; this.summary = summary; this.description = description; @@ -65,7 +62,6 @@ this.usage = usage; this.options = options; this.subcommands = subcommands; - this.environments = environments; this.bundles = bundles; } @@ -105,11 +101,6 @@ } @Override - public Set<Environment> getEnvironments() { - return environments; - } - - @Override public List<BundleInformation> getBundles() { return bundles; }
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/BuiltInCommandInfo.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/main/java/com/redhat/thermostat/launcher/internal/BuiltInCommandInfo.java Wed May 17 18:12:02 2017 -0400 @@ -40,11 +40,9 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.EnumSet; import java.util.List; import java.util.Map.Entry; import java.util.Properties; -import java.util.Set; import java.util.logging.Logger; import org.apache.commons.cli.Option; @@ -53,7 +51,6 @@ import com.redhat.thermostat.common.utils.LoggingUtils; import com.redhat.thermostat.launcher.BundleInformation; -import com.redhat.thermostat.shared.config.InvalidConfigurationException; public class BuiltInCommandInfo implements CommandInfo { @@ -64,7 +61,6 @@ private static final String COMMAND_GROUP_DESC = "command-groups"; private static final String PROPERTY_USAGE = "usage"; private static final String PROPERTY_OPTIONS = "options"; - private static final String PROPERTY_ENVIRONMENTS = "environments"; private static final String PROP_SHORTOPT = ".short"; private static final String PROP_LONGOPT = ".long"; @@ -75,7 +71,6 @@ private String name, summary, description, usage; private List<String> commandGroups = new ArrayList<>(); private Options options; - private EnumSet<Environment> environment; private List<BundleInformation> dependencies; BuiltInCommandInfo(String commandName, Properties properties) { @@ -102,8 +97,6 @@ usage = properties.getProperty(key); } else if (key.equals(PROPERTY_OPTIONS)) { learnOptions((String) entry.getValue(), properties); - } else if (key.equals(PROPERTY_ENVIRONMENTS)) { - environment = parseEnvironment(properties.getProperty(key)); } } } @@ -352,27 +345,6 @@ option.getArgName()); } - private EnumSet<Environment> parseEnvironment(String value) { - EnumSet<Environment> result = EnumSet.noneOf(Environment.class); - String[] terms = value.split(","); - for (String term : terms) { - term = term.trim(); - if (term.equals("shell")) { - result.add(Environment.SHELL); - } else if (term.equals("cli")) { - result.add(Environment.CLI); - } else { - logger.info("Command " + this.name + " is available in unknown context: " + term); - } - } - - if (result.isEmpty()) { - throw new InvalidConfigurationException("no value for environments"); - } - - return result; - } - @Override public String getName() { return name; @@ -409,11 +381,6 @@ } @Override - public Set<Environment> getEnvironments() { - return environment; - } - - @Override public List<BundleInformation> getBundles() { return dependencies; }
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/CommandInfo.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/main/java/com/redhat/thermostat/launcher/internal/CommandInfo.java Wed May 17 18:12:02 2017 -0400 @@ -90,11 +90,6 @@ */ public List<PluginConfiguration.Subcommand> getSubcommands(); - /** - * Environments where this command is available - */ - public Set<Environment> getEnvironments(); - List<BundleInformation> getBundles(); }
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/CompoundCommandInfoSource.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/main/java/com/redhat/thermostat/launcher/internal/CompoundCommandInfoSource.java Wed May 17 18:12:02 2017 -0400 @@ -42,7 +42,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Set; import org.apache.commons.cli.Options; @@ -138,12 +137,11 @@ String usage = selectBest(info1.getUsage(), info2.getUsage()); List<PluginConfiguration.Subcommand> subcommands = selectBest(info1.getSubcommands(), info2.getSubcommands()); Options options = selectBest(info1.getOptions(), info2.getOptions()); - Set<Environment> environment = selectBest(info1.getEnvironments(), info2.getEnvironments()); List<BundleInformation> bundles = new ArrayList<>(); bundles.addAll(info1.getBundles()); bundles.addAll(info2.getBundles()); - return new BasicCommandInfo(name, summary, description, commandGroups, usage, options, subcommands, environment, bundles); + return new BasicCommandInfo(name, summary, description, commandGroups, usage, options, subcommands, bundles); } private <T> T selectBest(T first, T second) {
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/CurrentEnvironment.java Wed May 17 18:11:05 2017 -0400 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,83 +0,0 @@ -/* - * Copyright 2012-2017 Red Hat, Inc. - * - * This file is part of Thermostat. - * - * Thermostat is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published - * by the Free Software Foundation; either version 2, or (at your - * option) any later version. - * - * Thermostat is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Thermostat; see the file COPYING. If not see - * <http://www.gnu.org/licenses/>. - * - * Linking this code with other modules is making a combined work - * based on this code. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. - * - * As a special exception, the copyright holders of this code give - * you permission to link this code with independent modules to - * produce an executable, regardless of the license terms of these - * independent modules, and to copy and distribute the resulting - * executable under terms of your choice, provided that you also - * meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module - * which is not derived from or based on this code. If you modify - * this code, you may extend this exception to your version of the - * library, but you are not obligated to do so. If you do not wish - * to do so, delete this exception statement from your version. - */ - -package com.redhat.thermostat.launcher.internal; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -public class CurrentEnvironment { - - public interface CurrentEnvironmentChangeListener { - public void enviornmentChanged(Environment oldEnv, Environment newEnv); - } - - private Environment current; - private List<CurrentEnvironmentChangeListener> listeners = new CopyOnWriteArrayList<>(); - - public CurrentEnvironment(Environment initial) { - current = initial; - } - - public Environment getCurrent() { - return current; - } - - public void setCurrent(Environment environment) { - if (environment == current) { - return; - } - - Environment old = current; - current = environment; - fireEnvironmentChanged(old, current); - } - - private void fireEnvironmentChanged(Environment oldEnv, Environment newEnv) { - for (CurrentEnvironmentChangeListener listener : listeners) { - listener.enviornmentChanged(oldEnv, newEnv); - } - } - - public void addListener(CurrentEnvironmentChangeListener listener) { - listeners.add(listener); - } - - public void removeListener(CurrentEnvironmentChangeListener listener) { - listeners.remove(listener); - } -} -
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/Environment.java Wed May 17 18:11:05 2017 -0400 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,45 +0,0 @@ -/* - * Copyright 2012-2017 Red Hat, Inc. - * - * This file is part of Thermostat. - * - * Thermostat is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published - * by the Free Software Foundation; either version 2, or (at your - * option) any later version. - * - * Thermostat is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Thermostat; see the file COPYING. If not see - * <http://www.gnu.org/licenses/>. - * - * Linking this code with other modules is making a combined work - * based on this code. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. - * - * As a special exception, the copyright holders of this code give - * you permission to link this code with independent modules to - * produce an executable, regardless of the license terms of these - * independent modules, and to copy and distribute the resulting - * executable under terms of your choice, provided that you also - * meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module - * which is not derived from or based on this code. If you modify - * this code, you may extend this exception to your version of the - * library, but you are not obligated to do so. If you do not wish - * to do so, delete this exception statement from your version. - */ - -package com.redhat.thermostat.launcher.internal; - - -public enum Environment { - SHELL, - CLI, - -} -
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/HelpCommand.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/main/java/com/redhat/thermostat/launcher/internal/HelpCommand.java Wed May 17 18:12:02 2017 -0400 @@ -80,8 +80,6 @@ private CommandInfoSource commandInfoSource; private CommandGroupMetadataSource commandGroupMetadataSource; - private Environment currentEnvironment; - private SortedMap<CommandGroupMetadata, SortedSet<CommandInfo>> commandGroupMap; private Map<String, CommandGroupMetadata> commandGroupMetadataMap; private Set<CommandInfo> contextualCommands = new HashSet<>(); @@ -94,10 +92,6 @@ this.commandGroupMetadataSource = commandGroupMetadataSource; } - public void setEnvironment(Environment env) { - currentEnvironment = env; - } - @Override public void run(CommandContext ctx) { Arguments args = ctx.getArguments(); @@ -113,22 +107,12 @@ return; } - for (CommandInfo info: commandInfoSource.getCommandInfos()) { - if (info.getEnvironments().contains(currentEnvironment)) { - contextualCommands.add(info); - } - } - + contextualCommands.addAll(commandInfoSource.getCommandInfos()); commandGroupMetadataMap = new HashMap<>(commandGroupMetadataSource.getCommandGroupMetadata()); commandGroupMap = createCommandGroupMap(); if (nonParsed.isEmpty()) { - if (currentEnvironment == Environment.CLI) { - //CLI only since the framework will already be - //started for a command invoked via shell - printOptionSummaries(ctx); - } - + printOptionSummaries(ctx); printCommandSummaries(ctx); } else { printCommandUsage(ctx, nonParsed.get(0)); @@ -230,9 +214,6 @@ Options options = info.getOptions(); String usage = APP_NAME + " " + info.getUsage() + "\n" + info.getDescription(); String header = ""; - if (isAvailabilityNoteNeeded(info)) { - header = getAvailabilityNote(info); - } header = header + "\n" + APP_NAME + " " + info.getName(); Option help = CommonOptions.getHelpOption(); options.addOption(help); @@ -269,23 +250,6 @@ pw.flush(); } - private boolean isAvailabilityNoteNeeded(CommandInfo info) { - return !info.getEnvironments().contains(currentEnvironment); - } - - /** Describe where command is available */ - private String getAvailabilityNote(CommandInfo info) { - // there are two mutually exclusive environments: if an availability - // note is needed, it will just be about one - if (info.getEnvironments().contains(Environment.SHELL)) { - return translator.localize(LocaleResources.COMMAND_AVAILABLE_INSIDE_SHELL).getContents(); - } else if (info.getEnvironments().contains(Environment.CLI)) { - return translator.localize(LocaleResources.COMMAND_AVAILABLE_OUTSIDE_SHELL).getContents(); - } else { - throw new AssertionError("Need to handle a third environment"); - } - } - @Override public boolean isStorageRequired() { return false;
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/LauncherImpl.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/main/java/com/redhat/thermostat/launcher/internal/LauncherImpl.java Wed May 17 18:12:02 2017 -0400 @@ -67,23 +67,14 @@ import com.redhat.thermostat.common.cli.CommandContextFactory; import com.redhat.thermostat.common.cli.CommandException; import com.redhat.thermostat.common.cli.CommandLineArgumentParseException; -import com.redhat.thermostat.common.config.ClientPreferences; import com.redhat.thermostat.common.tools.ApplicationState; import com.redhat.thermostat.common.utils.LoggingUtils; import com.redhat.thermostat.launcher.BundleInformation; import com.redhat.thermostat.launcher.BundleManager; -import com.redhat.thermostat.launcher.InteractiveStorageCredentials; import com.redhat.thermostat.launcher.Launcher; import com.redhat.thermostat.shared.config.CommonPaths; -import com.redhat.thermostat.shared.config.SSLConfiguration; -import com.redhat.thermostat.shared.locale.LocalizedString; import com.redhat.thermostat.shared.locale.Translate; -import com.redhat.thermostat.storage.core.ConnectionException; -import com.redhat.thermostat.storage.core.DbService; -import com.redhat.thermostat.storage.core.DbServiceFactory; import com.redhat.thermostat.storage.core.Storage; -import com.redhat.thermostat.storage.core.StorageCredentials; -import com.redhat.thermostat.storage.core.StorageException; /** * This class is thread-safe. @@ -107,39 +98,28 @@ private final BundleContext context; private final BundleManager registry; private final CommandContextFactory cmdCtxFactory; - private final DbServiceFactory dbServiceFactory; private final Version coreVersion; private final CommandSource commandSource; private final CommandInfoSource commandInfoSource; - private final CurrentEnvironment currentEnvironment; private final CommonPaths paths; private final DependencyManager manager; - private final ClientPreferences prefs; - private final SSLConfiguration sslConf; - public LauncherImpl(BundleContext context, CommandContextFactory cmdCtxFactory, BundleManager registry, - CommandInfoSource infoSource, CurrentEnvironment env, ClientPreferences prefs, - CommonPaths paths, SSLConfiguration sslConf) { - this(context, cmdCtxFactory, registry, infoSource, new CommandSource(context), env, - new DbServiceFactory(), new Version(), prefs, paths, sslConf); + CommandInfoSource infoSource, CommonPaths paths) { + this(context, cmdCtxFactory, registry, infoSource, new CommandSource(context), + new Version(), paths); } LauncherImpl(BundleContext context, CommandContextFactory cmdCtxFactory, BundleManager registry, CommandInfoSource commandInfoSource, CommandSource commandSource, - CurrentEnvironment currentEnvironment, DbServiceFactory dbServiceFactory, Version version, - ClientPreferences prefs, CommonPaths paths, SSLConfiguration sslConf) { + Version version, CommonPaths paths) { this.context = context; this.cmdCtxFactory = cmdCtxFactory; this.registry = registry; - this.dbServiceFactory = dbServiceFactory; this.coreVersion = version; this.commandSource = commandSource; this.commandInfoSource = commandInfoSource; - this.currentEnvironment = currentEnvironment; - this.prefs = prefs; this.paths = Objects.requireNonNull(paths); - this.sslConf = sslConf; this.manager = new DependencyManager(paths); // We log this in the constructor so as to not log it multiple times when a command invokes @@ -149,26 +129,23 @@ } @Override - public void run(String[] args, boolean inShell) { - run(args, null, inShell); + public void run(String[] args) { + run(args, null); } @Override - public void run(String[] args, Collection<ActionListener<ApplicationState>> listeners, boolean inShell) { + public void run(String[] args, Collection<ActionListener<ApplicationState>> listeners) { usageCount.incrementAndGet(); - Environment oldEnvironment = currentEnvironment.getCurrent(); - currentEnvironment.setCurrent(inShell ? Environment.SHELL : Environment.CLI); - try { if (hasNoArguments(args)) { runHelpCommand(); - } else if (isVersionQuery(args, inShell)) { + } else if (isVersionQuery(args)) { showVersion(); - } else if (isInfoQuery(args, inShell)) { + } else if (isInfoQuery(args)) { showInfo(); } else { - runCommandFromArguments(args, listeners, inShell); + runCommandFromArguments(args, listeners); } } catch (NoClassDefFoundError e) { // This could mean pom is missing <Private-Package> or <Export-Package> lines. @@ -184,7 +161,6 @@ throw e; } finally { args = null; - currentEnvironment.setCurrent(oldEnvironment); boolean isLastLaunch = (usageCount.decrementAndGet() == 0); if (isLastLaunch) { shutdown(); @@ -232,34 +208,34 @@ } private void runHelpCommand() { - runCommand(HELP_COMMAND_NAME, new String[0], null, false); + runCommand(HELP_COMMAND_NAME, new String[0], null); } private void runHelpCommandFor(String cmdName) { - runCommand(HELP_COMMAND_NAME, new String[] { "--", cmdName }, null, false); + runCommand(HELP_COMMAND_NAME, new String[] { "--", cmdName }, null); } // package-private for testing - void runCommandFromArguments(String[] args, Collection<ActionListener<ApplicationState>> listeners, boolean inShell) { - runCommand(args[0], Arrays.copyOfRange(args, 1, args.length), listeners, inShell); + void runCommandFromArguments(String[] args, Collection<ActionListener<ApplicationState>> listeners) { + runCommand(args[0], Arrays.copyOfRange(args, 1, args.length), listeners); } - private void runCommand(String cmdName, String[] cmdArgs, Collection<ActionListener<ApplicationState>> listeners, boolean inShell) { + private void runCommand(String cmdName, String[] cmdArgs, Collection<ActionListener<ApplicationState>> listeners) { // treat 'foo --help' as 'help foo' if (!cmdName.equals(HELP_COMMAND_NAME) && Arrays.asList(cmdArgs).contains(HELP_OPTION)) { - runCommand(HELP_COMMAND_NAME, new String[] { cmdName } , listeners, inShell); + runCommand(HELP_COMMAND_NAME, new String[] { cmdName } , listeners); return; } try { - parseArgsAndRunCommand(cmdName, cmdArgs, listeners, inShell); + parseArgsAndRunCommand(cmdName, cmdArgs, listeners); } catch (CommandException e) { cmdCtxFactory.getConsole().getError().println(e.getMessage()); } } private void parseArgsAndRunCommand(String cmdName, String[] cmdArgs, - Collection<ActionListener<ApplicationState>> listeners, boolean inShell) throws CommandException { + Collection<ActionListener<ApplicationState>> listeners) throws CommandException { PrintStream out = cmdCtxFactory.getConsole().getOutput(); PrintStream err = cmdCtxFactory.getConsole().getError(); @@ -299,10 +275,6 @@ return; } - if ((inShell && !cmdInfo.getEnvironments().contains(Environment.SHELL)) || (!inShell && !cmdInfo.getEnvironments().contains(Environment.CLI))) { - outputBadShellContext(inShell, out, cmdName); - return; - } if (listeners != null && cmd instanceof AbstractStateNotifyingCommand) { AbstractStateNotifyingCommand basicCmd = (AbstractStateNotifyingCommand) cmd; ActionNotifier<ApplicationState> notifier = basicCmd.getNotifier(); @@ -321,16 +293,6 @@ } } - private void outputBadShellContext(boolean inShell, PrintStream out, String cmd) { - LocalizedString message = null; - if (inShell) { - message = t.localize(LocaleResources.COMMAND_AVAILABLE_OUTSIDE_SHELL_ONLY, cmd); - } else { - message = t.localize(LocaleResources.COMMAND_AVAILABLE_INSIDE_SHELL_ONLY, cmd); - } - out.println(message.getContents()); - } - private Arguments parseCommandArguments(String[] cmdArgs, CommandInfo commandInfo) throws CommandLineArgumentParseException { CommandLineArgumentsParser cliArgsParser = new CommandLineArgumentsParser(); @@ -410,45 +372,14 @@ } } - @SuppressWarnings("rawtypes") private CommandContext setupCommandContext(Command cmd, Arguments args) throws CommandException { - CommandContext ctx = cmdCtxFactory.createContext(args); - - if (cmd.isStorageRequired()) { - - ServiceReference dbServiceReference = context.getServiceReference(DbService.class); - if (dbServiceReference == null) { - String dbUrl = ctx.getArguments().getArgument(CommonOptions.DB_URL_ARG); - if (dbUrl == null) { - dbUrl = prefs.getConnectionUrl(); - } - StorageCredentials creds = new InteractiveStorageCredentials(prefs, dbUrl, ctx.getConsole()); - try { - // this may throw storage exception - DbService service = dbServiceFactory.createDbService(dbUrl, creds, sslConf); - // This registers the DbService if all goes well - service.connect(); - } catch (StorageException ex) { - throw new CommandException(t.localize(LocaleResources.LAUNCHER_MALFORMED_URL, dbUrl)); - } catch (ConnectionException ex) { - String error = ex.getMessage(); - String message = ( error == null ? "" : " Error: " + error ); - logger.log(Level.SEVERE, "Could not connect to: " + dbUrl + message, ex); - throw new CommandException(t.localize(LocaleResources.LAUNCHER_CONNECTION_ERROR, dbUrl), ex); - } - } - } return ctx; } - private boolean isVersionQuery(String[] args, boolean inShell) { + private boolean isVersionQuery(String[] args) { // don't allow --version in the shell - if (inShell) { - return false; - } else { - return args[0].equals(Version.VERSION_OPTION); - } + return args[0].equals(Version.VERSION_OPTION); } private void showVersion() { @@ -457,13 +388,9 @@ cmdCtxFactory.getConsole().getOutput().println(coreVersion.getVersionInfo()); } - private boolean isInfoQuery(String[] args, boolean inShell) { + private boolean isInfoQuery(String[] args) { // don't allow --info in the shell - if (inShell) { - return false; - } else { - return args[0].equals(INFO_OPTION); - } + return args[0].equals(INFO_OPTION); } private void showInfo() {
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/PluginConfiguration.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/main/java/com/redhat/thermostat/launcher/internal/PluginConfiguration.java Wed May 17 18:12:02 2017 -0400 @@ -41,7 +41,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Set; import org.apache.commons.cli.Options; @@ -128,12 +127,11 @@ private final List<String> positionalArguments; private final Options options; private final List<Subcommand> subcommands; - private final Set<Environment> environment; private final List<BundleInformation> bundles; public NewCommand(String name, String summary, String description, List<String> commandGroups, String usage, List<String> positionalArguments, Options options, List<Subcommand> subcommands, - Set<Environment> environment, List<BundleInformation> bundles) { + List<BundleInformation> bundles) { this.commandName = name; this.summary = summary; this.description = description; @@ -142,7 +140,6 @@ this.positionalArguments = positionalArguments; this.options = options; this.subcommands = subcommands; - this.environment = environment; this.bundles = bundles; } @@ -185,11 +182,6 @@ return subcommands; } - /** Returns the environments where this command is available to be used */ - public Set<Environment> getEnvironments() { - return Collections.unmodifiableSet(environment); - } - public List<BundleInformation> getBundles() { return Collections.unmodifiableList(bundles); }
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/PluginConfigurationParser.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/main/java/com/redhat/thermostat/launcher/internal/PluginConfigurationParser.java Wed May 17 18:12:02 2017 -0400 @@ -44,18 +44,15 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; -import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import com.redhat.thermostat.launcher.internal.PluginConfiguration.CommandGroupMetadata; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; @@ -69,6 +66,7 @@ import com.redhat.thermostat.common.utils.LoggingUtils; import com.redhat.thermostat.launcher.BundleInformation; import com.redhat.thermostat.launcher.internal.PluginConfiguration.CommandExtensions; +import com.redhat.thermostat.launcher.internal.PluginConfiguration.CommandGroupMetadata; import com.redhat.thermostat.launcher.internal.PluginConfiguration.Configurations; import com.redhat.thermostat.launcher.internal.PluginConfiguration.NewCommand; import com.redhat.thermostat.launcher.internal.PluginConfiguration.PluginID; @@ -392,7 +390,6 @@ List<PluginConfiguration.Subcommand> subcommands = new ArrayList<>(); List<String> arguments = new ArrayList<>(); Options options = new Options(); - Set<Environment> availableInEnvironments = EnumSet.noneOf(Environment.class); List<BundleInformation> bundles = new ArrayList<>(); NodeList nodes = commandNode.getChildNodes(); @@ -414,8 +411,6 @@ arguments = parseArguments(pluginName, name, node); } else if (node.getNodeName().equals("options")) { options = parseOptions(node); - } else if (node.getNodeName().equals("environments")) { - availableInEnvironments = parseEnvironment(pluginName, name, node); } else if (node.getNodeName().equals("bundles")) { bundles.addAll(parseBundles(pluginName, name, node)); } @@ -425,13 +420,12 @@ logger.warning("plugin " + pluginName + " provides a new command " + name + " but supplies no bundles"); } - if (name == null || summary == null || description == null || availableInEnvironments.isEmpty()) { + if (name == null || summary == null || description == null) { logger.warning("plugin " + pluginName + " provides an incomplete new command: " + "name='" + name + "', summary='" + summary + ", description='" + description + "', options='" + options + "'"); return null; } else { - return new NewCommand(name, summary, description, commandGroups, usage, arguments, options, subcommands, - availableInEnvironments, bundles); + return new NewCommand(name, summary, description, commandGroups, usage, arguments, options, subcommands, bundles); } } @@ -500,10 +494,6 @@ return groups; } - private String parseCommandGroup(Node commandGroupNode) { - return commandGroupNode.getTextContent().trim().toLowerCase(); - } - private List<String> parseArguments(String pluginName, String commandName, Node argumentsNode) { return parseNodeAsList(pluginName, commandName, argumentsNode, "argument"); } @@ -658,19 +648,6 @@ return opt; } - private Set<Environment> parseEnvironment(String pluginName, String commandName, Node environmentNode) { - EnumSet<Environment> result = EnumSet.noneOf(Environment.class); - List<String> environments = parseNodeAsList(pluginName, commandName, environmentNode, "environment"); - for (String environment : environments) { - if (environment.equals("shell")) { - result.add(Environment.SHELL); - } else if (environment.equals("cli")) { - result.add(Environment.CLI); - } - } - return result; - } - private List<String> parseNodeAsList(String pluginName, String commandName, Node parentNode, String childElementName) { List<String> result = new ArrayList<>(); NodeList nodes = parentNode.getChildNodes();
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/PluginInfoSource.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/main/java/com/redhat/thermostat/launcher/internal/PluginInfoSource.java Wed May 17 18:12:02 2017 -0400 @@ -186,7 +186,6 @@ command.getCommandGroups(), usage, command.getOptions(), command.getSubcommands(), - command.getEnvironments(), command.getBundles() ); @@ -237,7 +236,6 @@ old.getCommandGroups(), old.getUsage(), old.getOptions(), old.getSubcommands(), - old.getEnvironments(), updatedBundles ); allNewCommands.put(entry.getKey(), updated); @@ -274,7 +272,7 @@ } private BasicCommandInfo createCommandInfo(String name, List<BundleInformation> bundles) { - return new BasicCommandInfo(name, null, null, Collections.<String>emptyList(), null, null, null, null, bundles); + return new BasicCommandInfo(name, null, null, Collections.<String>emptyList(), null, null, null, bundles); } public Map<String, String> getConfiguration(String pluginID, String fileName) throws IOException {
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/ShellArgsParser.java Wed May 17 18:11:05 2017 -0400 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,294 +0,0 @@ -/* - * Copyright 2012-2017 Red Hat, Inc. - * - * This file is part of Thermostat. - * - * Thermostat is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published - * by the Free Software Foundation; either version 2, or (at your - * option) any later version. - * - * Thermostat is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Thermostat; see the file COPYING. If not see - * <http://www.gnu.org/licenses/>. - * - * Linking this code with other modules is making a combined work - * based on this code. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. - * - * As a special exception, the copyright holders of this code give - * you permission to link this code with independent modules to - * produce an executable, regardless of the license terms of these - * independent modules, and to copy and distribute the resulting - * executable under terms of your choice, provided that you also - * meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module - * which is not derived from or based on this code. If you modify - * this code, you may extend this exception to your version of the - * library, but you are not obligated to do so. If you do not wish - * to do so, delete this exception statement from your version. - */ - -package com.redhat.thermostat.launcher.internal; - -import com.redhat.thermostat.shared.locale.Translate; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -import static java.util.Objects.requireNonNull; - -/** - * Parser for thermostat shell command line input. Splits lines on whitespaces to chunk commands and arguments, - * respecting quotation marks, so that ex: - * - * some-command --flag "quoted arg" - * - * is split into three parts: "some-command", "--flag", "quoted arg" - */ -class ShellArgsParser { - - private static final Translate<LocaleResources> translator = LocaleResources.createLocalizer(); - - private static final int NOT_YET_PARSED = -1; - private final String input; - private int pos = NOT_YET_PARSED; - private char c; - private final Issues issues = new Issues(); - - ShellArgsParser(String input) { - this.input = input; - } - - String[] parse() { - if (input.isEmpty()) { - ++pos; - return new String[]{}; - } - readChar(); - List<String> result = new ArrayList<>(); - do { - consumeWhitespace(); - if (isQuote()) { - result.add(quote()); - } else if (isWord()) { - result.add(word()); - } - } while (ready()); - return result.toArray(new String[result.size()]); - } - - Issues getParseIssues() { - if (pos == NOT_YET_PARSED) { - throw new IllegalStateException(translator.localize(LocaleResources.PARSE_ISSUES_CALLED_BEFORE_PARSE).getContents()); - } - return issues; - } - - private void consumeWhitespace() { - while (isWhitespace() && ready()) { - readChar(); - } - } - - private String quote() { - StringBuilder sb = new StringBuilder(); - boolean closed = false; - int startPos = pos; - char openingQuote = c; - while (ready()) { - readChar(); - if (isEscapedQuote()) { - readChar(); - sb.append(c); - continue; - } - if (c == openingQuote) { - if (ready()) { - readChar(); - if (!ready()) { - if (isQuote()) { - issues.addIssue(new Issue(pos, Issue.Type.UNMATCHED_QUOTE)); - } - } else { - if (!isWhitespace()) { - issues.addIssue(new Issue(pos, Issue.Type.EXPECTED_WHITESPACE)); - } - } - } - closed = true; - break; - } - sb.append(c); - } - if (!closed) { - issues.addIssue(new Issue(startPos, Issue.Type.UNMATCHED_QUOTE)); - } - return sb.toString(); - } - - private String word() { - StringBuilder sb = new StringBuilder(); - sb.append(c); - while (!isWhitespace() && ready()) { - readChar(); - if (isEscapedQuote()) { - readChar(); - sb.append(c); - continue; - } - if (!isWhitespace()) { - sb.append(c); - } - if (isQuote()) { - issues.addIssue(new Issue(pos, Issue.Type.UNEXPECTED_QUOTE)); - } - } - return sb.toString(); - } - - private boolean ready() { - return pos < input.length() - 1; - } - - private char readChar() { - c = input.charAt(++pos); - return c; - } - - private char lookahead() { - return input.charAt(pos + 1); - } - - private boolean isEscapedQuote() { - return c == '\\' && (lookahead() == '"' || lookahead() == '\''); - } - - private boolean isQuote() { - return c == '"' || c == '\''; - } - - private boolean isWhitespace() { - return Character.isWhitespace(c); - } - - private boolean isWord() { - return !(isQuote() || isWhitespace()); - } - - static class Issues { - private final List<Issue> issues = new ArrayList<>(); - - void addIssue(Issue issue) { - this.issues.add(requireNonNull(issue)); - } - - List<Issue> getAllIssues() { - return Collections.unmodifiableList(issues); - } - - List<Issue> getWarnings() { - return Collections.unmodifiableList(filterIssuesBySeverity(getAllIssues(), Issue.Type.Severity.WARN)); - } - - List<Issue> getErrors() { - return Collections.unmodifiableList(filterIssuesBySeverity(getAllIssues(), Issue.Type.Severity.ERROR)); - } - - private static List<Issue> filterIssuesBySeverity(Iterable<Issue> issues, Issue.Type.Severity severity) { - List<Issue> results = new ArrayList<>(); - for (Issue issue : issues) { - if (issue.getType().getSeverity().equals(severity)) { - results.add(issue); - } - } - return results; - } - } - - static class Issue { - private final int columnNumber; - private final Type type; - - Issue(int columnNumber, Type type) { - this.columnNumber = columnNumber; - this.type = requireNonNull(type); - } - - int getColumnNumber() { - return columnNumber; - } - - Type getType() { - return type; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - Issue issue = (Issue) o; - - return columnNumber == issue.columnNumber && type == issue.type; - } - - @Override - public int hashCode() { - return Objects.hash(columnNumber, type); - } - - @Override - public String toString() { - return type.getSeverity() + " : " + type.toString() + " col " + Integer.toString(columnNumber); - } - - enum Type { - UNMATCHED_QUOTE(Severity.ERROR), - UNEXPECTED_QUOTE(Severity.ERROR), - EXPECTED_WHITESPACE(Severity.WARN), - ; - - private final Severity severity; - - Type(Severity severity) { - this.severity = requireNonNull(severity); - } - - public Severity getSeverity() { - return severity; - } - - enum Severity { - WARN, - ERROR, - } - } - } - - static class IssuesFormatter { - String format(Issues issues) { - return format(issues.getAllIssues()); - } - - String format(Iterable<Issue> issues) { - StringBuilder sb = new StringBuilder(); - for (Issue issue : issues) { - sb.append(issue.toString()).append(System.lineSeparator()); - } - return sb.toString(); - } - } - -}
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/ShellCommand.java Wed May 17 18:11:05 2017 -0400 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,300 +0,0 @@ -/* - * Copyright 2012-2017 Red Hat, Inc. - * - * This file is part of Thermostat. - * - * Thermostat is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published - * by the Free Software Foundation; either version 2, or (at your - * option) any later version. - * - * Thermostat is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Thermostat; see the file COPYING. If not see - * <http://www.gnu.org/licenses/>. - * - * Linking this code with other modules is making a combined work - * based on this code. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. - * - * As a special exception, the copyright holders of this code give - * you permission to link this code with independent modules to - * produce an executable, regardless of the license terms of these - * independent modules, and to copy and distribute the resulting - * executable under terms of your choice, provided that you also - * meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module - * which is not derived from or based on this code. If you modify - * this code, you may extend this exception to your version of the - * library, but you are not obligated to do so. If you do not wish - * to do so, delete this exception statement from your version. - */ - -package com.redhat.thermostat.launcher.internal; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import jline.Terminal; -import jline.TerminalFactory; -import jline.console.ConsoleReader; -import jline.console.UserInterruptException; -import jline.console.completer.CandidateListCompletionHandler; -import jline.console.history.FileHistory; -import jline.console.history.History; -import jline.console.history.PersistentHistory; - -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; - -import com.redhat.thermostat.common.ApplicationInfo; -import com.redhat.thermostat.common.Version; -import com.redhat.thermostat.common.cli.AbstractCommand; -import com.redhat.thermostat.common.cli.CommandContext; -import com.redhat.thermostat.common.cli.CommandException; -import com.redhat.thermostat.common.cli.Console; -import com.redhat.thermostat.common.config.ClientPreferences; -import com.redhat.thermostat.common.config.experimental.ConfigurationInfoSource; -import com.redhat.thermostat.common.utils.LoggingUtils; -import com.redhat.thermostat.launcher.Launcher; -import com.redhat.thermostat.shared.config.CommonPaths; -import com.redhat.thermostat.shared.config.InvalidConfigurationException; -import com.redhat.thermostat.shared.locale.Translate; -import com.redhat.thermostat.storage.core.DbService; - -public class ShellCommand extends AbstractCommand { - - private static final Logger logger = LoggingUtils.getLogger(ShellCommand.class); - private static final Translate<LocaleResources> t = LocaleResources.createLocalizer(); - - private static final List<String> exitKeywords = Arrays.asList("exit", "quit", "q" ); - private static final List<String> clearKeywords = Arrays.asList("clear", "cls"); - - private HistoryProvider historyProvider; - private Version version; - - private BundleContext bundleContext; - - private final ShellPrompt shellPrompt; - private CommandInfoSource commandInfoSource; - private final ClientPreferences prefs; - private TabCompletion tabCompletion; - private CompleterServiceRegistry completerServiceRegistry; - - static class HistoryProvider { - - private CommonPaths paths; - - HistoryProvider(CommonPaths paths) { - this.paths = paths; - } - - public PersistentHistory get() { - PersistentHistory history = null; - try { - history = new FileHistory(paths.getUserHistoryFile()); - } catch (InvalidConfigurationException | IOException e) { - /* no history available */ - } - return history; - } - } - - public ShellCommand(BundleContext context, CommonPaths paths, ConfigurationInfoSource config) { - this(context, new Version(), new HistoryProvider(paths), config, new ClientPreferences(paths)); - } - - ShellCommand(BundleContext context, Version version, HistoryProvider provider, ConfigurationInfoSource config, ClientPreferences prefs) { - this.historyProvider = provider; - this.bundleContext = context; - this.version = version; - - this.prefs = prefs; - this.shellPrompt = new ShellPrompt(); - - try { - Map<String, String> promptConfig = config.getConfiguration("shell-command", "shell-prompt.conf"); - this.shellPrompt.overridePromptConfig(promptConfig); - } catch (IOException e) { - //Do nothing - } - } - - @Override - public void run(CommandContext ctx) throws CommandException { - Terminal term = TerminalFactory.create(); - PersistentHistory history = historyProvider.get(); - - try { - ctx.getConsole().getOutput().println(version.getVersionInfo()); - String userGuideUrl = new ApplicationInfo().getUserGuide(); - String userGuideMessage = t.localize(LocaleResources.COMMAND_SHELL_USER_GUIDE, userGuideUrl).getContents(); - ctx.getConsole().getOutput().println(userGuideMessage); - - ConsoleReader reader = createConsoleReader(ctx, term); - setupConsoleReader(reader, history); - shellMainLoop(ctx.getConsole(), reader); - } catch (IOException ex) { - throw new CommandException(t.localize(LocaleResources.COMMAND_SHELL_IO_EXCEPTION), ex); - } finally { - closeTerminal(term); - if (history != null) { - try { - history.flush(); - } catch (IOException e) { - logger.log(Level.WARNING, "Unable to save history", e); - } - } - } - } - - private void setupConsoleReader(ConsoleReader reader, History history) throws IOException { - reader.setHandleUserInterrupt(true); - reader.setPrompt(shellPrompt.getPrompt()); - if (completerServiceRegistry != null) { - completerServiceRegistry.start(); - } - tabCompletion.attachToReader(reader); - if (history != null) { - reader.setHistory(history); - } - CandidateListCompletionHandler completionHandler = new CandidateListCompletionHandler(); - completionHandler.setPrintSpaceAfterFullCompletion(false); - reader.setCompletionHandler(completionHandler); - } - - // package-private for testing - ConsoleReader createConsoleReader(CommandContext ctx, Terminal terminal) throws IOException { - return new ConsoleReader(ctx.getConsole().getInput(), ctx.getConsole().getOutput(), terminal); - } - - private void closeTerminal(Terminal term) { - try { - term.restore(); - } catch (Exception e) { - logger.log(Level.WARNING, "Error restoring terminal state.", e); - } - } - - private void shellMainLoop(Console console, ConsoleReader reader) throws IOException, CommandException { - try { - while (handleConsoleInput(console, reader, shellPrompt.getPrompt())) { /* no-op; the loop conditional performs the action */ } - } finally { - reader.shutdown(); - } - } - - /** - * @return true if the shell should continue accepting more input or false if the shell should quit - */ - private boolean handleConsoleInput(Console console, ConsoleReader reader, String prompt) throws IOException, CommandException { - String line; - try { - line = reader.readLine(prompt); - } catch (UserInterruptException uie) { - return handleUserInterrupt(reader, console); - } - if (line == null) { - // ex. Ctrl-D on empty line - return false; - } - line = line.trim(); - if (line.equals("")) { - return true; - } else if (exitKeywords.contains(line)) { - return false; - } else if (clearKeywords.contains(line)) { - reader.clearScreen(); - return true; - } else { - launchCommand(line); - return true; - } - } - - private boolean handleUserInterrupt(ConsoleReader reader, Console console) { - String prompt = reader.getPrompt(); - try { - console.getOutput().println(t.localize(LocaleResources.QUIT_PROMPT).getContents()); - - String confirmChars = t.localize(LocaleResources.QUIT_CONFIRM).getContents(); - String denyChars = t.localize(LocaleResources.QUIT_DENY).getContents(); - char[] expectedChars = (confirmChars + denyChars).toCharArray(); - - char val; - try { - val = (char) reader.readCharacter(expectedChars); - } catch (IOException ioe) { - return false; - } - - return confirmChars.indexOf(val) == -1; - } finally { - reader.setPrompt(prompt); - } - } - - private void launchCommand(String line) throws CommandException { - ShellArgsParser parser = new ShellArgsParser(line); - String[] parsed = parser.parse(); - ShellArgsParser.Issues issues = parser.getParseIssues(); - if (!issues.getAllIssues().isEmpty()) { - ShellArgsParser.IssuesFormatter issuesFormatter = new ShellArgsParser.IssuesFormatter(); - if (!issues.getWarnings().isEmpty()) { - String formattedIssues = issuesFormatter.format(issues.getWarnings()); - logger.warning(t.localize(LocaleResources.PARSER_WARNING, formattedIssues).getContents()); - } - if (!issues.getErrors().isEmpty()) { - String formattedIssues = issuesFormatter.format(issues.getErrors()); - logger.warning(t.localize(LocaleResources.PARSER_ERROR, formattedIssues).getContents()); - return; - } - } - ServiceReference launcherRef = bundleContext.getServiceReference(Launcher.class.getName()); - if (launcherRef != null) { - Launcher launcher = (Launcher) bundleContext.getService(launcherRef); - launcher.run(parsed, true); - bundleContext.ungetService(launcherRef); - } else { - throw new CommandException(t.localize(LocaleResources.MISSING_LAUNCHER)); - } - } - - void setTabCompletion(TabCompletion tabCompletion) { - this.tabCompletion = tabCompletion; - } - - @Override - public boolean isStorageRequired() { - return false; - } - - public void dbServiceAvailable(DbService dbService) { - this.shellPrompt.storageConnected(dbService); - } - - public void dbServiceUnavailable() { - this.shellPrompt.storageDisconnected(); - } - - public void setCommandInfoSource(final CommandInfoSource source) { - this.commandInfoSource = source; - if (commandInfoSource != null && tabCompletion != null) { - tabCompletion.setupTabCompletion(commandInfoSource); - } - } - - public void setCompleterServiceRegistry(CompleterServiceRegistry completerServiceRegistry) { - this.completerServiceRegistry = completerServiceRegistry; - } - -} -
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/ShellPrompt.java Wed May 17 18:11:05 2017 -0400 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,170 +0,0 @@ -/* - * Copyright 2012-2017 Red Hat, Inc. - * - * This file is part of Thermostat. - * - * Thermostat is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published - * by the Free Software Foundation; either version 2, or (at your - * option) any later version. - * - * Thermostat is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Thermostat; see the file COPYING. If not see - * <http://www.gnu.org/licenses/>. - * - * Linking this code with other modules is making a combined work - * based on this code. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. - * - * As a special exception, the copyright holders of this code give - * you permission to link this code with independent modules to - * produce an executable, regardless of the license terms of these - * independent modules, and to copy and distribute the resulting - * executable under terms of your choice, provided that you also - * meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module - * which is not derived from or based on this code. If you modify - * this code, you may extend this exception to your version of the - * library, but you are not obligated to do so. If you do not wish - * to do so, delete this exception statement from your version. - */ - -package com.redhat.thermostat.launcher.internal; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.redhat.thermostat.common.utils.LoggingUtils; -import com.redhat.thermostat.shared.locale.Translate; -import com.redhat.thermostat.storage.core.DbService; - -public class ShellPrompt { - - public static final String DEFAULT_CONNECTED_TOKEN = "+"; - public static final String DEFAULT_DISCONNECTED_TOKEN = "-"; - - private static final String SHELL_PROMPT_FORMAT_KEY = "shell-prompt"; - private static final String CONNECT_PROMPT_FORMAT_KEY = "connected-prompt"; - private static final String DISCONNECT_PROMPT_FORMAT_KEY = "disconnected-prompt"; - - private static final String DEFAULT_PROMPT_FORMAT = "Thermostat %connect > "; - - private static final Logger logger = LoggingUtils.getLogger(ShellCommand.class); - private static final Translate<LocaleResources> t = LocaleResources.createLocalizer(); - - private Map<String, String> promptConfig = new HashMap<>(); - - private enum Tokens { - CONNECT("%connect", DEFAULT_DISCONNECTED_TOKEN), //Default to disconnected - - CONNECTION_URL("%url", ""), - - PROTOCOL("%protocol", ""), - HOST("%host", ""), - PORT("%port", ""), - - USER("%user", ""), - //TODO: implement tokens below - SECURE("%secure", ""), - ; - - private String token; - private String defaultValue; - - private Tokens(String token, String defaultValue) { - this.token = token; - this.defaultValue = defaultValue; - } - - public String getToken() { - return this.token; - } - - public String getDefaultValue() { - return this.defaultValue; - } - } - - public ShellPrompt() { - promptConfig.put(SHELL_PROMPT_FORMAT_KEY, DEFAULT_PROMPT_FORMAT); - promptConfig.put(CONNECT_PROMPT_FORMAT_KEY, DEFAULT_CONNECTED_TOKEN); - promptConfig.put(DISCONNECT_PROMPT_FORMAT_KEY, DEFAULT_DISCONNECTED_TOKEN); - } - - public String getPrompt() { - String format = promptConfig.get(SHELL_PROMPT_FORMAT_KEY); - return replaceTokens(format); - } - - private String replaceTokens(String prompt) { - for (Tokens t : Tokens.values()) { - String token = t.getToken(); - prompt = prompt.replaceAll(token, - promptConfig.containsKey(token) ? promptConfig.get(token) : t.getDefaultValue()); - } - return prompt; - } - - public void storageConnected(DbService dbService) { - String connectionURL = dbService.getConnectionUrl(); - - buildUrlTokens(connectionURL); - promptConfig.put(Tokens.USER.getToken(), dbService.getUserName()); - - buildConnectToken(CONNECT_PROMPT_FORMAT_KEY); - } - - public void storageDisconnected() { - clearUrlTokens(); - promptConfig.put(Tokens.USER.getToken(), Tokens.USER.getDefaultValue()); - - buildConnectToken(DISCONNECT_PROMPT_FORMAT_KEY); - } - - private void buildConnectToken(String promptFormatKey) { - //Reset connect token beforehand since replaceTokens will use the value - promptConfig.put(Tokens.CONNECT.getToken(), ""); - promptConfig.put(Tokens.CONNECT.getToken(), replaceTokens(promptConfig.get(promptFormatKey))); - } - - private void buildUrlTokens(String connectionURL) { - try { - URI uri = new URI(connectionURL); - promptConfig.put(Tokens.CONNECTION_URL.getToken(), uri.toString()); - promptConfig.put(Tokens.PROTOCOL.getToken(), uri.getScheme()); - promptConfig.put(Tokens.HOST.getToken(), uri.getHost()); - - int port = uri.getPort(); - promptConfig.put(Tokens.PORT.getToken(), (port >= 0) ? String.valueOf(port) : ""); - } catch (URISyntaxException e) { - logger.log(Level.WARNING, t.localize(LocaleResources.INVALID_DB_URL, connectionURL).getContents()); - promptConfig.put(Tokens.CONNECT.getToken(), connectionURL); - } - } - - private void clearUrlTokens() { - promptConfig.put(Tokens.CONNECTION_URL.getToken(), Tokens.CONNECTION_URL.getDefaultValue()); - promptConfig.put(Tokens.PROTOCOL.getToken(), Tokens.PROTOCOL.getDefaultValue()); - promptConfig.put(Tokens.HOST.getToken(), Tokens.HOST.getDefaultValue()); - promptConfig.put(Tokens.PORT.getToken(), Tokens.PORT.getDefaultValue()); - } - - public void overridePromptConfig(Map<String, String> newConfig) { - for (Map.Entry<String, String> entry : newConfig.entrySet()) { - this.promptConfig.put(entry.getKey(), entry.getValue()); - } - - if (newConfig.containsKey(DISCONNECT_PROMPT_FORMAT_KEY)) { - buildConnectToken(DISCONNECT_PROMPT_FORMAT_KEY); - } - } -}
--- a/launcher/src/main/java/com/redhat/thermostat/launcher/internal/TabCompletion.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/main/java/com/redhat/thermostat/launcher/internal/TabCompletion.java Wed May 17 18:12:02 2017 -0400 @@ -256,20 +256,18 @@ public void setupTabCompletion(CommandInfoSource commandInfoSource) { for (CommandInfo info : commandInfoSource.getCommandInfos()) { - if (info.getEnvironments().contains(Environment.SHELL)) { - String commandName = info.getName(); - TreeCompleter.Node command = getCommandByName(commandName); + String commandName = info.getName(); + TreeCompleter.Node command = getCommandByName(commandName); - setupSubcommandCompletion(command, info); + setupSubcommandCompletion(command, info); - for (Option option : (Collection<Option>) info.getOptions().getOptions()) { - setupDefaultCompletion(command, option); - } + for (Option option : (Collection<Option>) info.getOptions().getOptions()) { + setupDefaultCompletion(command, option); + } - addHelpOptionIfRequired(command); + addHelpOptionIfRequired(command); - treeCompleter.addBranch(command); - } + treeCompleter.addBranch(command); } }
--- a/launcher/src/test/java/com/redhat/thermostat/launcher/internal/ActivatorTest.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/test/java/com/redhat/thermostat/launcher/internal/ActivatorTest.java Wed May 17 18:12:02 2017 -0400 @@ -154,12 +154,12 @@ assertCommandIsRegistered(context, "help", HelpCommand.class); - verify(mockTracker, times(3)).open(); + verify(mockTracker, times(2)).open(); Action action = actionCaptor.getValue(); assertNotNull(action); activator.stop(context); - verify(mockTracker, times(3)).close(); + verify(mockTracker, times(2)).close(); } @Test @@ -169,18 +169,11 @@ MultipleServiceTracker launcherDepsTracker = mock(MultipleServiceTracker.class); Class<?>[] launcherDeps = new Class[] { CommonPaths.class, - SSLConfiguration.class, }; whenNew(MultipleServiceTracker.class).withParameterTypes(BundleContext.class, Class[].class, Action.class).withArguments(eq(context), eq(launcherDeps), actionCaptor.capture()).thenReturn(launcherDepsTracker); MultipleServiceTracker unusedTracker = mock(MultipleServiceTracker.class); - Class<?>[] shellDeps = new Class[] { - CommonPaths.class, - ConfigurationInfoSource.class, - }; - whenNew(MultipleServiceTracker.class).withParameterTypes(BundleContext.class, Class[].class, Action.class).withArguments(eq(context), - eq(shellDeps), actionCaptor.capture()).thenReturn(unusedTracker); Class<?>[] vmIdCompleterDeps = new Class[] { VmInfoDAO.class, AgentInfoDAO.class @@ -201,7 +194,6 @@ Activator activator = new Activator(); ConfigurationInfoSource configurationInfoSource = mock(ConfigurationInfoSource.class); - when(configurationInfoSource.getConfiguration("shell-command", "shell-prompt.conf")).thenReturn(new HashMap<String, String>()); context.registerService(ConfigurationInfoSource.class, configurationInfoSource, null); activator.start(context); @@ -210,7 +202,6 @@ Action action = actionCaptor.getAllValues().get(0); assertNotNull(action); - SSLConfiguration sslConfiguration = mock(SSLConfiguration.class); CommonPaths paths = mock(CommonPaths.class); when(paths.getSystemThermostatHome()).thenReturn(mock(File.class)); when(paths.getUserThermostatHome()).thenReturn(mock(File.class)); @@ -227,8 +218,7 @@ Map<String, Object> services = new HashMap<>(); services.put(CommonPaths.class.getName(), paths); services.put(ConfigurationInfoSource.class.getName(), configurationInfoSource); - services.put(SSLConfiguration.class.getName(), sslConfiguration); - action.dependenciesAvailable(new DependencyProvider(services)); + action.dependenciesAvailable(new DependencyProvider(services)); assertTrue(context.isServiceRegistered(CommandInfoSource.class.getName(), mock(CompoundCommandInfoSource.class).getClass())); assertTrue(context.isServiceRegistered(BundleManager.class.getName(), BundleManagerImpl.class)); @@ -243,77 +233,6 @@ assertFalse(context.isServiceRegistered(Launcher.class.getName(), LauncherImpl.class)); } - @Test - public void testServiceTrackerCustomizerForShellTracker() throws Exception { - StubBundleContext context = new StubBundleContext(); - ArgumentCaptor<Action> actionCaptor = ArgumentCaptor.forClass(Action.class); - MultipleServiceTracker unusedTracker = mock(MultipleServiceTracker.class); - Class<?>[] launcherDeps = new Class[] { - CommonPaths.class, - SSLConfiguration.class, - }; - whenNew(MultipleServiceTracker.class).withParameterTypes(BundleContext.class, Class[].class, Action.class).withArguments(eq(context), - eq(launcherDeps), actionCaptor.capture()).thenReturn(unusedTracker); - - MultipleServiceTracker shellTracker = mock(MultipleServiceTracker.class); - Class<?>[] shellDeps = new Class[] { - CommonPaths.class, - ConfigurationInfoSource.class, - }; - whenNew(MultipleServiceTracker.class).withParameterTypes(BundleContext.class, Class[].class, Action.class).withArguments(eq(context), - eq(shellDeps), actionCaptor.capture()).thenReturn(shellTracker); - Class<?>[] vmIdCompleterDeps = new Class[] { - VmInfoDAO.class, - AgentInfoDAO.class - }; - whenNew(MultipleServiceTracker.class).withParameterTypes(BundleContext.class, Class[].class, Action.class).withArguments(eq(context), - eq(vmIdCompleterDeps), actionCaptor.capture()).thenReturn(unusedTracker); - Class<?>[] agentIdCompleterDeps = new Class[] { - AgentInfoDAO.class - }; - whenNew(MultipleServiceTracker.class).withParameterTypes(BundleContext.class, Class[].class, Action.class).withArguments(eq(context), - eq(agentIdCompleterDeps), actionCaptor.capture()).thenReturn(unusedTracker); - Class<?>[] helpCommandDeps = new Class[] { - CommandInfoSource.class, - CommandGroupMetadataSource.class - }; - whenNew(MultipleServiceTracker.class).withParameterTypes(BundleContext.class, Class[].class, Action.class).withArguments(eq(context), - eq(helpCommandDeps), actionCaptor.capture()).thenReturn(unusedTracker); - - Activator activator = new Activator(); - ConfigurationInfoSource configurationInfoSource = mock(ConfigurationInfoSource.class); - when(configurationInfoSource.getConfiguration("shell-command", "shell-prompt.conf")).thenReturn(new HashMap<String, String>()); - context.registerService(ConfigurationInfoSource.class, configurationInfoSource, null); - - activator.start(context); - - Action action = actionCaptor.getAllValues().get(1); - - assertNotNull(action); - CommonPaths paths = mock(CommonPaths.class); - when(paths.getSystemLibRoot()).thenReturn(new File("")); - when(paths.getSystemPluginRoot()).thenReturn(new File("")); - when(paths.getUserPluginRoot()).thenReturn(new File("")); - when(paths.getUserClientConfigurationFile()).thenReturn(new File("")); - when(paths.getSystemPluginConfigurationDirectory()).thenReturn(new File("")); - when(paths.getUserPluginConfigurationDirectory()).thenReturn(new File("")); - @SuppressWarnings("rawtypes") - ServiceRegistration pathsReg = context.registerService(CommonPaths.class, paths, null); - Map<String, Object> services = new HashMap<>(); - services.put(CommonPaths.class.getName(), paths); - services.put(ConfigurationInfoSource.class.getName(), configurationInfoSource); - action.dependenciesAvailable(new DependencyProvider(services)); - - assertTrue(context.isServiceRegistered(Command.class.getName(), ShellCommand.class)); - - action.dependenciesUnavailable(); - pathsReg.unregister(); - - assertFalse(context.isServiceRegistered(CommandInfoSource.class.getName(), CompoundCommandInfoSource.class)); - assertFalse(context.isServiceRegistered(BundleManager.class.getName(), BundleManagerImpl.class)); - assertFalse(context.isServiceRegistered(Launcher.class.getName(), LauncherImpl.class)); - } - private Path createStubThermostatHome() throws Exception { Path tempDir = Files.createTempDirectory("test"); tempDir.toFile().deleteOnExit();
--- a/launcher/src/test/java/com/redhat/thermostat/launcher/internal/BasicCommandInfoTest.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/test/java/com/redhat/thermostat/launcher/internal/BasicCommandInfoTest.java Wed May 17 18:12:02 2017 -0400 @@ -39,9 +39,7 @@ import static org.junit.Assert.assertEquals; import java.util.Collections; -import java.util.EnumSet; import java.util.List; -import java.util.Set; import org.apache.commons.cli.Options; import org.junit.Test; @@ -56,14 +54,12 @@ final String SUMMARY = "some-summary"; final String DESCRIPTION = "some-description"; final List<String> COMMAND_GROUPS = Collections.singletonList("some-command-group"); - final List<String> COMMAND_GROUP_METADATAS = Collections.emptyList(); final String USAGE = "some-usage"; final Options OPTIONS = new Options(); final List<PluginConfiguration.Subcommand> SUBCOMMANDS = Collections.emptyList(); - final Set<Environment> ENVIRONMENT = EnumSet.noneOf(Environment.class); final List<BundleInformation> BUNDLES = Collections.emptyList(); - BasicCommandInfo info = new BasicCommandInfo(NAME, SUMMARY, DESCRIPTION, COMMAND_GROUPS, USAGE, OPTIONS, SUBCOMMANDS, ENVIRONMENT, BUNDLES); + BasicCommandInfo info = new BasicCommandInfo(NAME, SUMMARY, DESCRIPTION, COMMAND_GROUPS, USAGE, OPTIONS, SUBCOMMANDS, BUNDLES); assertEquals(NAME, info.getName()); assertEquals(SUMMARY, info.getSummary());
--- a/launcher/src/test/java/com/redhat/thermostat/launcher/internal/BuiltInCommandInfoTest.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/test/java/com/redhat/thermostat/launcher/internal/BuiltInCommandInfoTest.java Wed May 17 18:12:02 2017 -0400 @@ -46,7 +46,6 @@ import java.util.Collection; import java.util.List; import java.util.Properties; -import java.util.Set; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; @@ -312,18 +311,5 @@ BuiltInCommandInfo info = new BuiltInCommandInfo(name, props); } - @Test - public void verifyEnviornment() { - Properties props = new Properties(); - String name = "name"; - String env = "cli, shell"; - props.put("environments", env); - BuiltInCommandInfo info = new BuiltInCommandInfo(name, props); - - Set<Environment> commandEnv = info.getEnvironments(); - assertTrue(commandEnv.contains(Environment.CLI)); - assertTrue(commandEnv.contains(Environment.SHELL)); - } - }
--- a/launcher/src/test/java/com/redhat/thermostat/launcher/internal/CurrentEnvironmentTest.java Wed May 17 18:11:05 2017 -0400 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,76 +0,0 @@ -/* - * Copyright 2012-2017 Red Hat, Inc. - * - * This file is part of Thermostat. - * - * Thermostat is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published - * by the Free Software Foundation; either version 2, or (at your - * option) any later version. - * - * Thermostat is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Thermostat; see the file COPYING. If not see - * <http://www.gnu.org/licenses/>. - * - * Linking this code with other modules is making a combined work - * based on this code. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. - * - * As a special exception, the copyright holders of this code give - * you permission to link this code with independent modules to - * produce an executable, regardless of the license terms of these - * independent modules, and to copy and distribute the resulting - * executable under terms of your choice, provided that you also - * meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module - * which is not derived from or based on this code. If you modify - * this code, you may extend this exception to your version of the - * library, but you are not obligated to do so. If you do not wish - * to do so, delete this exception statement from your version. - */ - -package com.redhat.thermostat.launcher.internal; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import org.junit.Test; - -import com.redhat.thermostat.launcher.internal.CurrentEnvironment.CurrentEnvironmentChangeListener; - -public class CurrentEnvironmentTest { - - @Test - public void verifyInitialization() { - CurrentEnvironment environment = new CurrentEnvironment(Environment.CLI); - - assertEquals(Environment.CLI, environment.getCurrent()); - } - - @Test - public void verifySetAndGet() { - CurrentEnvironment environment = new CurrentEnvironment(Environment.CLI); - environment.setCurrent(Environment.SHELL); - - assertEquals(Environment.SHELL, environment.getCurrent()); - } - - @Test - public void verifyListenersAreInvoked() { - CurrentEnvironment environment = new CurrentEnvironment(Environment.CLI); - CurrentEnvironmentChangeListener listener = mock(CurrentEnvironmentChangeListener.class); - - environment.addListener(listener); - - environment.setCurrent(Environment.SHELL); - - verify(listener).enviornmentChanged(Environment.CLI, Environment.SHELL); - } -} -
--- a/launcher/src/test/java/com/redhat/thermostat/launcher/internal/HelpCommandTest.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/test/java/com/redhat/thermostat/launcher/internal/HelpCommandTest.java Wed May 17 18:12:02 2017 -0400 @@ -45,7 +45,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.EnumSet; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; @@ -116,7 +115,10 @@ cmd.setCommandGroupMetadataSource(commandGroupMetadataSource); Arguments args = mock(Arguments.class); cmd.run(ctxFactory.createContext(args)); - String expected = "list of commands:\n\n"; + String expected = "list of global options:\n\n" + + GLOBAL_OPTIONS + + "\n" + + "list of commands:\n\n"; String actual = ctxFactory.getOutput(); assertEquals(expected, actual); } @@ -128,20 +130,17 @@ CommandInfo info1 = mock(CommandInfo.class); when(info1.getName()).thenReturn("test1"); when(info1.getSummary()).thenReturn("test command 1"); - when(info1.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); infoList.add(info1); CommandInfo info2 = mock(CommandInfo.class); when(info2.getName()).thenReturn("test2longname"); when(info2.getSummary()).thenReturn("test command 2"); - when(info2.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); infoList.add(info2); when(commandInfoSource.getCommandInfos()).thenReturn(infoList); HelpCommand cmd = new HelpCommand(); - cmd.setEnvironment(Environment.CLI); cmd.setCommandInfoSource(commandInfoSource); cmd.setCommandGroupMetadataSource(commandGroupMetadataSource); @@ -165,7 +164,6 @@ when(testCommandInfo.getUsage()).thenReturn("usage of test command"); when(testCommandInfo.getDescription()).thenReturn("description of test command"); when(testCommandInfo.getOptions()).thenReturn(new Options()); - when(testCommandInfo.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI)); PluginConfiguration.Subcommand subcommand = mock(PluginConfiguration.Subcommand.class); when(subcommand.getName()).thenReturn("subcommand"); @@ -186,8 +184,7 @@ String actual = ctxFactory.getOutput(); assertEquals("usage: thermostat usage of test command\n" + - " description of test command\n" + - "Note: this command is only supported outside the shell\n" + + " description of test command\n\n" + "thermostat test1\n" + " --help show usage of command\n\n" + "Subcommands:\n" + @@ -202,32 +199,26 @@ CommandInfo helpInfo = mock(CommandInfo.class); when(helpInfo.getName()).thenReturn("help"); when(helpInfo.getSummary()).thenReturn("show help"); - when(helpInfo.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); CommandInfo info1 = mock(CommandInfo.class); when(info1.getName()).thenReturn("test1"); when(info1.getSummary()).thenReturn("test command 1"); - when(info1.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); CommandInfo info2 = mock(CommandInfo.class); when(info2.getName()).thenReturn("test2"); when(info2.getSummary()).thenReturn("test command 2"); - when(info2.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); CommandInfo info3 = mock(CommandInfo.class); when(info3.getName()).thenReturn("test3"); when(info3.getSummary()).thenReturn("test command 3"); - when(info3.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); CommandInfo info4 = mock(CommandInfo.class); when(info4.getName()).thenReturn("test4"); when(info4.getSummary()).thenReturn("test command 4"); - when(info4.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); when(commandInfoSource.getCommandInfos()).thenReturn(Arrays.asList(info2, helpInfo, info4, info3, info1)); HelpCommand cmd = new HelpCommand(); - cmd.setEnvironment(Environment.CLI); cmd.setCommandInfoSource(commandInfoSource); cmd.setCommandGroupMetadataSource(commandGroupMetadataSource); Arguments args = mock(Arguments.class); @@ -248,90 +239,6 @@ } @Test - public void verifyHelpFiltersCommands() { - CommandInfo helpInfo = mock(CommandInfo.class); - when(helpInfo.getName()).thenReturn("help"); - when(helpInfo.getSummary()).thenReturn("show help"); - when(helpInfo.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI)); - - CommandInfo info1 = mock(CommandInfo.class); - when(info1.getName()).thenReturn("test1"); - when(info1.getSummary()).thenReturn("test command 1"); - when(info1.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); - - CommandInfo info2 = mock(CommandInfo.class); - when(info2.getName()).thenReturn("test2"); - when(info2.getSummary()).thenReturn("test command 2"); - when(info2.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI)); - - CommandInfo info3 = mock(CommandInfo.class); - when(info3.getName()).thenReturn("test3"); - when(info3.getSummary()).thenReturn("test command 3"); - when(info3.getEnvironments()).thenReturn(EnumSet.of(Environment.SHELL)); - - CommandInfo info4 = mock(CommandInfo.class); - when(info4.getName()).thenReturn("test4"); - when(info4.getSummary()).thenReturn("test command 4"); - when(info4.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI)); - - when(commandInfoSource.getCommandInfos()).thenReturn(Arrays.asList(info2, helpInfo, info4, info3, info1)); - - HelpCommand cmd = new HelpCommand(); - cmd.setEnvironment(Environment.CLI); - cmd.setCommandInfoSource(commandInfoSource); - cmd.setCommandGroupMetadataSource(commandGroupMetadataSource); - Arguments args = mock(Arguments.class); - when(args.getNonOptionArguments()).thenReturn(new ArrayList<String>()); - cmd.run(ctxFactory.createContext(args)); - - String actual = ctxFactory.getOutput(); - String expected = "list of global options:\n\n" - + GLOBAL_OPTIONS - + "\n" - + "list of commands:\n\n" - + " help show help\n" - + " test1 test command 1\n" - + " test2 test command 2\n" - + " test4 test command 4\n"; - assertEquals(expected, actual); - } - - @Test - public void verifyHelpFiltersOptions() { - CommandInfo helpInfo = mock(CommandInfo.class); - when(helpInfo.getName()).thenReturn("help"); - when(helpInfo.getSummary()).thenReturn("show help"); - when(helpInfo.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); - - CommandInfo info1 = mock(CommandInfo.class); - when(info1.getName()).thenReturn("test1"); - when(info1.getSummary()).thenReturn("test command 1"); - when(info1.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); - - CommandInfo info2 = mock(CommandInfo.class); - when(info2.getName()).thenReturn("test2"); - when(info2.getSummary()).thenReturn("test command 2"); - when(info2.getEnvironments()).thenReturn(EnumSet.of(Environment.SHELL)); - - when(commandInfoSource.getCommandInfos()).thenReturn(Arrays.asList(info2, helpInfo, info1)); - - HelpCommand cmd = new HelpCommand(); - cmd.setEnvironment(Environment.SHELL); - cmd.setCommandInfoSource(commandInfoSource); - cmd.setCommandGroupMetadataSource(commandGroupMetadataSource); - Arguments args = mock(Arguments.class); - when(args.getNonOptionArguments()).thenReturn(new ArrayList<String>()); - cmd.run(ctxFactory.createContext(args)); - - String actual = ctxFactory.getOutput(); - String expected = "list of commands:\n\n" - + " help show help\n" - + " test1 test command 1\n" - + " test2 test command 2\n"; - assertEquals(expected, actual); - } - - @Test public void verifyHelpUnknownCmdPrintsSummaries() { when(commandInfoSource.getCommandInfo("test1")).thenThrow(new CommandInfoNotFoundException("test1")); @@ -357,7 +264,6 @@ when(info1.getDescription()).thenReturn("description of test1 command"); when(info1.getCommandGroups()).thenReturn(Collections.singletonList("group")); when(info1.getOptions()).thenReturn(new Options()); - when(info1.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI)); CommandInfo info2 = mock(CommandInfo.class); when(info2.getName()).thenReturn("test2"); @@ -365,7 +271,6 @@ when(info2.getDescription()).thenReturn("description of test2 command"); when(info2.getCommandGroups()).thenReturn(Collections.singletonList("group")); when(info2.getOptions()).thenReturn(new Options()); - when(info2.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI)); CommandInfo info3 = mock(CommandInfo.class); when(info3.getName()).thenReturn("test3"); @@ -373,7 +278,6 @@ when(info3.getDescription()).thenReturn("description of test3 command"); when(info3.getCommandGroups()).thenReturn(Collections.<String>emptyList()); when(info3.getOptions()).thenReturn(new Options()); - when(info3.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI)); when(commandInfoSource.getCommandInfo("test1")).thenReturn(info1); when(commandInfoSource.getCommandInfo("test2")).thenReturn(info2); @@ -381,7 +285,6 @@ when(commandInfoSource.getCommandInfos()).thenReturn(Arrays.asList(info1, info2, info3)); HelpCommand cmd = new HelpCommand(); - cmd.setEnvironment(Environment.CLI); cmd.setCommandInfoSource(commandInfoSource); cmd.setCommandGroupMetadataSource(commandGroupMetadataSource); Arguments args = mock(Arguments.class); @@ -412,13 +315,11 @@ when(commandInfo.getSummary()).thenReturn("summary of test1 command"); when(commandInfo.getCommandGroups()).thenReturn(Arrays.asList("group1", "group2")); when(commandInfo.getOptions()).thenReturn(new Options()); - when(commandInfo.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI)); when(commandInfoSource.getCommandInfo("test1")).thenReturn(commandInfo); when(commandInfoSource.getCommandInfos()).thenReturn(Collections.singleton(commandInfo)); HelpCommand cmd = new HelpCommand(); - cmd.setEnvironment(Environment.CLI); cmd.setCommandInfoSource(commandInfoSource); cmd.setCommandGroupMetadataSource(commandGroupMetadataSource); Arguments args = mock(Arguments.class);
--- a/launcher/src/test/java/com/redhat/thermostat/launcher/internal/LauncherImplTest.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/test/java/com/redhat/thermostat/launcher/internal/LauncherImplTest.java Wed May 17 18:12:02 2017 -0400 @@ -36,13 +36,10 @@ package com.redhat.thermostat.launcher.internal; -import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -58,8 +55,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.EnumSet; -import java.util.List; import java.util.concurrent.ExecutorService; import java.util.logging.Handler; import java.util.logging.Level; @@ -73,7 +68,6 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.mockito.ArgumentCaptor; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; @@ -81,15 +75,12 @@ import com.redhat.thermostat.common.ActionNotifier; import com.redhat.thermostat.common.ApplicationService; import com.redhat.thermostat.common.ExitStatus; -import com.redhat.thermostat.common.Pair; import com.redhat.thermostat.common.Version; import com.redhat.thermostat.common.cli.AbstractStateNotifyingCommand; import com.redhat.thermostat.common.cli.Arguments; -import com.redhat.thermostat.common.cli.Command; import com.redhat.thermostat.common.cli.CommandContext; import com.redhat.thermostat.common.cli.CommandException; import com.redhat.thermostat.common.cli.CommandRegistry; -import com.redhat.thermostat.common.config.ClientPreferences; import com.redhat.thermostat.common.internal.test.TestCommandContextFactory; import com.redhat.thermostat.common.internal.test.TestTimerFactory; import com.redhat.thermostat.common.tools.ApplicationState; @@ -97,11 +88,7 @@ import com.redhat.thermostat.launcher.BundleManager; import com.redhat.thermostat.launcher.internal.DisallowSystemExitSecurityManager.ExitException; import com.redhat.thermostat.shared.config.CommonPaths; -import com.redhat.thermostat.shared.config.SSLConfiguration; import com.redhat.thermostat.shared.locale.LocalizedString; -import com.redhat.thermostat.storage.core.DbService; -import com.redhat.thermostat.storage.core.DbServiceFactory; -import com.redhat.thermostat.storage.core.StorageCredentials; import com.redhat.thermostat.testutils.StubBundleContext; public class LauncherImplTest { @@ -154,16 +141,13 @@ private TestTimerFactory timerFactory; private BundleManager registry; private Version version; - private DbServiceFactory dbServiceFactory; private CommandInfoSource infos; private CommandGroupMetadataSource commandGroupMetadataSource; private ActionNotifier<ApplicationState> notifier; private LauncherImpl launcher; - private CurrentEnvironment environment; private CommonPaths paths; - private SSLConfiguration sslConf; @SuppressWarnings("unchecked") @Before @@ -187,7 +171,6 @@ when(info1.getSummary()).thenReturn("description 1"); when(info1.getDescription()).thenReturn("description 1"); when(info1.getOptions()).thenReturn(options1); - when(info1.getEnvironments()).thenReturn(EnumSet.of(Environment.SHELL, Environment.CLI)); TestCommand cmd2 = new TestCommand(new TestCmd2()); CommandInfo info2 = mock(CommandInfo.class); @@ -199,7 +182,6 @@ options2.addOption(opt4); when(info2.getSummary()).thenReturn("description 2"); when(info2.getOptions()).thenReturn(options2); - when(info2.getEnvironments()).thenReturn(EnumSet.of(Environment.SHELL, Environment.CLI)); TestCommand cmd3 = new TestCommand(); CommandInfo info3 = mock(CommandInfo.class); @@ -207,7 +189,6 @@ cmd3.setStorageRequired(true); when(info3.getSummary()).thenReturn("description 3"); when(info3.getOptions()).thenReturn(new Options()); - when(info3.getEnvironments()).thenReturn(EnumSet.of(Environment.SHELL, Environment.CLI)); // This TestCommand object doesn't need to connect to storage, // and it is used to test commands without any required option @@ -217,13 +198,11 @@ cmd4.setStorageRequired(false); when(info4.getSummary()).thenReturn("description 4"); when(info4.getOptions()).thenReturn(new Options()); - when(info4.getEnvironments()).thenReturn(EnumSet.of(Environment.SHELL, Environment.CLI)); AbstractStateNotifyingCommand basicCmd = mock(AbstractStateNotifyingCommand.class); CommandInfo basicInfo = mock(CommandInfo.class); when(basicInfo.getName()).thenReturn("basic"); when(basicInfo.getSummary()).thenReturn("nothing that means anything"); - when(basicInfo.getEnvironments()).thenReturn(EnumSet.of(Environment.SHELL, Environment.CLI)); when(basicCmd.isStorageRequired()).thenReturn(false); Options options = new Options(); when(basicInfo.getOptions()).thenReturn(options); @@ -236,10 +215,8 @@ when(helpCommandInfo.getBundles()).thenReturn(new ArrayList<BundleInformation>()); when(helpCommandInfo.getOptions()).thenReturn(new Options()); when(helpCommandInfo.getUsage()).thenReturn("thermostat help"); - when(helpCommandInfo.getEnvironments()).thenReturn(EnumSet.of(Environment.SHELL, Environment.CLI)); HelpCommand helpCommand = new HelpCommand(); - helpCommand.setEnvironment(Environment.CLI); CommandRegistry reg = ctxFactory.getCommandRegistry(); reg.registerCommand("help", helpCommand); @@ -284,8 +261,6 @@ when(appSvc.getApplicationExecutor()).thenReturn(exec); bundleContext.registerService(ApplicationService.class, appSvc, null); - environment = mock(CurrentEnvironment.class); - dbServiceFactory = mock(DbServiceFactory.class); version = mock(Version.class); paths = mock(CommonPaths.class); @@ -295,7 +270,6 @@ File setupFile = mock(File.class); when(setupFile.exists()).thenReturn(true); when(paths.getUserSetupCompleteStampFile()).thenReturn(setupFile); - ClientPreferences prefs = new ClientPreferences(paths); userPluginRoot = Files.createTempDirectory("userPluginRoot").toFile(); systemPluginRoot = Files.createTempDirectory("systemPluginRoot").toFile(); @@ -306,9 +280,8 @@ when(paths.getSystemThermostatHome()).thenReturn(mock(File.class)); when(paths.getUserThermostatHome()).thenReturn(mock(File.class)); - sslConf = mock(SSLConfiguration.class); launcher = new LauncherImpl(bundleContext, ctxFactory, registry, infos, new CommandSource(bundleContext), - environment, dbServiceFactory, version, prefs, paths, sslConf); + version, paths); } @After @@ -331,11 +304,11 @@ @Test public void testMain() { - runAndVerifyCommand(new String[] {name1, "--arg1", "Hello", "--arg2", "World"}, "Hello, World", false); + runAndVerifyCommand(new String[] {name1, "--arg1", "Hello", "--arg2", "World"}, "Hello, World"); ctxFactory.reset(); - runAndVerifyCommand(new String[] {"test2", "--arg3", "Hello", "--arg4", "World"}, "World: Hello", false); + runAndVerifyCommand(new String[] {"test2", "--arg3", "Hello", "--arg4", "World"}, "World: Hello"); } @Test @@ -350,12 +323,12 @@ + " test2 description 2\n" + " test3 description 3\n" + " test4 description 4\n"; - runAndVerifyCommand(new String[0], expected, false); + runAndVerifyCommand(new String[0], expected); } @Test public void verifySetLogLevel() { - runAndVerifyCommand(new String[] {name1, "--logLevel", "WARNING", "--arg1", "Hello", "--arg2", "World"}, "Hello, World", false); + runAndVerifyCommand(new String[] {name1, "--logLevel", "WARNING", "--arg1", "Hello", "--arg2", "World"}, "Hello, World"); Logger globalLogger = Logger.getLogger("com.redhat.thermostat"); assertEquals(Level.WARNING, globalLogger.getLevel()); } @@ -372,7 +345,7 @@ + " test2 description 2\n" + " test3 description 3\n" + " test4 description 4\n"; - runAndVerifyCommand(new String[] {"--help"}, expected, false); + runAndVerifyCommand(new String[] {"--help"}, expected); } @Test @@ -387,7 +360,7 @@ + " test2 description 2\n" + " test3 description 3\n" + " test4 description 4\n"; - runAndVerifyCommand(new String[] {"-help"}, expected, false); + runAndVerifyCommand(new String[] {"-help"}, expected); } @Test @@ -402,7 +375,7 @@ + " test2 description 2\n" + " test3 description 3\n" + " test4 description 4\n"; - runAndVerifyCommand(new String[] {"foobarbaz"}, expected, false); + runAndVerifyCommand(new String[] {"foobarbaz"}, expected); } @Test @@ -417,7 +390,7 @@ + " test2 description 2\n" + " test3 description 3\n" + " test4 description 4\n"; - runAndVerifyCommand(new String[] {"foo", "--bar", "baz"}, expected, false); + runAndVerifyCommand(new String[] {"foo", "--bar", "baz"}, expected); } @Test @@ -434,7 +407,7 @@ when(info1.getSubcommands()).thenReturn(Collections.singletonList(subInfo)); String expected = "foo, bar"; - runAndVerifyCommand(new String[] {"test1", "sub", "--opt", "--arg1", "foo", "--arg2", "bar"}, expected, false); + runAndVerifyCommand(new String[] {"test1", "sub", "--opt", "--arg1", "foo", "--arg2", "bar"}, expected); } @Test @@ -465,7 +438,7 @@ "\n" + "sub:\n" + "subcommand description\n\n\n"; - runAndVerifyCommand(new String[] {"test1", "sub", "--arg1", "foo", "--arg2", "bar"}, expected, false); + runAndVerifyCommand(new String[] {"test1", "sub", "--arg1", "foo", "--arg2", "bar"}, expected); } @Test @@ -482,7 +455,7 @@ when(info1.getSubcommands()).thenReturn(Collections.singletonList(subInfo)); String expected = "foo, bar"; - runAndVerifyCommand(new String[] {"test1", "sub", "--opt", "--arg1", "foo", "--arg2", "bar"}, expected, false); + runAndVerifyCommand(new String[] {"test1", "sub", "--opt", "--arg1", "foo", "--arg2", "bar"}, expected); } @Test @@ -499,7 +472,7 @@ when(info1.getSubcommands()).thenReturn(Collections.singletonList(subInfo)); String expected = "foo, bar"; - runAndVerifyCommand(new String[] {"test1", "--arg1", "foo", "--arg2", "bar"}, expected, false); + runAndVerifyCommand(new String[] {"test1", "--arg1", "foo", "--arg2", "bar"}, expected); } // This tests the case where we have a parent command "test1" with subcommand "sub", @@ -523,7 +496,7 @@ when(info1.getSubcommands()).thenReturn(Collections.singletonList(subInfo)); String expected = "foo, bar"; - runAndVerifyCommand(new String[] {"test1", "--opt", "--arg1", "foo", "--arg2", "bar"}, expected, false); + runAndVerifyCommand(new String[] {"test1", "--opt", "--arg1", "foo", "--arg2", "bar"}, expected); } // This tests the case where we have a parent command "test1" with subcommand "sub", @@ -548,7 +521,7 @@ when(info1.getSubcommands()).thenReturn(Collections.singletonList(subInfo)); String expected = "null, bar"; - runAndVerifyCommand(new String[] {"test1", "sub", "--arg1", "foo", "--arg2", "bar"}, expected, false); + runAndVerifyCommand(new String[] {"test1", "sub", "--arg1", "foo", "--arg2", "bar"}, expected); } @Test @@ -589,7 +562,7 @@ + " --arg2 <arg>\n" + " --help show usage of command\n" + " -l,--logLevel <arg>\n"; - runAndVerifyCommand(new String[] {"test1", "--arg1", "arg1value", "--argNotAccepted"}, expected, false); + runAndVerifyCommand(new String[] {"test1", "--arg1", "arg1value", "--argNotAccepted"}, expected); } @Test @@ -603,13 +576,13 @@ + " --arg2 <arg>\n" + " --help show usage of command\n" + " -l,--logLevel <arg>\n"; - runAndVerifyCommand(new String[] {"test1"}, expected, false); + runAndVerifyCommand(new String[] {"test1"}, expected); } @Test public void testMissingNotRequiredOption() { String expected = ""; - runAndVerifyCommand(new String[] {"test4"}, expected, false); + runAndVerifyCommand(new String[] {"test4"}, expected); } @Test @@ -623,7 +596,7 @@ + " --arg2 <arg>\n" + " --help show usage of command\n" + " -l,--logLevel <arg>\n"; - runAndVerifyCommand(new String[] {"test1", "--arg1"}, expected, false); + runAndVerifyCommand(new String[] {"test1", "--arg1"}, expected); } @Test @@ -638,7 +611,7 @@ + " test2 description 2\n" + " test3 description 3\n" + " test4 description 4\n"; - runAndVerifyCommand(new String[] {"foo"}, expected, false); + runAndVerifyCommand(new String[] {"foo"}, expected); } @Test @@ -655,99 +628,32 @@ CommandInfo cmdInfo = mock(CommandInfo.class); when(cmdInfo.getName()).thenReturn("error"); when(cmdInfo.getOptions()).thenReturn(new Options()); - when(cmdInfo.getEnvironments()).thenReturn(EnumSet.of(Environment.SHELL, Environment.CLI)); when(infos.getCommandInfo("error")).thenReturn(cmdInfo); - wrappedRun(launcher, new String[] { "error" }, false); + wrappedRun(launcher, new String[] { "error" }); assertEquals("test error\n", ctxFactory.getError()); } - private void runAndVerifyCommand(String[] args, String expected, boolean inShell) { - wrappedRun(launcher, args, inShell); + private void runAndVerifyCommand(String[] args, String expected) { + wrappedRun(launcher, args); assertEquals(expected, ctxFactory.getOutput()); assertTrue(timerFactory.isShutdown()); } - private void wrappedRun(LauncherImpl launcher, String[] args, boolean inShell) { - wrappedRun(launcher, args, inShell, null); + private void wrappedRun(LauncherImpl launcher, String[] args) { + wrappedRun(launcher, args, null); } - private void wrappedRun(LauncherImpl launcher, String[] args, boolean inShell, Collection<ActionListener<ApplicationState>> listeners) { + private void wrappedRun(LauncherImpl launcher, String[] args, Collection<ActionListener<ApplicationState>> listeners) { try { - launcher.run(args, listeners, inShell); + launcher.run(args, listeners); } catch (ExitException e) { System.out.println(e.getMessage()); } } @Test - public void verifyPrefsAreUsed() { - ClientPreferences prefs = mock(ClientPreferences.class); - String dbUrl = "mongo://fluff:12345"; - when(prefs.getConnectionUrl()).thenReturn(dbUrl); - when(prefs.getUserName()).thenReturn("user"); - - LauncherImpl launcher = new LauncherImpl(bundleContext, ctxFactory, registry, infos, new CommandSource(bundleContext), - environment, dbServiceFactory, version, prefs, paths, sslConf); - - DbService dbService = mock(DbService.class); - ArgumentCaptor<String> dbUrlCaptor = ArgumentCaptor.forClass(String.class); - when(dbServiceFactory.createDbService(dbUrlCaptor.capture(), any(StorageCredentials.class), any(SSLConfiguration.class))).thenReturn(dbService); - wrappedRun(launcher, new String[] { "test3" }, false); - verify(dbService).connect(); - verify(prefs).getConnectionUrl(); - assertEquals(dbUrl, dbUrlCaptor.getValue()); - } - - @Test - public void verifyUserInputUsedIfNoSavedAuthInfo() { - ClientPreferences prefs = mock(ClientPreferences.class); - String dbUrl = "mongo://fluff:12345"; - when(prefs.getConnectionUrl()).thenReturn(dbUrl); - LauncherImpl launcher = new LauncherImpl(bundleContext, ctxFactory, registry, infos, new CommandSource(bundleContext), - environment, dbServiceFactory, version, prefs, paths, sslConf); - - DbService dbService = mock(DbService.class); - ArgumentCaptor<String> dbUrlCaptor = ArgumentCaptor.forClass(String.class); - when(dbServiceFactory.createDbService(dbUrlCaptor.capture(), any(StorageCredentials.class), any(SSLConfiguration.class))).thenReturn(dbService); - ctxFactory.setInput("user\rpass\r"); - wrappedRun(launcher, new String[] { "test3" }, false); - verify(dbService).connect(); - verify(prefs).getConnectionUrl(); - assertEquals(dbUrl, dbUrlCaptor.getValue()); - } - - @Test - public void verifyDbServiceConnectIsCalledForStorageCommand() throws Exception { - ClientPreferences prefs = mock(ClientPreferences.class); - String dbUrl = "mongo://fluff:12345"; - String user = "user"; - char[] password = new char[] {'1', '2', '3', '4', '5'}; - when(prefs.getConnectionUrl()).thenReturn(dbUrl); - when(prefs.getUserName()).thenReturn(user); - LauncherImpl launcher = new LauncherImpl(bundleContext, ctxFactory, registry, infos, new CommandSource(bundleContext), - environment, dbServiceFactory, version, prefs, paths, sslConf); - - Command mockCmd = mock(Command.class); - when(mockCmd.isStorageRequired()).thenReturn(true); - - ctxFactory.getCommandRegistry().registerCommand("dummy", mockCmd); - - CommandInfo cmdInfo = mock(CommandInfo.class); - when(cmdInfo.getName()).thenReturn("dummy"); - when(cmdInfo.getOptions()).thenReturn(new Options()); - when(cmdInfo.getEnvironments()).thenReturn(EnumSet.of(Environment.SHELL, Environment.CLI)); - when(infos.getCommandInfo("dummy")).thenReturn(cmdInfo); - - DbService dbService = mock(DbService.class); - when(dbServiceFactory.createDbService(anyString(), any(StorageCredentials.class), any(SSLConfiguration.class))).thenReturn(dbService); - - wrappedRun(launcher, new String[] { "dummy" }, false); - verify(dbService).connect(); - } - - @Test public void verifyVersionInfoQuery() { String versionString = "foo bar baz"; @@ -755,7 +661,7 @@ when(version.getVersionInfo()).thenReturn(versionString); - wrappedRun(launcher, new String[] {Version.VERSION_OPTION}, false); + wrappedRun(launcher, new String[] {Version.VERSION_OPTION}); assertEquals(expectedVersionInfo, ctxFactory.getOutput()); assertTrue(timerFactory.isShutdown()); @@ -772,7 +678,6 @@ assertTrue(logger.getLevel() == Level.ALL); TestLogHandler handler = new TestLogHandler(); logger.addHandler(handler); - ClientPreferences prefs = mock(ClientPreferences.class); CommonPaths logPaths = mock(CommonPaths.class); when(logPaths.getUserThermostatHome()).thenReturn(mock(File.class)); when(logPaths.getSystemThermostatHome()).thenReturn(mock(File.class)); @@ -786,8 +691,7 @@ // this should trigger logging new LauncherImpl(bundleContext, ctxFactory, registry, infos, new CommandSource(bundleContext), - environment, dbServiceFactory, - version, prefs, logPaths, sslConf); + version, logPaths); assertTrue(handler.loggedThermostatHome); assertTrue(handler.loggedUserHome); verify(logPaths).getUserThermostatHome(); @@ -808,13 +712,13 @@ listeners.add(listener); String[] args = new String[] {"basic"}; - wrappedRun(launcher, args, false, listeners); + wrappedRun(launcher, args, listeners); verify(notifier).addActionListener(listener); } @Test public void verifyShutdown() throws BundleException { - wrappedRun(launcher, new String[] { "test1" }, false); + wrappedRun(launcher, new String[] { "test1" }); verify(sysBundle).stop(); } @@ -822,7 +726,7 @@ @Test public void verifySetExitStatus() { try { - launcher.run(new String[] { "test1" }, false); + launcher.run(new String[] { "test1" }); fail("Should have called System.exit()"); } catch (ExitException e) { // pass, by default launcher exits with an exit status @@ -831,104 +735,6 @@ } } - @Test - public void verifyCommandSupportedInShellBehavesNormally() { - runWithShellStatus(true, "fluff", true, true, ""); - } - - @Test - public void verifyCommandSupportedOutsideShellBehavesNormally() { - runWithShellStatus(false, "fluff", true, true, ""); - } - - @Test - public void verifyCommandNotSupportedInShellDisplaysMessage() { - runWithShellStatus(true, "fluff", false, true, "The fluff command is not supported from within the thermostat shell.\n"); - } - - @Test - public void verifyCommandNotSupportedOutsideShellDisplaysMessage() { - runWithShellStatus(false, "fluff", true, false, "The fluff command is not supported from outside the thermostat shell.\n"); - } - - private void runWithShellStatus(boolean isInShell, String cmdName, boolean isAvailableInShell, - boolean isAvailableOutsideShell, String expected) { - Command mockCmd = mock(Command.class); - when(mockCmd.isStorageRequired()).thenReturn(false); - - EnumSet<Environment> available = EnumSet.noneOf(Environment.class); - if (isAvailableInShell) { - available.add(Environment.SHELL); - } - if (isAvailableOutsideShell) { - available.add(Environment.CLI); - } - - CommandInfo cmdInfo = mock(CommandInfo.class); - when(cmdInfo.getName()).thenReturn(cmdName); - when(cmdInfo.getOptions()).thenReturn(new Options()); - when(cmdInfo.getEnvironments()).thenReturn(available); - when(infos.getCommandInfo(cmdName)).thenReturn(cmdInfo); - - ctxFactory.getCommandRegistry().registerCommand(cmdName, mockCmd); - runAndVerifyCommand(new String[] { cmdName }, expected, isInShell); - } - - /* - * Bash completion uses help which expects help to always run - * (no setup required). - */ - @Test - public void verifyHelpIsNotRunThroughSetupHook() { - String[] argsList = new String[] { "help" }; - - List<Pair<String[], Boolean>> resultList = runAsUnconfiguredThermostat(argsList); - assertEquals("Expected to run only help", 1, resultList.size()); - Pair<String[], Boolean> actual = resultList.get(0); - assertFalse("Expected to run outside shell", actual.getSecond()); - String[] expectedList = new String[] { "help" }; - assertArrayEquals(expectedList, actual.getFirst()); - } - - @Test - public void verifyCommandHelpOptionIsNotRunThroughSetupHook() { - String[] argsList = new String[] { "web-storage-service", "--help" }; - - List<Pair<String[], Boolean>> resultList = runAsUnconfiguredThermostat(argsList); - assertEquals("Expected to run only web-storage-service --help", 1, resultList.size()); - Pair<String[], Boolean> actual = resultList.get(0); - assertFalse("Expected to run outside shell", actual.getSecond()); - String[] expectedList = new String[] { "web-storage-service", "--help" }; - assertArrayEquals(expectedList, actual.getFirst()); - } - - private List<Pair<String[], Boolean>> runAsUnconfiguredThermostat(String[] args) { - CommonPaths setupPaths = mock(CommonPaths.class); - File mockFile = mock(File.class); - when(mockFile.exists()).thenReturn(false); - when(setupPaths.getUserSetupCompleteStampFile()).thenReturn(mockFile); - File fileWithAbsPath = mock(File.class); - when(setupPaths.getSystemThermostatHome()).thenReturn(fileWithAbsPath); - when(setupPaths.getUserThermostatHome()).thenReturn(fileWithAbsPath); - when(setupPaths.getSystemPluginRoot()).thenReturn(systemPluginRoot); - when(setupPaths.getSystemLibRoot()).thenReturn(systemLibRoot); - when(setupPaths.getUserPluginRoot()).thenReturn(userPluginRoot); - final List<Pair<String[], Boolean>> runList = new ArrayList<>(); - launcher = new LauncherImpl(bundleContext, ctxFactory, registry, infos, - new CommandSource(bundleContext), environment, - dbServiceFactory, version, - mock(ClientPreferences.class), setupPaths, sslConf) { - @Override - void runCommandFromArguments(String[] args, Collection<ActionListener<ApplicationState>> listeners, boolean inShell) { - Pair<String[], Boolean> pair = new Pair<>(args, inShell); - runList.add(pair); - } - }; - - wrappedRun(launcher, args, false, null); - return runList; - } - private static class TestLogHandler extends Handler { private boolean loggedThermostatHome;
--- a/launcher/src/test/java/com/redhat/thermostat/launcher/internal/PluginConfigurationParserTest.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/test/java/com/redhat/thermostat/launcher/internal/PluginConfigurationParserTest.java Wed May 17 18:12:02 2017 -0400 @@ -142,10 +142,6 @@ " <command-groups>\n" + " <command-group>group</command-group>\n" + " </command-groups>\n" + - " <environments>\n" + - " <environment>shell</environment>\n" + - " <environment>cli</environment>\n" + - " </environments>\n" + " <bundles>\n" + " <bundle><symbolic-name>foo</symbolic-name><version>1.0</version></bundle>\n" + " <bundle><symbolic-name>bar</symbolic-name><version>1.0</version></bundle>\n" + @@ -175,8 +171,6 @@ Options opts = newCommand.getOptions(); assertTrue(opts.getOptions().isEmpty()); assertTrue(opts.getRequiredOptions().isEmpty()); - assertTrue(newCommand.getEnvironments().contains(Environment.SHELL)); - assertTrue(newCommand.getEnvironments().contains(Environment.CLI)); BundleInformation[] expectedBundles = new BundleInformation[] { new BundleInformation("foo", "1.0"), new BundleInformation("bar", "1.0"), new BundleInformation("baz", "1.0"), }; @@ -210,10 +204,6 @@ " </options>" + " </subcommand>" + " </subcommands>" + - " <environments>" + - " <environment>shell</environment>" + - " <environment>cli</environment>" + - " </environments>" + " <bundles>\n" + " <bundle><symbolic-name>foo</symbolic-name><version>1.0</version></bundle>\n" + " <bundle><symbolic-name>bar</symbolic-name><version>1.0</version></bundle>\n" + @@ -264,10 +254,6 @@ " <command-groups>\n" + " <command-group>group</command-group>\n" + " </command-groups>\n" + - " <environments>\n" + - " <environment>shell</environment>\n" + - " <environment>cli</environment>\n" + - " </environments>\n" + " <bundles>\n" + " <bundle><symbolic-name>foo</symbolic-name><version>1.0</version></bundle>\n" + " <bundle><symbolic-name>bar</symbolic-name><version>1.0</version></bundle>\n" + @@ -437,10 +423,6 @@ " <name>test</name>\n" + " <summary>some summary</summary>\n" + " <description>some description</description>\n" + - " <environments>" + - " <environment>shell</environment>" + - " <environment>cli</environment>" + - " </environments>" + " </command>\n" + " </commands>\n" + "</plugin>"; @@ -468,10 +450,6 @@ " <name>test</name>\n" + " <summary>summary</summary>\n" + " <description> Line 1. " + newLine + "Line 2. Line 3." + newLine + "Line 4.</description>\n" + - " <environments>" + - " <environment>shell</environment>" + - " <environment>cli</environment>" + - " </environments>" + " </command>\n" + " </commands>\n" + "</plugin>"; @@ -501,10 +479,6 @@ " <arguments>\n" + " <argument>file</argument>\n" + " </arguments>\n" + - " <environments>" + - " <environment>shell</environment>" + - " <environment>cli</environment>" + - " </environments>" + " </command>\n" + " </commands>\n" + "</plugin>"; @@ -527,9 +501,6 @@ List<String> args = command.getPositionalArguments(); assertEquals(1, args.size()); assertEquals("file", args.get(0)); - - assertTrue(command.getEnvironments().contains(Environment.SHELL)); - assertTrue(command.getEnvironments().contains(Environment.CLI)); } @Test @@ -567,10 +538,6 @@ " <description>some required and long option</description>\n" + " </option>\n" + " </options>\n" + - " <environments>" + - " <environment>shell</environment>" + - " <environment>cli</environment>" + - " </environments>" + " </command>\n" + " </commands>\n" + "</plugin>"; @@ -621,10 +588,6 @@ " <name>test</name>\n" + " <summary>summary</summary>\n" + " <description>just a test</description>\n" + - " <environments>" + - " <environment>shell</environment>" + - " <environment>cli</environment>" + - " </environments>" + " <options>\n" + " <option common=\"true\">\n" + " <long>dbUrl</long>\n" + @@ -672,10 +635,6 @@ " <name>test</name>\n" + " <summary>summary</summary>\n" + " <description>just a test</description>\n" + - " <environments>" + - " <environment>shell</environment>" + - " <environment>cli</environment>" + - " </environments>" + " <options>\n" + " <option common=\"true\">\n" + " <long>foobarbaz</long>\n" + @@ -711,10 +670,6 @@ " <name>test</name>\n" + " <summary>some summary</summary>\n" + " <description>some description</description>\n" + - " <environments>" + - " <environment>shell</environment>" + - " <environment>cli</environment>" + - " </environments>" + " </command>\n" + " </commands>\n" + "</plugin>"; @@ -740,10 +695,6 @@ " <name>test</name>\n" + " <summary>some summary</summary>\n" + " <description>some description</description>\n" + - " <environments>" + - " <environment>shell</environment>" + - " <environment>cli</environment>" + - " </environments>" + " </command>\n" + " </commands>\n" + "</plugin>"; @@ -769,10 +720,6 @@ " <name>test</name>\n" + " <summary>some summary</summary>\n" + " <description>some description</description>\n" + - " <environments>" + - " <environment>shell</environment>" + - " <environment>cli</environment>" + - " </environments>" + " </command>\n" + " </commands>\n" + "</plugin>";
--- a/launcher/src/test/java/com/redhat/thermostat/launcher/internal/PluginInfoSourceTest.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/test/java/com/redhat/thermostat/launcher/internal/PluginInfoSourceTest.java Wed May 17 18:12:02 2017 -0400 @@ -46,6 +46,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; + import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -56,13 +57,10 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.Arrays; import java.util.Collections; -import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Set; -import com.redhat.thermostat.launcher.internal.PluginConfiguration.CommandGroupMetadata; import org.apache.commons.cli.Options; import org.junit.After; import org.junit.Before; @@ -71,6 +69,7 @@ import com.redhat.thermostat.launcher.BundleInformation; import com.redhat.thermostat.launcher.internal.PluginConfiguration.CommandExtensions; +import com.redhat.thermostat.launcher.internal.PluginConfiguration.CommandGroupMetadata; import com.redhat.thermostat.launcher.internal.PluginConfiguration.Configurations; import com.redhat.thermostat.launcher.internal.PluginConfiguration.NewCommand; import com.redhat.thermostat.launcher.internal.PluginConfiguration.PluginID; @@ -201,7 +200,6 @@ final List<String> COMMAND_GROUPS = Collections.singletonList("group"); final String USAGE = "usage"; final Options OPTIONS = new Options(); - final Set<Environment> ENVIRONMENTS = EnumSet.of(Environment.SHELL); BundleInformation bundleInfo = new BundleInformation("plugin-bundle", "0.1"); Path pluginDir = sysPluginRootDir.resolve("plugin1"); @@ -213,7 +211,6 @@ when(cmd.getCommandGroups()).thenReturn(COMMAND_GROUPS); when(usageBuilder.getUsage(NAME, false, OPTIONS)).thenReturn(USAGE); when(cmd.getOptions()).thenReturn(OPTIONS); - when(cmd.getEnvironments()).thenReturn(ENVIRONMENTS); when(cmd.getBundles()).thenReturn(Arrays.asList(bundleInfo)); when(parserResult.getNewCommands()).thenReturn(Arrays.asList(cmd));
--- a/launcher/src/test/java/com/redhat/thermostat/launcher/internal/ShellArgsParserTest.java Wed May 17 18:11:05 2017 -0400 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,570 +0,0 @@ -/* - * Copyright 2012-2017 Red Hat, Inc. - * - * This file is part of Thermostat. - * - * Thermostat is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published - * by the Free Software Foundation; either version 2, or (at your - * option) any later version. - * - * Thermostat is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Thermostat; see the file COPYING. If not see - * <http://www.gnu.org/licenses/>. - * - * Linking this code with other modules is making a combined work - * based on this code. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. - * - * As a special exception, the copyright holders of this code give - * you permission to link this code with independent modules to - * produce an executable, regardless of the license terms of these - * independent modules, and to copy and distribute the resulting - * executable under terms of your choice, provided that you also - * meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module - * which is not derived from or based on this code. If you modify - * this code, you may extend this exception to your version of the - * library, but you are not obligated to do so. If you do not wish - * to do so, delete this exception statement from your version. - */ - -package com.redhat.thermostat.launcher.internal; - -import org.junit.Test; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.core.IsNot.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class ShellArgsParserTest { - - private ShellArgsParser.Issues issues; - - @Test(expected = IllegalStateException.class) - public void testGetIssuesBeforeParse() { - ShellArgsParser sap = new ShellArgsParser(""); - sap.getParseIssues(); - sap.parse(); - } - - @Test - public void testEmptyString() { - assertEmpty(""); - assertNoIssues(); - } - - @Test - public void testOneCharArg() { - assertResult("f", "f"); - assertNoIssues(); - } - - @Test - public void testSingleArg() { - assertResult("foo", "foo"); - assertNoIssues(); - } - - @Test - public void testTwoArgs() { - assertResult("foo bar", "foo", "bar"); - assertNoIssues(); - } - - @Test - public void testThreeArgs() { - assertResult("foo bar baz", "foo", "bar", "baz"); - assertNoIssues(); - } - - @Test - public void testLeadingSpaces() { - assertResult(" foo", "foo"); - assertNoIssues(); - } - - @Test - public void testTrailingSpaces() { - assertResult("foo ", "foo"); - assertNoIssues(); - } - - @Test - public void testInnerSpaces() { - assertResult("foo bar", "foo", "bar"); - assertNoIssues(); - } - - @Test - public void testLotsOfSpaces() { - assertResult(" foo bar ", "foo", "bar"); - assertNoIssues(); - } - - @Test - public void testOnlySpaces() { - assertEmpty(" "); - assertNoIssues(); - } - - @Test - public void testTabCharacter() { - assertResult("foo\tbar", "foo", "bar"); - assertNoIssues(); - } - - @Test - public void testQuotedArg() { - assertResult("\"foo\"", "foo"); - assertNoIssues(); - } - - @Test - public void testSingleQuotedArg() { - assertResult("'foo'", "foo"); - assertNoIssues(); - } - - @Test - public void testQuotedString() { - assertResult("\"foo bar\"", "foo bar"); - assertNoIssues(); - } - - @Test - public void testSingleQuotedString() { - assertResult("'foo bar'", "foo bar"); - assertNoIssues(); - } - - @Test - public void testQuotedArgFirst() { - assertResult("\"foo bar\" baz", "foo bar", "baz"); - assertNoIssues(); - } - - @Test - public void testSingleQuotedArgFirst() { - assertResult("'foo bar' baz", "foo bar", "baz"); - assertNoIssues(); - } - - @Test - public void testSingleStartingQuote() { - assertResult("\"foo", "foo"); - assertIssues(new ShellArgsParser.Issue(0, ShellArgsParser.Issue.Type.UNMATCHED_QUOTE)); - } - - @Test - public void testSingleStartingSingleQuote() { - assertResult("'foo", "foo"); - assertIssues(new ShellArgsParser.Issue(0, ShellArgsParser.Issue.Type.UNMATCHED_QUOTE)); - } - - @Test - public void testSingleEndingQuote() { - assertResult("foo\"", "foo\""); - assertIssues(new ShellArgsParser.Issue(3, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE)); - } - - @Test - public void testSingleEndingSingleQuote() { - assertResult("foo'", "foo'"); - assertIssues(new ShellArgsParser.Issue(3, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE)); - } - - @Test - public void testSingleMiddleQuote() { - assertResult("foo \" bar", "foo", " bar"); - assertIssues(new ShellArgsParser.Issue(4, ShellArgsParser.Issue.Type.UNMATCHED_QUOTE)); - } - - @Test - public void testSingleMiddleSingleQuote() { - assertResult("foo ' bar", "foo", " bar"); - assertIssues(new ShellArgsParser.Issue(4, ShellArgsParser.Issue.Type.UNMATCHED_QUOTE)); - } - - @Test - public void testOneQuoteMark() { - assertResult("\"", ""); - assertIssues(new ShellArgsParser.Issue(0, ShellArgsParser.Issue.Type.UNMATCHED_QUOTE)); - } - - @Test - public void testOneSingleQuoteMark() { - assertResult("'", ""); - assertIssues(new ShellArgsParser.Issue(0, ShellArgsParser.Issue.Type.UNMATCHED_QUOTE)); - } - - @Test - public void testThreeQuoteMarks() { - assertResult("\"\"\"", ""); - assertIssues(new ShellArgsParser.Issue(2, ShellArgsParser.Issue.Type.UNMATCHED_QUOTE)); - } - - @Test - public void testThreeSingleQuoteMarks() { - assertResult("'''", ""); - assertIssues(new ShellArgsParser.Issue(2, ShellArgsParser.Issue.Type.UNMATCHED_QUOTE)); - } - - @Test - public void testFourQuoteMarks() { - assertResult("\"\"\"\"", "", ""); - assertIssues(new ShellArgsParser.Issue(2, ShellArgsParser.Issue.Type.EXPECTED_WHITESPACE)); - } - - @Test - public void testFourSingleQuoteMarks() { - assertResult("''''", "", ""); - assertIssues(new ShellArgsParser.Issue(2, ShellArgsParser.Issue.Type.EXPECTED_WHITESPACE)); - } - - @Test - public void testAdjacentQuotes() { - assertResult("\"f\"\"b\"", "f", "b"); - assertIssues(new ShellArgsParser.Issue(3, ShellArgsParser.Issue.Type.EXPECTED_WHITESPACE)); - } - - @Test - public void testAdjacentSingleQuotes() { - assertResult("'f''b'", "f", "b"); - assertIssues(new ShellArgsParser.Issue(3, ShellArgsParser.Issue.Type.EXPECTED_WHITESPACE)); - } - - @Test - public void testQuoteAdjacentToWord() { - assertResult("foo\"bar\"", "foo\"bar\""); - assertIssues(new ShellArgsParser.Issue(3, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE), - new ShellArgsParser.Issue(7, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE)); - } - - @Test - public void testSingleQuoteAdjacentToWord() { - assertResult("foo'bar'", "foo'bar'"); - assertIssues(new ShellArgsParser.Issue(3, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE), - new ShellArgsParser.Issue(7, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE)); - } - - @Test - public void testSingleEscapedQuote() { - assertResult("foo\\\"", "foo\""); - assertNoIssues(); - } - - @Test - public void testSingleEscapedSingleQuote() { - assertResult("foo\\'", "foo'"); - assertNoIssues(); - } - - @Test - public void testQuoteContainingEscapedQuoteLiteral() { - assertResult("\"foo \\\" bar\"", "foo \" bar"); - assertNoIssues(); - } - - @Test - public void testQuoteContainingEscapedQuoteLiteral2() { - assertResult("\"foo \\\"\"", "foo \""); - assertNoIssues(); - } - - @Test - public void testSingleQuoteContainingEscapedSingleQuoteLiteral() { - assertResult("'foo \\' bar'", "foo ' bar"); - assertNoIssues(); - } - - @Test - public void testQuoteContainingEscapedSingleQuoteLiteral2() { - assertResult("\"foo \\\"\"", "foo \""); - assertNoIssues(); - } - - @Test - public void testQuoteContainingEscapedSingleSingleQuoteLiteral2() { - assertResult("'foo \\''", "foo '"); - assertNoIssues(); - } - - @Test - public void testEscapedQuoteInsideSingleQuotes() { - assertResult("'foo \\\" bar'", "foo \" bar"); - assertNoIssues(); - } - - @Test - public void testEscapedSingleQuoteInsideQuotes() { - assertResult("\"foo \\' bar\"", "foo ' bar"); - assertNoIssues(); - } - - @Test - public void testQuotedEmptyString() { - assertResult("\"\"", ""); - assertNoIssues(); - } - - @Test - public void testSingleQuotedEmptyString() { - assertResult("''", ""); - assertNoIssues(); - } - - @Test - public void testQuotedSpacesString() { - assertResult("\" \"", " "); - assertNoIssues(); - } - - @Test - public void testSingleQuotedSpacesString() { - assertResult("' '", " "); - assertNoIssues(); - } - - @Test - public void testSingleAndDoubleQuotes() { - assertResult("\"foo\" 'bar'", "foo", "bar"); - assertNoIssues(); - } - - @Test - public void testSingleQuotesWithinDoubleQuotes() { - assertResult("\"some 'quoted' args\"", "some 'quoted' args"); - assertNoIssues(); - } - - @Test - public void testDoubleQuotesWithinSingleQuotes() { - assertResult("'some \"quoted\" args'", "some \"quoted\" args"); - assertNoIssues(); - } - - @Test - public void testSingleAndDoubleQuotesAdjacent() { - assertResult("\"foo\"'bar'", "foo", "bar"); - assertIssues(new ShellArgsParser.Issue(5, ShellArgsParser.Issue.Type.EXPECTED_WHITESPACE)); - } - - @Test - public void testMismatchedQuotes() { - assertResult("\"foo'", "foo'"); - assertIssues(new ShellArgsParser.Issue(0, ShellArgsParser.Issue.Type.UNMATCHED_QUOTE)); - } - - @Test - public void testSingleCharArgument() { - assertResult("some-command -f 2", "some-command", "-f", "2"); - assertNoIssues(); - } - - @Test - public void testSingleCharArgumentAdjoined() { - assertResult("some-command -f2", "some-command", "-f2"); - assertNoIssues(); - } - - @Test - public void testSingleCharArgumentWithSingleQuotes() { - assertResult("some-command -f '2'", "some-command", "-f", "2"); - assertNoIssues(); - } - - @Test - public void testSingleCharArgumentWithDoubleQuotes() { - assertResult("some-command -f \"2\"", "some-command", "-f", "2"); - assertNoIssues(); - } - - @Test - public void testSingleCharArgumentWithExtraWhitespace() { - assertResult("some-command -f 2", "some-command", "-f", "2"); - assertNoIssues(); - } - - @Test - public void testSingleCharArgumentWithTrailingWhitespace() { - assertResult("some-command -f 2 ", "some-command", "-f", "2"); - assertNoIssues(); - } - - @Test - public void testIssueGetters() { - ShellArgsParser.Issue issue = new ShellArgsParser.Issue(10, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE); - int columnNumber = issue.getColumnNumber(); - ShellArgsParser.Issue.Type issueType = issue.getType(); - assertEquals(10, columnNumber); - assertEquals(ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE, issueType); - } - - @Test - public void testIssueEquality() { - ShellArgsParser.Issue issue1 = new ShellArgsParser.Issue(10, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE); - ShellArgsParser.Issue issue2 = new ShellArgsParser.Issue(10, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE); - ShellArgsParser.Issue issue3 = new ShellArgsParser.Issue(1, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE); - ShellArgsParser.Issue issue4 = new ShellArgsParser.Issue(10, ShellArgsParser.Issue.Type.EXPECTED_WHITESPACE); - assertThat(issue1, is(equalTo(issue2))); - assertThat(issue1.hashCode(), is(equalTo(issue2.hashCode()))); - assertThat(issue1, not(equalTo(issue3))); - assertThat(issue1, not(equalTo(issue4))); - } - - @Test - public void testIssuesAllIssuesListContents() { - ShellArgsParser.Issue issue1 = new ShellArgsParser.Issue(10, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE); - ShellArgsParser.Issue issue2 = new ShellArgsParser.Issue(15, ShellArgsParser.Issue.Type.EXPECTED_WHITESPACE); - ShellArgsParser.Issue issue3 = new ShellArgsParser.Issue(20, ShellArgsParser.Issue.Type.UNMATCHED_QUOTE); - ShellArgsParser.Issues issues = new ShellArgsParser.Issues(); - issues.addIssue(issue1); - issues.addIssue(issue1); - issues.addIssue(issue2); - issues.addIssue(issue3); - - assertThat(issues.getAllIssues().size(), is(equalTo(4))); - assertThat(issues.getAllIssues().size(), is(equalTo(issues.getWarnings().size() + issues.getErrors().size()))); - - assertTrue(issues.getAllIssues().contains(issue1)); - assertTrue(issues.getAllIssues().contains(issue2)); - assertTrue(issues.getAllIssues().contains(issue3)); - } - - @Test - public void testIssuesWarningsListContents() { - ShellArgsParser.Issue issue1 = new ShellArgsParser.Issue(10, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE); - ShellArgsParser.Issue issue2 = new ShellArgsParser.Issue(15, ShellArgsParser.Issue.Type.EXPECTED_WHITESPACE); - ShellArgsParser.Issue issue3 = new ShellArgsParser.Issue(20, ShellArgsParser.Issue.Type.UNMATCHED_QUOTE); - ShellArgsParser.Issues issues = new ShellArgsParser.Issues(); - issues.addIssue(issue1); - issues.addIssue(issue1); - issues.addIssue(issue2); - issues.addIssue(issue3); - - assertThat(issues.getWarnings().size(), is(equalTo(1))); - - assertFalse(issues.getWarnings().contains(issue1)); - assertTrue(issues.getWarnings().contains(issue2)); - assertFalse(issues.getWarnings().contains(issue3)); - } - - @Test - public void testIssuesErrorsListContents() { - ShellArgsParser.Issue issue1 = new ShellArgsParser.Issue(10, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE); - ShellArgsParser.Issue issue2 = new ShellArgsParser.Issue(15, ShellArgsParser.Issue.Type.EXPECTED_WHITESPACE); - ShellArgsParser.Issue issue3 = new ShellArgsParser.Issue(20, ShellArgsParser.Issue.Type.UNMATCHED_QUOTE); - ShellArgsParser.Issues issues = new ShellArgsParser.Issues(); - issues.addIssue(issue1); - issues.addIssue(issue1); - issues.addIssue(issue2); - issues.addIssue(issue3); - - assertThat(issues.getErrors().size(), is(equalTo(3))); - - assertTrue(issues.getErrors().contains(issue1)); - assertFalse(issues.getErrors().contains(issue2)); - assertTrue(issues.getErrors().contains(issue3)); - } - - @Test(expected = UnsupportedOperationException.class) - public void testIssuesAllIssuesListUnmodifiable() { - ShellArgsParser.Issue issue1 = new ShellArgsParser.Issue(10, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE); - ShellArgsParser.Issue issue2 = new ShellArgsParser.Issue(15, ShellArgsParser.Issue.Type.EXPECTED_WHITESPACE); - ShellArgsParser.Issues issues = new ShellArgsParser.Issues(); - issues.addIssue(issue1); - - List<ShellArgsParser.Issue> allIssuesList = issues.getAllIssues(); - allIssuesList.add(issue2); - fail("Should have hit UnsupportedOperationException on add"); - } - - @Test(expected = UnsupportedOperationException.class) - public void testIssuesWarningsListUnmodifiable() { - ShellArgsParser.Issue issue1 = new ShellArgsParser.Issue(10, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE); - ShellArgsParser.Issue issue2 = new ShellArgsParser.Issue(15, ShellArgsParser.Issue.Type.EXPECTED_WHITESPACE); - ShellArgsParser.Issues issues = new ShellArgsParser.Issues(); - issues.addIssue(issue1); - - List<ShellArgsParser.Issue> warningsList = issues.getWarnings(); - warningsList.add(issue2); - fail("Should have hit UnsupportedOperationException on add"); - } - - @Test(expected = UnsupportedOperationException.class) - public void testIssuesErrorsListUnmodifiable() { - ShellArgsParser.Issue issue1 = new ShellArgsParser.Issue(10, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE); - ShellArgsParser.Issue issue2 = new ShellArgsParser.Issue(15, ShellArgsParser.Issue.Type.EXPECTED_WHITESPACE); - ShellArgsParser.Issues issues = new ShellArgsParser.Issues(); - issues.addIssue(issue1); - - List<ShellArgsParser.Issue> errorsList = issues.getErrors(); - errorsList.add(issue2); - fail("Should have hit UnsupportedOperationException on add"); - } - - @Test - public void testIssuesFormatterOutputContents() { - ShellArgsParser.Issue issue1 = new ShellArgsParser.Issue(10, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE); - ShellArgsParser.Issue issue2 = new ShellArgsParser.Issue(15, ShellArgsParser.Issue.Type.EXPECTED_WHITESPACE); - ShellArgsParser.Issues issues = new ShellArgsParser.Issues(); - issues.addIssue(issue1); - issues.addIssue(issue2); - - ShellArgsParser.IssuesFormatter formatter = new ShellArgsParser.IssuesFormatter(); - String output = formatter.format(issues); - assertTrue(output.contains(issue1.toString())); - assertTrue(output.contains(issue2.toString())); - } - - @Test - public void testIssuesFormatterOutputSame() { - ShellArgsParser.Issue issue1 = new ShellArgsParser.Issue(10, ShellArgsParser.Issue.Type.UNEXPECTED_QUOTE); - ShellArgsParser.Issue issue2 = new ShellArgsParser.Issue(15, ShellArgsParser.Issue.Type.EXPECTED_WHITESPACE); - ShellArgsParser.Issues issues = new ShellArgsParser.Issues(); - issues.addIssue(issue1); - issues.addIssue(issue2); - - ShellArgsParser.IssuesFormatter formatter = new ShellArgsParser.IssuesFormatter(); - String issuesOutput = formatter.format(issues); - String iterableOutput = formatter.format(issues); - assertThat(issuesOutput, is(equalTo(iterableOutput))); - } - - private void assertEmpty(String input) { - ShellArgsParser sap = new ShellArgsParser(input); - String[] result = sap.parse(); - issues = sap.getParseIssues(); - assertEquals(Collections.emptyList(), Arrays.asList(result)); - } - - private void assertResult(String input, String ... expecteds) { - ShellArgsParser sap = new ShellArgsParser(input); - String[] result = sap.parse(); - issues = sap.getParseIssues(); - assertEquals(Arrays.asList(expecteds), Arrays.asList(result)); - } - - private void assertNoIssues() { - assertTrue(issues.getAllIssues().isEmpty()); - } - - private void assertIssues(ShellArgsParser.Issue ... expecteds) { - assertEquals(Arrays.asList(expecteds), issues.getAllIssues()); - } -}
--- a/launcher/src/test/java/com/redhat/thermostat/launcher/internal/ShellCommandTest.java Wed May 17 18:11:05 2017 -0400 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,767 +0,0 @@ -/* - * Copyright 2012-2017 Red Hat, Inc. - * - * This file is part of Thermostat. - * - * Thermostat is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published - * by the Free Software Foundation; either version 2, or (at your - * option) any later version. - * - * Thermostat is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Thermostat; see the file COPYING. If not see - * <http://www.gnu.org/licenses/>. - * - * Linking this code with other modules is making a combined work - * based on this code. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. - * - * As a special exception, the copyright holders of this code give - * you permission to link this code with independent modules to - * produce an executable, regardless of the license terms of these - * independent modules, and to copy and distribute the resulting - * executable under terms of your choice, provided that you also - * meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module - * which is not derived from or based on this code. If you modify - * this code, you may extend this exception to your version of the - * library, but you are not obligated to do so. If you do not wish - * to do so, delete this exception statement from your version. - */ - -package com.redhat.thermostat.launcher.internal; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.EnumSet; - -import jline.Terminal; -import jline.console.ConsoleReader; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; - -import com.redhat.thermostat.common.Version; -import com.redhat.thermostat.common.cli.Arguments; -import com.redhat.thermostat.common.cli.CommandContext; -import com.redhat.thermostat.common.cli.CommandException; -import com.redhat.thermostat.common.cli.SimpleArguments; -import com.redhat.thermostat.common.config.ClientPreferences; -import com.redhat.thermostat.common.config.experimental.ConfigurationInfoSource; -import com.redhat.thermostat.common.internal.test.TestCommandContextFactory; -import com.redhat.thermostat.common.utils.StringUtils; -import com.redhat.thermostat.launcher.Launcher; -import com.redhat.thermostat.launcher.internal.ShellCommand.HistoryProvider; - -import jline.TerminalFactory; -import jline.TerminalFactory.Flavor; -import jline.TerminalFactory.Type; -import jline.UnixTerminal; -import jline.console.history.PersistentHistory; - -public class ShellCommandTest { - - static private final String VERSION = "Thermostat some version"; - static private final String VERSION_OUTPUT = VERSION + "\n"; - static private final String USER_GUIDE_OUTPUT = "Please see the User Guide at http://icedtea.classpath.org/wiki/Thermostat/UserGuide\n"; - static private final String INTRO = VERSION_OUTPUT + USER_GUIDE_OUTPUT; - static private final String PROMPT = "Thermostat " + ShellPrompt.DEFAULT_DISCONNECTED_TOKEN + " > "; - - private ShellCommand cmd; - - private BundleContext bundleContext; - private HistoryProvider historyProvider; - private Version version; - private ConfigurationInfoSource config; - private CommandInfoSource infos; - private ClientPreferences prefs; - private TabCompletion tabCompletion; - - @Before - public void setUp() { - bundleContext = mock(BundleContext.class); - historyProvider = mock(HistoryProvider.class); - version = mock(Version.class); - when(version.getVersionInfo()).thenReturn(VERSION); - config = mock(ConfigurationInfoSource.class); - tabCompletion = new TabCompletion(); - - prefs = mock(ClientPreferences.class); - when(prefs.getConnectionUrl()).thenReturn("http://127.0.0.1:mockStorage"); - infos = mock(CommandInfoSource.class); - cmd = new ShellCommand(bundleContext, version, historyProvider, config, prefs); - cmd.setTabCompletion(tabCompletion); - setupCommandInfoSource(); - } - - @After - public void tearDown() { - cmd = null; - bundleContext = null; - TerminalFactory.registerFlavor(Flavor.UNIX, UnixTerminal.class); - TerminalFactory.reset(); - } - - @Test - public void testBasic() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - ctxFactory.setInput("help\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - verify(launcher).run(new String[]{"help"}, true); - } - - @Test - public void testExtraSpacesAreIgnored() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - ctxFactory.setInput("foo bar\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - verify(launcher).run(new String[]{"foo", "bar"}, true); - } - - @Test - public void testQuitAlsoExits() throws CommandException { - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(); - ctxFactory.setInput("quit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - assertEquals(INTRO + PROMPT + "quit\n", makeNewlinesConsistent(ctxFactory.getOutput())); - assertEquals("", ctxFactory.getError()); - } - - @Test - public void testQAlsoExits() throws CommandException { - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(); - ctxFactory.setInput("q\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - assertEquals(INTRO + PROMPT + "q\n", makeNewlinesConsistent(ctxFactory.getOutput())); - assertEquals("", ctxFactory.getError()); - } - - @Test - public void testEofExits() throws CommandException { - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(); - ctxFactory.setInput("\u0004"); // EOF - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - assertEquals(INTRO + PROMPT, makeNewlinesConsistent(ctxFactory.getOutput())); - assertEquals("", ctxFactory.getError()); - } - - @Test - public void testDoNothingWithoutInput() throws CommandException { - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(); - ctxFactory.setInput("\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - assertEquals(INTRO + PROMPT + "\n" + PROMPT + "exit\n", makeNewlinesConsistent(ctxFactory.getOutput())); - } - - @Test - public void testHistoryIsQueried() throws CommandException { - PersistentHistory history = mock(PersistentHistory.class); - when(history.previous()).thenReturn(true); - when(history.current()).thenReturn("old-history-value"); - - when(historyProvider.get()).thenReturn(history); - - ServiceReference ref = mock(ServiceReference.class); - - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - - // "\u001b[A" is the escape code for up-arrow. use xxd -p to generate - ctxFactory.setInput("\u001b[A\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - - assertEquals(INTRO + PROMPT + "old-history-value\n" + PROMPT + "exit\n", makeNewlinesConsistent(ctxFactory.getOutput())); - assertEquals("", ctxFactory.getError()); - - verify(launcher).run(new String[] {"old-history-value"}, true); - } - - @Test - public void testHistoryIsUpdated() throws CommandException, IOException { - PersistentHistory mockHistory = mock(PersistentHistory.class); - when(historyProvider.get()).thenReturn(mockHistory); - - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - - ctxFactory.setInput("add-to-history\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - - verify(launcher).run(new String[] {"add-to-history"}, true); - verify(mockHistory).add("add-to-history"); - verify(mockHistory).flush(); - - assertEquals(INTRO + PROMPT + "add-to-history\n" + PROMPT + "exit\n", makeNewlinesConsistent(ctxFactory.getOutput())); - assertEquals("", ctxFactory.getError()); - } - - @Test(expected=CommandException.class) - public void testIOException() throws CommandException { - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(); - ctxFactory.setInputThrowsException(new IOException()); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - } - - @Test(expected=CommandException.class) - public void testTerminalRestoreException() throws CommandException { - TerminalFactory.configure(Type.UNIX); - TerminalFactory.registerFlavor(Flavor.UNIX, TestTerminal.class); - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(); - ctxFactory.setInputThrowsException(new IOException()); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - } - - @Test - public void testStorageRequired() { - assertFalse(cmd.isStorageRequired()); - } - - @Test - public void testClearKeywordClearsScreen() throws CommandException, IOException { - final ConsoleReader reader = mock(ConsoleReader.class); - when(reader.readLine()).thenReturn("clear").thenReturn("quit"); - when(reader.readLine(anyString())).thenReturn("clear").thenReturn("quit"); - cmd = new ShellCommand(bundleContext, version, historyProvider, config, prefs) { - @Override - ConsoleReader createConsoleReader(CommandContext ctx, Terminal terminal) throws IOException { - return reader; - } - }; - cmd.setTabCompletion(tabCompletion); - setupCommandInfoSource(); - - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - verify(reader).clearScreen(); - // "clear" is a shell keyword, not a real command, so it should not have been passed through to the Launcher - verifyZeroInteractions(launcher); - } - - @Test - public void testClsKeywordClearsScreen() throws CommandException, IOException { - final ConsoleReader reader = mock(ConsoleReader.class); - when(reader.readLine()).thenReturn("clear").thenReturn("quit"); - when(reader.readLine(anyString())).thenReturn("clear").thenReturn("quit"); - cmd = new ShellCommand(bundleContext, version, historyProvider, config, prefs) { - @Override - ConsoleReader createConsoleReader(CommandContext ctx, Terminal terminal) throws IOException { - return reader; - } - }; - cmd.setTabCompletion(tabCompletion); - setupCommandInfoSource(); - - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - verify(reader).clearScreen(); - // "cls" is a shell keyword, not a real command, so it should not have been passed through to the Launcher - verifyZeroInteractions(launcher); - } - - @Test - public void testNoInputTabCompletes() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(); - ctxFactory.setInput("\t\nq\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - - String tabOutput = getTabOutput(getOutputWithoutIntro(ctxFactory)); - - assertTrue(tabOutput.contains("test1")); - assertTrue(tabOutput.contains("test2longname")); - assertEquals("", ctxFactory.getError()); - } - - @Test - public void testPartiallyFilledInputTabCompletes() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - ctxFactory.setInput("t\t\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - - String tabOutput = getTabOutput(getOutputWithoutIntro(ctxFactory)); - assertTrue(tabOutput.contains("test1")); - assertTrue(tabOutput.contains("test2longname")); - assertEquals("", ctxFactory.getError()); - } - - @Test - public void testFullCommandDoesNotTabComplete() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(); - ctxFactory.setInput("test1\t\nq\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - - String usefulOutput = getOutputWithoutIntro(ctxFactory); - String tabOutput = getTabOutput(usefulOutput); - assertTrue(tabOutput.length() == 0); - assertEquals(PROMPT + "q", usefulOutput.split("\n")[1]); - assertEquals("", ctxFactory.getError()); - } - - @Test - public void testFullInputWithSpaceTabCompletes() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - ctxFactory.setInput("test1 \t\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - - String tabOutput = getTabOutput(getOutputWithoutIntro(ctxFactory)); - assertTrue(tabOutput.contains("--Add")); - assertTrue(tabOutput.contains("--remove")); - assertTrue(tabOutput.contains("--test")); - assertTrue(tabOutput.contains("-A")); - assertTrue(tabOutput.contains("-r")); - assertTrue(tabOutput.contains("-t")); - assertEquals("", ctxFactory.getError()); - - } - - @Test - public void testOptionWithOnlyFirstLetterTabCompletes() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - ctxFactory.setInput("test2longname --c\t\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - - String tabOutput = getTabOutput(getOutputWithoutIntro(ctxFactory)); - assertTrue(tabOutput.contains("--copy")); - assertTrue(tabOutput.contains("--copy&paste")); - assertEquals("", ctxFactory.getError()); - } - - @Test - public void testOptionWithPartiallyFilledInputTabCompletes() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - ctxFactory.setInput("test1 te\t\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - - String usefulOutput = getOutputWithoutIntro(ctxFactory); - String tabOutput = getTabOutput(usefulOutput); - assertTrue(tabOutput.length() == 0); - assertEquals(PROMPT + "exit", usefulOutput.split("\n")[1]); - assertEquals("", ctxFactory.getError()); - - } - - @Test - public void testFullOptionDoesNotTabComplete() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - ctxFactory.setInput("test1 test\t\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - - String usefulOutput = getOutputWithoutIntro(ctxFactory); - String tabOutput = getTabOutput(usefulOutput); - assertTrue(tabOutput.length() == 0); - assertEquals(PROMPT + "exit", usefulOutput.split("\n")[1]); - assertEquals("", ctxFactory.getError()); - - } - - @Test - public void testFullOptionWithSpaceTabCompletes() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - ctxFactory.setInput("test2longname --Paste \t\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - - String tabOutput = getTabOutput(getOutputWithoutIntro(ctxFactory)); - assertTrue(tabOutput.contains("--Paste")); - assertTrue(tabOutput.contains("--copy")); - assertTrue(tabOutput.contains("--copy&paste")); - assertTrue(tabOutput.contains("-c")); - assertTrue(tabOutput.contains("-p")); - assertTrue(tabOutput.contains("-v")); - assertEquals("", ctxFactory.getError()); - - } - - @Test - public void testFullOptionCompletesInline() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - - String input = "test2longn"; - ctxFactory.setInput(input + "\t\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - - String tabOutput = getTabOutput(getOutputWithoutIntro(ctxFactory)); - String inline = getTabbedInline(ctxFactory, input); - - assertEquals(0, tabOutput.length()); - assertTrue(inline.endsWith("test2longname")); - assertEquals("", ctxFactory.getError()); - } - - @Test - public void testSimilarOptionCompletesCommonPortionInline() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - - String input = "tes"; - ctxFactory.setInput(input + "\t\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - - String tabOutput = getTabOutput(getOutputWithoutIntro(ctxFactory)); - String inline = getTabbedInline(ctxFactory, input); - - assertTrue(tabOutput.length() != 0); - assertTrue(inline.endsWith("test")); - assertEquals("", ctxFactory.getError()); - } - - @Test - public void testSubOptionCompletesInline() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - - String input = "test2longname --Pas"; - ctxFactory.setInput(input + "\t\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - - String tabOutput = getTabOutput(getOutputWithoutIntro(ctxFactory)); - String inline = getTabbedInline(ctxFactory, input); - - assertEquals(0, tabOutput.length()); - assertTrue(inline.endsWith("--Paste")); - assertEquals("", ctxFactory.getError()); - } - - @Test - public void testSimilarSubOptionCompletesCommonPortionInline() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - - String input = "test2longname --cop"; - ctxFactory.setInput(input + "\t\nexit\n"); - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - - String tabOutput = getTabOutput(getOutputWithoutIntro(ctxFactory)); - String inline = getTabbedInline(ctxFactory, input); - - assertTrue(tabOutput.contains("--copy")); - assertTrue(tabOutput.contains("--copy&paste")); - assertTrue(inline.endsWith("--copy")); - assertEquals("", ctxFactory.getError()); - } - - @Test - public void testStartsCompleterRegistryWhenAvailable() throws CommandException { - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - ctxFactory.setInput("exit\n"); - - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - CompleterServiceRegistry registry = mock(CompleterServiceRegistry.class); - cmd.setCompleterServiceRegistry(registry); - cmd.run(ctx); - verify(registry).start(); - } - - @Test - public void testAttachesTabCompletionToConsoleReader() throws Exception { - TabCompletion tabCompletion = mock(TabCompletion.class); - cmd.setTabCompletion(tabCompletion); - - ServiceReference ref = mock(ServiceReference.class); - when(bundleContext.getServiceReference(Launcher.class.getName())).thenReturn(ref); - Launcher launcher = mock(Launcher.class); - when(bundleContext.getService(ref)).thenReturn(launcher); - - TestCommandContextFactory ctxFactory = new TestCommandContextFactory(bundleContext); - ctxFactory.setInput("exit\n"); - - Arguments args = new SimpleArguments(); - CommandContext ctx = ctxFactory.createContext(args); - cmd.run(ctx); - verify(tabCompletion).attachToReader(isA(ConsoleReader.class)); - } - - @Test - public void testSetCommandInfoSourceTriggersTabCompletionSetup() { - TabCompletion tabCompletion = mock(TabCompletion.class); - cmd.setTabCompletion(tabCompletion); - verify(tabCompletion, never()).setupTabCompletion(isA(CommandInfoSource.class)); - CommandInfoSource infoSource = mock(CommandInfoSource.class); - cmd.setCommandInfoSource(infoSource); - verify(tabCompletion).setupTabCompletion(infoSource); - } - - private String getOutputWithoutIntro(final TestCommandContextFactory ctxFactory) { - String[] allOutput = makeNewlinesConsistent(ctxFactory.getOutput()).split("\n"); - String[] outputWithoutIntro = Arrays.copyOfRange(allOutput, 2, allOutput.length); - return StringUtils.join("\n", Arrays.asList(outputWithoutIntro)); - } - - private String getTabOutput(final String outputToProcess) { - String[] allOutput = outputToProcess.split("\n"); - String tabOutput = ""; - for (String output : allOutput) { - if (!output.startsWith("Thermostat")) { - tabOutput += output; - } - } - return tabOutput; - } - - private String getTabbedInline(TestCommandContextFactory ctxFactory, String input) { - String inline = ""; - String[] lines = makeNewlinesConsistent(ctxFactory.getOutput()).split("\n"); - for(String line : lines) { - if (line.contains(input)) { - inline = line.split(PROMPT + input)[1]; - inline = inline.replaceAll(" ", ""); - return inline; - } - } - return inline; - } - - private String makeNewlinesConsistent(String input) { - return input.replace("\r\n", "\n"); - } - - private void setupCommandInfoSource() { - Collection<CommandInfo> infoList = new ArrayList<>(); - - CommandInfo info1 = mock(CommandInfo.class); - when(info1.getName()).thenReturn("test1"); - when(info1.getDescription()).thenReturn("test command 1"); - when(info1.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); - - ArrayList<Option> optionsList1 = new ArrayList<>(); - Option option1 = mock(Option.class); - when(option1.getLongOpt()).thenReturn("test"); - when(option1.getOpt()).thenReturn("t"); - Option option2 = mock(Option.class); - when(option2.getLongOpt()).thenReturn("Add"); - when(option2.getOpt()).thenReturn("A"); - Option option3 = mock(Option.class); - when(option3.getLongOpt()).thenReturn("remove"); - when(option3.getOpt()).thenReturn("r"); - optionsList1.add(option1); - optionsList1.add(option2); - optionsList1.add(option3); - - Options options1 = mock(Options.class); - when(info1.getOptions()).thenReturn(options1); - when(options1.getOptions()).thenReturn(new ArrayList<>(optionsList1)); - when(info1.getOptions().getOptions()).thenReturn(new ArrayList<>(optionsList1)); - - infoList.add(info1); - - CommandInfo info2 = mock(CommandInfo.class); - when(info2.getName()).thenReturn("test2longname"); - when(info2.getDescription()).thenReturn("test command 2"); - when(info2.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); - - ArrayList<Option> optionsList2 = new ArrayList<>(); - Option option4 = mock(Option.class); - when(option4.getLongOpt()).thenReturn("copy"); - when(option4.getOpt()).thenReturn("c"); - Option option5 = mock(Option.class); - when(option5.getLongOpt()).thenReturn("copy&paste"); - when(option5.getOpt()).thenReturn("p"); - Option option6 = mock(Option.class); - when(option6.getLongOpt()).thenReturn("Paste"); - when(option6.getOpt()).thenReturn("v"); - optionsList2.add(option4); - optionsList2.add(option5); - optionsList2.add(option6); - - Options options2 = mock(Options.class); - when(info2.getOptions()).thenReturn(options2); - when(options2.getOptions()).thenReturn(new ArrayList<>(optionsList2)); - when(info2.getOptions().getOptions()).thenReturn(new ArrayList<>(optionsList2)); - - infoList.add(info2); - - CommandInfo info3 = mock(CommandInfo.class); - when(info3.getName()).thenReturn("validate"); - when(info3.getDescription()).thenReturn("mock validate command"); - when(info3.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); - - ArrayList<Option> optionsList3 = new ArrayList<>(); - Option option7 = mock(Option.class); - when(option7.getLongOpt()).thenReturn("dbUrl"); - when(option7.getOpt()).thenReturn("d"); - Option option8 = mock(Option.class); - when(option8.getLongOpt()).thenReturn("loglevel"); - when(option8.getOpt()).thenReturn("l"); - Option option9 = mock(Option.class); - when(option9.getLongOpt()).thenReturn("agent"); - when(option9.getOpt()).thenReturn("a"); - Option option10 = mock(Option.class); - when(option10.getLongOpt()).thenReturn("fake-option"); - when(option10.getOpt()).thenReturn("f"); - optionsList3.add(option7); - optionsList3.add(option8); - optionsList3.add(option9); - optionsList3.add(option10); - - Options options3 = mock(Options.class); - when(info3.getOptions()).thenReturn(options3); - when(options3.getOptions()).thenReturn(new ArrayList<>(optionsList3)); - when(info3.getOptions().getOptions()).thenReturn(new ArrayList<>(optionsList3)); - - infoList.add(info3); - - when(infos.getCommandInfos()).thenReturn(infoList); - cmd.setCommandInfoSource(infos); - } - -} -
--- a/launcher/src/test/java/com/redhat/thermostat/launcher/internal/ShellPromptTest.java Wed May 17 18:11:05 2017 -0400 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,292 +0,0 @@ -/* - * Copyright 2012-2017 Red Hat, Inc. - * - * This file is part of Thermostat. - * - * Thermostat is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published - * by the Free Software Foundation; either version 2, or (at your - * option) any later version. - * - * Thermostat is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Thermostat; see the file COPYING. If not see - * <http://www.gnu.org/licenses/>. - * - * Linking this code with other modules is making a combined work - * based on this code. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. - * - * As a special exception, the copyright holders of this code give - * you permission to link this code with independent modules to - * produce an executable, regardless of the license terms of these - * independent modules, and to copy and distribute the resulting - * executable under terms of your choice, provided that you also - * meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module - * which is not derived from or based on this code. If you modify - * this code, you may extend this exception to your version of the - * library, but you are not obligated to do so. If you do not wish - * to do so, delete this exception statement from your version. - */ - -package com.redhat.thermostat.launcher.internal; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; - -import com.redhat.thermostat.common.cli.CommandException; -import com.redhat.thermostat.storage.core.DbService; - -public class ShellPromptTest { - - ShellPrompt shellPrompt; - - @Before - public void setup() { - shellPrompt = new ShellPrompt(); - } - - @Test - public void testDefaultConnectedPrompt() throws CommandException { - DbService dbService = mock(DbService.class); - when(dbService.getConnectionUrl()).thenReturn("http://unused.url.com"); - - shellPrompt.storageConnected(dbService); - - String expected = "Thermostat " + ShellPrompt.DEFAULT_CONNECTED_TOKEN + " > "; - assertEquals(expected, shellPrompt.getPrompt()); - } - - @Test - public void testDefaultDisconnectedPrompt() { - shellPrompt.storageDisconnected(); - - String expected = "Thermostat " + ShellPrompt.DEFAULT_DISCONNECTED_TOKEN + " > "; - assertEquals(expected, shellPrompt.getPrompt()); - } - - @Test - public void testInvalidConnectionUrl() throws CommandException { - DbService dbService = mock(DbService.class); - when(dbService.getConnectionUrl()).thenReturn("invalid-url"); - - shellPrompt.storageConnected(dbService); - - String expected = "Thermostat " + ShellPrompt.DEFAULT_CONNECTED_TOKEN + " > "; - assertEquals(expected, shellPrompt.getPrompt()); - } - - @Test - public void testCustomPrompt() { - String customPrompt = "TMS ::> "; - Map<String, String> customConfig = new HashMap<>(); - customConfig.put("shell-prompt", customPrompt); - shellPrompt.overridePromptConfig(customConfig); - - assertEquals(customPrompt, shellPrompt.getPrompt()); - } - - @Test - public void testConnectToken() { - String customPrompt = "%connect"; - Map<String, String> customConfig = new HashMap<>(); - customConfig.put("shell-prompt", customPrompt); - shellPrompt.overridePromptConfig(customConfig); - - String expected = ShellPrompt.DEFAULT_DISCONNECTED_TOKEN; - - assertEquals(expected, shellPrompt.getPrompt()); - } - - @Test - public void testURLToken() { - String customPrompt = "%url"; - Map<String, String> customConfig = new HashMap<>(); - customConfig.put("shell-prompt", customPrompt); - - shellPrompt.overridePromptConfig(customConfig); - - String url = "http://blob:9/meow"; - DbService dbService = mock(DbService.class); - when(dbService.getConnectionUrl()).thenReturn(url); - - shellPrompt.storageConnected(dbService); - - assertEquals(url, shellPrompt.getPrompt()); - } - - @Test - public void testProtocolToken() { - String customPrompt = "%protocol"; - Map<String, String> customConfig = new HashMap<>(); - customConfig.put("shell-prompt", customPrompt); - - shellPrompt.overridePromptConfig(customConfig); - - String url = "http://blob:9/meow"; - DbService dbService = mock(DbService.class); - when(dbService.getConnectionUrl()).thenReturn(url); - - shellPrompt.storageConnected(dbService); - - String expected = "http"; - - assertEquals(expected, shellPrompt.getPrompt()); - } - - @Test - public void testHostToken() { - String customPrompt = "%host"; - Map<String, String> customConfig = new HashMap<>(); - customConfig.put("shell-prompt", customPrompt); - - shellPrompt.overridePromptConfig(customConfig); - - String url = "http://blob:9/meow"; - DbService dbService = mock(DbService.class); - when(dbService.getConnectionUrl()).thenReturn(url); - - shellPrompt.storageConnected(dbService); - - String expected = "blob"; - - assertEquals(expected, shellPrompt.getPrompt()); - } - - @Test - public void testPortToken() { - String customPrompt = "%port"; - Map<String, String> customConfig = new HashMap<>(); - customConfig.put("shell-prompt", customPrompt); - - shellPrompt.overridePromptConfig(customConfig); - - String url = "http://blob:9/meow"; - DbService dbService = mock(DbService.class); - when(dbService.getConnectionUrl()).thenReturn(url); - - shellPrompt.storageConnected(dbService); - - String expected = "9"; - - assertEquals(expected, shellPrompt.getPrompt()); - } - - @Test - public void testUserToken() { - String expected = "username"; - - String customPrompt = "%user"; - Map<String, String> customConfig = new HashMap<>(); - customConfig.put("shell-prompt", customPrompt); - - shellPrompt.overridePromptConfig(customConfig); - - String url = "http://blob:9/meow"; - DbService dbService = mock(DbService.class); - when(dbService.getConnectionUrl()).thenReturn(url); - when(dbService.getUserName()).thenReturn(expected); - - shellPrompt.storageConnected(dbService); - - assertEquals(expected, shellPrompt.getPrompt()); - } - - @Test - public void testConnectString() { - String connectString = "%url"; - String url = "http://blob:9/meow"; - - String customPrompt = "%connect"; - Map<String, String> customConfig = new HashMap<>(); - customConfig.put("shell-prompt", customPrompt); - customConfig.put("connected-prompt", connectString); - - shellPrompt.overridePromptConfig(customConfig); - - DbService dbService = mock(DbService.class); - when(dbService.getConnectionUrl()).thenReturn(url); - shellPrompt.storageConnected(dbService); - - assertEquals(url, shellPrompt.getPrompt()); - } - - @Test - public void testComplexCustomPrompt() { - String url = "http://complex.url.com:9/test"; - DbService dbService = mock(DbService.class); - when(dbService.getConnectionUrl()).thenReturn(url); - - String customPrompt = "TMS %connect ::> "; - Map<String, String> customConfig = new HashMap<>(); - customConfig.put("shell-prompt", customPrompt); - - String connectPrompt = "[%url %host %port %protocol]"; - customConfig.put("connected-prompt", connectPrompt); - - shellPrompt.overridePromptConfig(customConfig); - shellPrompt.storageConnected(dbService); - - String expected = "TMS [http://complex.url.com:9/test complex.url.com 9 http] ::> "; - assertEquals(expected, shellPrompt.getPrompt()); - } - - @Test - public void testRepeatTokenPrompt() { - String url = "http://unused.url.com"; - DbService dbService = mock(DbService.class); - when(dbService.getConnectionUrl()).thenReturn(url); - - String customPrompt = "TMS %connect %connect ::> "; - Map<String, String> customConfig = new HashMap<>(); - customConfig.put("shell-prompt", customPrompt); - - shellPrompt.overridePromptConfig(customConfig); - - String expected = "TMS - - ::> "; - assertEquals(expected, shellPrompt.getPrompt()); - } - - @Test - public void testConnectTokenExpansion() { - String url = "http://unused.url.com"; - DbService dbService = mock(DbService.class); - when(dbService.getConnectionUrl()).thenReturn(url); - - String customPrompt = "TMS %connect ::> "; - Map<String, String> customConfig = new HashMap<>(); - customConfig.put("shell-prompt", customPrompt); - - String connectPrompt = "[CONNECT %connect]"; - customConfig.put("connected-prompt", connectPrompt); - - String disconnectPrompt = "[DISCONNECT %connect]"; - customConfig.put("disconnected-prompt", disconnectPrompt); - - shellPrompt.overridePromptConfig(customConfig); - - String expectedDisconnect = "TMS [DISCONNECT ] ::> "; - assertEquals(expectedDisconnect, shellPrompt.getPrompt()); - - shellPrompt.storageConnected(dbService); - - String expectedConnect = "TMS [CONNECT ] ::> "; - assertEquals(expectedConnect, shellPrompt.getPrompt()); - - shellPrompt.storageDisconnected(); - - assertEquals(expectedDisconnect, shellPrompt.getPrompt()); - } -}
--- a/launcher/src/test/java/com/redhat/thermostat/launcher/internal/TabCompletionTest.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/test/java/com/redhat/thermostat/launcher/internal/TabCompletionTest.java Wed May 17 18:12:02 2017 -0400 @@ -49,7 +49,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -202,14 +201,12 @@ when(mockCommand.getName()).thenReturn("mock-command"); when(mockCommand.getBundles()).thenReturn(Collections.<BundleInformation>emptyList()); when(mockCommand.getDescription()).thenReturn("description"); - when(mockCommand.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); when(mockCommand.getOptions()).thenReturn(mockOptions); CommandInfo fakeCommand = mock(CommandInfo.class); when(fakeCommand.getName()).thenReturn("fake-command"); when(fakeCommand.getBundles()).thenReturn(Collections.<BundleInformation>emptyList()); when(fakeCommand.getDescription()).thenReturn("description"); - when(fakeCommand.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); when(fakeCommand.getOptions()).thenReturn(fakeOptions); CommandInfoSource infoSource = mock(CommandInfoSource.class); @@ -280,14 +277,12 @@ when(mockCommand.getBundles()).thenReturn(Collections.<BundleInformation>emptyList()); when(mockCommand.getDescription()).thenReturn("description"); when(mockCommand.getSubcommands()).thenReturn(Collections.singletonList(subcommand)); - when(mockCommand.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); when(mockCommand.getOptions()).thenReturn(options); CommandInfo fakeCommand = mock(CommandInfo.class); when(fakeCommand.getName()).thenReturn("fake-command"); when(fakeCommand.getBundles()).thenReturn(Collections.<BundleInformation>emptyList()); when(fakeCommand.getDescription()).thenReturn("description"); - when(fakeCommand.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); when(fakeCommand.getOptions()).thenReturn(options); CommandInfoSource infoSource = mock(CommandInfoSource.class); @@ -321,8 +316,7 @@ when(parent.getBundles()).thenReturn(Collections.<BundleInformation>emptyList()); when(parent.getDescription()).thenReturn("parent desc"); when(parent.getSubcommands()).thenReturn(Collections.singletonList(subcommand)); - when(parent.getEnvironments()).thenReturn(EnumSet.of(Environment.CLI, Environment.SHELL)); - when(parent.getOptions()).thenReturn(parentOptions); + when(parent.getOptions()).thenReturn(parentOptions); CommandInfoSource infoSource = mock(CommandInfoSource.class); when(infoSource.getCommandInfos()).thenReturn(Collections.singletonList(parent));
--- a/launcher/src/test/java/com/redhat/thermostat/launcher/internal/TestCommandInfo.java Wed May 17 18:11:05 2017 -0400 +++ b/launcher/src/test/java/com/redhat/thermostat/launcher/internal/TestCommandInfo.java Wed May 17 18:12:02 2017 -0400 @@ -38,7 +38,6 @@ import java.util.Collections; import java.util.List; -import java.util.Set; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; @@ -54,7 +53,6 @@ private String usage; private Options options = new Options(); - private Set<Environment> environments; public TestCommandInfo(String name) { this.name = name; @@ -118,15 +116,6 @@ } @Override - public Set<Environment> getEnvironments() { - return environments; - } - - public void setAvailable(Set<Environment> environments) { - this.environments = environments; - } - - @Override public List<BundleInformation> getBundles() { return Collections.emptyList(); }
--- a/main/src/main/java/com/redhat/thermostat/main/internal/FrameworkProvider.java Wed May 17 18:11:05 2017 -0400 +++ b/main/src/main/java/com/redhat/thermostat/main/internal/FrameworkProvider.java Wed May 17 18:12:02 2017 -0400 @@ -242,7 +242,7 @@ private void runLauncher(Framework framework, String[] args) throws InterruptedException { Object launcher = getService(framework, Launcher.class.getName()); - callVoidReflectedMethod(launcher, "run", args, false); + callVoidReflectedMethod(launcher, "run", (Object) args); } private Object getService(Framework framework, String name) throws InterruptedException {
--- a/main/src/test/java/com/redhat/thermostat/main/internal/FrameworkProviderTest.java Wed May 17 18:11:05 2017 -0400 +++ b/main/src/test/java/com/redhat/thermostat/main/internal/FrameworkProviderTest.java Wed May 17 18:12:02 2017 -0400 @@ -222,7 +222,7 @@ provider.start(new String[] {}); - verify(launcher).run(new String[] {}, false); + verify(launcher).run(new String[] {}); } @Test