Esempio n. 1
0
  @Command(value = "\\.unload(\\??) (" + MODULE_REGEX + ")", allowPM = false)
  public void unloadModules(CommandContext ctx, String qm, String moduleNames) {
    final boolean showErrors = qm.isEmpty();
    for (String moduleName : moduleNames.split(" ")) {
      // Don't allow unloading Core
      if (moduleName.equals(this.getClass().getSimpleName())) {
        this.bot.sendNoticeTo(
            ctx.getResponseTarget(),
            "#error .unload cannot unload the %(#module)s module",
            this.getFriendlyName());
        continue;
      }

      try {
        this.bot.unloadModule(moduleName, false);
        try {
          this.bot.saveModules();
        } catch (ModuleSaveException e) {
          Log.e(e);
        }

        this.bot.sendNoticeTo(ctx.getResponseTarget(), "Module %(#module)s unloaded", moduleName);
      } catch (ModuleUnloadException e) {
        Log.e(e);
        if (showErrors) {
          this.bot.sendNoticeTo(ctx.getResponseTarget(), "#error %s", e.getMessage());
        }
      }
    }
  }
Esempio n. 2
0
 @Command("\\.rev")
 public void rev(CommandContext ctx) {
   final Git.Revision rev = this.bot.revision;
   ctx.respond(
       "Currently on revision %(#hash)s by %(#author)s -- %(#description)s",
       rev.getHash(), rev.getAuthor(), rev.getDescription());
   ctx.respond("%s", Git.revisionLink(rev));
 }
Esempio n. 3
0
  /*
   * (non-Javadoc)
   *
   * @see org.mobicents.ss7.management.console.CommandHandler#handle(org.mobicents .ss7.management.console.CommandContext,
   * java.lang.String)
   */
  @Override
  public void handle(CommandContext ctx, String commandLine) {
    String[] commands = commandLine.split(" ");
    if (commands.length != 1) {
      ctx.printLine("Invalid command.");
      return;
    }

    ctx.terminateSession();
  }
Esempio n. 4
0
  // Attempt to execute a command.
  private void executeMethod(String[] args, CommandSender sender, Object[] methodArgs)
      throws CommandException {
    String cmdName = args[0].toLowerCase();
    String modifier = args.length > 1 ? args[1] : "";
    boolean help = modifier.toLowerCase().equals("help");

    Method method = commands.get(cmdName + " " + modifier.toLowerCase());
    if (method == null && !help) method = commands.get(cmdName + " *");

    if (method == null && help) {
      executeHelp(args, sender);
      return;
    }

    if (method == null) throw new UnhandledCommandException();

    if (!serverCommands.contains(method) && sender instanceof ConsoleCommandSender)
      throw new ServerCommandException();

    if (!hasPermission(method, sender)) throw new NoPermissionsException();

    Command cmd = method.getAnnotation(Command.class);
    CommandContext context = new CommandContext(sender, args);

    if (context.argsLength() < cmd.min())
      throw new CommandUsageException(CommandMessages.TOO_FEW_ARGUMENTS, getUsage(args, cmd));

    if (cmd.max() != -1 && context.argsLength() > cmd.max())
      throw new CommandUsageException(CommandMessages.TOO_MANY_ARGUMENTS, getUsage(args, cmd));

    if (!cmd.flags().contains("*")) {
      for (char flag : context.getFlags())
        if (cmd.flags().indexOf(String.valueOf(flag)) == -1)
          throw new CommandUsageException("Unknown flag: " + flag, getUsage(args, cmd));
    }

    methodArgs[0] = context;

    for (Annotation annotation : registeredAnnotations.get(method)) {
      CommandAnnotationProcessor processor = annotationProcessors.get(annotation.annotationType());
      processor.process(sender, context, annotation, methodArgs);
    }

    Object instance = instances.get(method);
    try {
      method.invoke(instance, methodArgs);
    } catch (IllegalArgumentException e) {
      logger.log(Level.SEVERE, "Failed to execute command", e);
    } catch (IllegalAccessException e) {
      logger.log(Level.SEVERE, "Failed to execute command", e);
    } catch (InvocationTargetException e) {
      if (e.getCause() instanceof CommandException) throw (CommandException) e.getCause();
      throw new WrappedCommandException(e.getCause());
    }
  }
Esempio n. 5
0
  /*
   * (non-Javadoc)
   *
   * @see org.mobicents.ss7.management.console.CommandHandler#isAvailable(org.mobicents
   * .ss7.management.console.CommandContext)
   */
  @Override
  public boolean isAvailable(CommandContext commandContext) {
    // Available only in disconnected mode
    if (commandContext.isControllerConnected()) {
      commandContext.printLine(
          "The command is not available in the current context. Please disconnnect first");
      return false;
    }

    return true;
  }
 /**
  * Contains various available command strategies in {@link
  * org.mifosplatform.batch.command.internal}. Any new command Strategy will have to be added
  * within this function in order to initiate it within the constructor.
  */
 private void init() {
   this.commandStrategies.put(
       CommandContext.resource("clients").method("POST").build(), "createClientCommandStrategy");
   this.commandStrategies.put(
       CommandContext.resource("clients\\/\\d+").method("PUT").build(),
       "updateClientCommandStrategy");
   this.commandStrategies.put(
       CommandContext.resource("loans").method("POST").build(), "applyLoanCommandStrategy");
   this.commandStrategies.put(
       CommandContext.resource("savingsaccounts").method("POST").build(),
       "applySavingsCommandStrategy");
 }
Esempio n. 7
0
  @Command(
      name = "rename",
      descref = Messages.Help.Description.RENAME,
      permission = Permissions.PERMISSION_RENAME,
      minArgs = 2,
      usage = "/spleef rename <game> <to>")
  public void onRenameCommand(CommandContext context, HeavySpleef heavySpleef)
      throws CommandException {
    final CommandSender sender =
        context.getSender() instanceof Player
            ? heavySpleef.getSpleefPlayer(context.getSender())
            : context.getSender();

    final String from = context.getString(0);
    final String to = context.getString(1);

    GameManager manager = heavySpleef.getGameManager();

    CommandValidate.isTrue(
        manager.hasGame(from),
        i18n.getVarString(Messages.Command.GAME_DOESNT_EXIST).setVariable("game", from).toString());
    CommandValidate.isTrue(
        !manager.hasGame(to), i18n.getString(Messages.Command.GAME_ALREADY_EXIST));

    Game game = manager.getGame(from);
    final String oldName = game.getName();

    manager.renameGame(
        game,
        to,
        new FutureCallback<Void>() {

          @Override
          public void onSuccess(Void result) {
            sender.sendMessage(
                i18n.getVarString(Messages.Command.GAME_RENAMED)
                    .setVariable("from", oldName)
                    .setVariable("to", to)
                    .toString());
          }

          @Override
          public void onFailure(Throwable t) {
            sender.sendMessage(
                i18n.getVarString(Messages.Command.ERROR_ON_SAVE)
                    .setVariable("detail-message", t.toString())
                    .toString());
          }
        });
  }
Esempio n. 8
0
  @Command(value = "(?:\\.help|:question:) (.+)", allowPM = true)
  public JSONObject specific(CommandContext ctx, String search)
      throws JSONException, InvocationTargetException {
    // First, try module names
    for (NoiseModule module : this.bot.getModules().values()) {
      if (!module.showInHelp()) {
        continue;
      }
      if (search.equalsIgnoreCase(module.getFriendlyName())) {
        return new JSONObject()
            .put("name", module.getFriendlyName())
            .put("description", module.getDescription())
            .put("examples", module.getExamples());
      }
    }

    // Then try command pattern matching. This depends on BotUtils
    final NoiseModule botUtilsModule = this.bot.getModules().get("BotUtils");
    if (botUtilsModule != null) {
      final MessageResult result =
          botUtilsModule.processMessage(ctx.deriveMessage(".which " + search));
      final String[] modules = result.data.get().getStringArray("modules");
      if (modules.length > 0) {
        // TODO Show all modules if the command matches more than one?
        return this.specific(ctx, modules[0]);
      }
    }

    return new JSONObject().put("error", "Unknown module: " + search);
  }
Esempio n. 9
0
 @TabComplete("rename")
 public void onRenameTabComplete(
     CommandContext context, List<String> list, HeavySpleef heavySpleef) {
   GameManager manager = heavySpleef.getGameManager();
   if (context.argsLength() == 1) {
     for (Game game : manager.getGames()) {
       list.add(game.getName());
     }
   }
 }
Esempio n. 10
0
  /** execute */
  public CommandResult execute(CommandContext context) {
    // set output type
    context.setOutputType(getOutputType());

    CommandResult result = new CommandResult(this, context);

    // set result
    result.setOutputString(this.getExpansion());

    // indicate successful execution so that command result processing will work
    result.setExecutedSuccessfully(true);

    // grab input type so we can report back which input was used
    String inputTypeString = (String) context.get(CommandContext.INPUT_TYPE);
    InputType inputType = InputType.get(inputTypeString);

    result.setInputType(inputType);

    return result;
  }
Esempio n. 11
0
 @Command(value = "\\.reload(\\??) (" + MODULE_REGEX + ")", allowPM = false)
 public void reloadModules(CommandContext ctx, String qm, String moduleNames) {
   final boolean showErrors = qm.isEmpty();
   for (String moduleName : moduleNames.split(" ")) {
     try {
       if (this.bot.getModules().containsKey(moduleName)) {
         this.bot.reloadModule(moduleName);
         this.bot.sendNoticeTo(ctx.getResponseTarget(), "Module %(#module)s reloaded", moduleName);
       } else {
         this.bot.loadModule(moduleName);
         this.bot.sendNoticeTo(ctx.getResponseTarget(), "Module %(#module)s loaded", moduleName);
       }
     } catch (ModuleInitException | ModuleUnloadException e) {
       Log.e(e);
       if (showErrors) {
         this.bot.sendNoticeTo(ctx.getResponseTarget(), "#error %s", e.getMessage());
       }
     }
   }
 }
Esempio n. 12
0
 @Command("\\.sync")
 public void sync(CommandContext ctx) {
   try {
     Git.attemptUpdate();
     // attemptUpdate() will call NoiseBot.syncAll(), which handles outputting sync info to all
     // channels
   } catch (Git.SyncException e) {
     // Only output the error to the channel/user that requested the sync
     ctx.respond("#error %s", e.getMessage());
   }
 }
Esempio n. 13
0
 @Override
 public List<Command> getFinalizeCommand(CommandContext context) {
   if (primary == null) {
     return Collections.emptyList();
   }
   return Arrays.asList(
       new Command[] {
         new Command(
             Arrays.asList(
                 new String[] {
                   context.getHomePathPrefix() + CMD_FINALIZER,
                   primary,
                   batchId,
                   flowId,
                   context.getExecutionId(),
                 }),
             MODULE_NAME_PREFIX + primary,
             getProfileName(primary),
             getEnvironment(context)),
       });
 }
Esempio n. 14
0
 public void execute() {
   boolean continueExecution = true;
   while (continueExecution) {
     this.console.prompt("contacts> ");
     String commandLine = this.console.readLine();
     if (commandLine.trim().isEmpty()) {
       continue;
     }
     try {
       CommandContext context = createCommandContext(commandLine);
       CommandProcessor processor = ShellUtil.createProcessor(context.commandName());
       processor.setConsole(this.console);
       processor.setRepository(this.repository);
       processor.setContentManager(this.manager);
       if (processor.canExecute(context)) {
         continueExecution = processor.execute(context);
       }
     } catch (ParseException e) {
       this.console.error("ERROR: Could not process command (%s)%n", e.getMessage());
     }
   }
 }
Esempio n. 15
0
  /**
   * Returns an appropriate commandStrategy after determining it using the CommandContext of the
   * request. If no such Strategy is found then a default strategy is returned back.
   *
   * @param commandContext
   * @return CommandStrategy
   * @see org.mifosplatform.batch.command.internal.UnknownCommandStrategy
   */
  public CommandStrategy getCommandStrategy(final CommandContext commandContext) {

    if (this.commandStrategies.containsKey(commandContext)) {
      return (CommandStrategy)
          this.applicationContext.getBean(this.commandStrategies.get(commandContext));
    }

    for (ConcurrentHashMap.Entry<CommandContext, String> entry :
        this.commandStrategies.entrySet()) {
      if (commandContext.matcher(entry.getKey())) {
        return (CommandStrategy)
            this.applicationContext.getBean(this.commandStrategies.get(entry.getKey()));
      }
    }

    return new UnknownCommandStrategy();
  }
Esempio n. 16
0
 @Override
 public List<Command> getImportCommand(CommandContext context) {
   List<Command> results = new ArrayList<Command>();
   if (primary != null) {
     results.add(
         new Command(
             Arrays.asList(
                 new String[] {
                   context.getHomePathPrefix() + CMD_IMPORTER,
                   CMD_ARG_PRIMARY,
                   primary,
                   batchId,
                   flowId,
                   context.getExecutionId(),
                   "20380101000000",
                   context.getVariableList(),
                 }),
             MODULE_NAME_PREFIX + primary,
             getProfileName(primary),
             getEnvironment(context)));
   }
   for (String secondary : secondaries) {
     results.add(
         new Command(
             Arrays.asList(
                 new String[] {
                   context.getHomePathPrefix() + CMD_IMPORTER,
                   CMD_ARG_SECONDARY,
                   secondary,
                   batchId,
                   flowId,
                   context.getExecutionId(),
                   "20380101000000",
                   context.getVariableList(),
                 }),
             MODULE_NAME_PREFIX + secondary,
             getProfileName(secondary),
             getEnvironment(context)));
   }
   return results;
 }
Esempio n. 17
0
 public int invoke(CommandLine cl, CommandContext context, AnzoClient client)
     throws AnzoException {
   for (String arg : cl.getArgs()) {
     if (!context.isCURIE(arg) && !context.isURI(arg)) {
       throw new InvalidArgumentException("parameter is not a valid uri or prefixed URI: " + arg);
     }
     if (context.isURI(arg)) {
       CURIE curie = context.getCURIE(arg);
       if (curie == null) {
         try {
           System.out.println(context.getURI(arg));
         } catch (URISyntaxException e) {
           throw new InvalidArgumentException(e);
         }
       } else {
         System.out.println("[" + curie + "]");
       }
     } else {
       System.out.println("[" + context.getCURIE(arg) + "]");
     }
   }
   return 0;
 }
 public void exit(CommandContext commandContext, int exitCode, int pid) {
   if (pid < 0 || !removePid(pid)) {
     commandContext.stopCommand();
   }
 }
Esempio n. 19
0
 @Command("\\.owner\\?")
 public void isOwner(CommandContext ctx) {
   this.triggerIfOwner(ctx, () -> ctx.respond("#success You own this NoiseBot"), true);
 }
Esempio n. 20
0
 /**
  * This function either builds a GeoGitTransaction to run commands off of if there is a
  * transactionId to build off of or the GeoGit commandLocator otherwise.
  *
  * @param context - the context to get the information needed to get the commandLocator
  * @return
  */
 public Context getCommandLocator(CommandContext context) {
   if (transactionId != null) {
     return new GeogitTransaction(context.getGeoGIT().getContext(), transactionId);
   }
   return context.getGeoGIT().getContext();
 }
 @Override
 public boolean canExecute(CommandContext context) {
   return !context.hasOptions() && !context.hasTarget();
 }