@Override
  public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (sender instanceof Player) {
      if (sender.isOp() || sender.hasPermission("wg")) {
        if (args.length == 0) {
          sender.sendMessage("not supported!");
          if (supported) {
            sender.sendMessage(ChatColor.GREEN + "Applying on WorldEdit region.");

            // Retrieve session.
            PlayerSession session =
                Starving.getInstance().getWorldGenManager().getSession((Player) sender);

            // Create definition.
            AffectedBlocksDefinition definition =
                new RegionAffectedBlocksDef(new Region(null, null, null));

            session.getFilter().apply(definition, session.getFilterProperties());
          }
        } else {
          sender.sendMessage(ChatColor.RED + "Usage: /ar ");
        }
      } else {
        sender.sendMessage(ChatColor.RED + "Not enough permissions!");
      }
    } else {
      sender.sendMessage(ChatColor.RED + "This reason can be only used by players!");
    }
    return true;
  }
Ejemplo n.º 2
0
  public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if ((_plugin.permissions != null
            && _plugin.permissions.has((Player) sender, "mobbounty.commands.mbtm"))
        || (_plugin.permissions == null && sender.isOp())) {
      if (args.length == 2) {
        if (args[1].matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")) {
          Double amount = Double.parseDouble(args[1]);
          MobBountyTime time = MobBountyTime.getTimeFromString(args[0]);

          if (time != null) {
            _plugin
                .getConfigManager()
                .setProperty(
                    MobBountyConfFile.MULTIPLIERS, "Time." + time.getName(), amount.toString());

            String message = _plugin.getLocaleManager().getString("MBGMChange");
            if (message != null) {
              message = message.replace("%T", time.getName()).replace("%A", amount.toString());
              sender.sendMessage(message);
            }
          } else this.commandUsage(sender, label);
        } else this.commandUsage(sender, label);
      } else this.commandUsage(sender, label);
    } else {
      String message = _plugin.getLocaleManager().getString("NoAccess");
      if (message != null) sender.sendMessage(message);
    }

    return true;
  }
Ejemplo n.º 3
0
 private boolean checkPerm(String perm, CommandSender sender) {
   if (sender.isOp()) return true;
   if (sender.hasPermission(perm)) return true;
   if (sender.hasPermission("andeedee.hc.*")) return true;
   if (sender.hasPermission("andeedee.*")) return true;
   return false;
 }
Ejemplo n.º 4
0
 private String getShortDescription(CommandSender sender, Command cmd) {
   String msg = "\u00a73" + cmd.getName();
   String[] aliases = cmd.getAliases();
   if (aliases.length > 1) {
     msg += "\u00a77";
     for (int i = 1; i < aliases.length; i++) {
       msg += " | " + aliases[i];
     }
   }
   msg += "\u00a7a";
   for (String param : cmd.getParams()) {
     if (param.startsWith("?")) {
       msg += " [" + param.substring(1) + "]";
     } else {
       msg += " <" + param + ">";
     }
   }
   if (cmd instanceof CompositeCommand) {
     msg += " [command|help]";
   }
   msg += "\u00a77 - \u00a7e";
   msg += cmd.getDescription();
   if (sender.isOp() && cmd.getPermission() != null) {
     msg += " \u00a7c(" + cmd.getPermission() + ")";
   }
   msg += "\n";
   return msg;
 }
 @Override
 public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
   if (sender instanceof Player) {
     if (sender.isOp() || sender.hasPermission("wg")) {
       if (args.length == 1) {
         int size = Integer.parseInt(args[0]);
         if (size > 10) {
           sender.sendMessage(ChatColor.GOLD + "WARNING: Large brush size selected!");
         }
         worldGenManager.getSession((Player) sender).setBrushSize(size);
         sender.sendMessage(ChatColor.GREEN + "Brush size set to " + size + ".");
       } else {
         sender.sendMessage(
             ChatColor.YELLOW
                 + "Current brush size: "
                 + worldGenManager.getSession((Player) sender).getBrush().getSize());
         sender.sendMessage(ChatColor.RED + "Usage: /bs <size>");
       }
     } else {
       sender.sendMessage(ChatColor.RED + "Not enough permissions!");
     }
   } else {
     sender.sendMessage(ChatColor.RED + "This reason can be only used by players!");
   }
   return true;
 }
Ejemplo n.º 6
0
 @Override
 public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
   if (sender.hasPermission("NEC.fbroadcast")
       || sender.isOp()
       || sender instanceof BlockCommandSender
       || sender instanceof ConsoleCommandSender) {
     if (command.getName().equalsIgnoreCase("FBroadcast")) {
       if (args.length == 0) {
         sender.sendMessage(plugin.prefix + "Use " + plugin.SText + "/FBroadcast <message>");
         return true;
       } else {
         StringBuilder msg = new StringBuilder(args[0]);
         for (int i = 1; i < args.length; i++) {
           msg.append(" ").append(args[i]);
         }
         String m = msg.toString();
         String m1 = ChatColor.translateAlternateColorCodes('&', m);
         Bukkit.broadcastMessage(m1);
         return true;
       }
     }
   }
   sender.sendMessage(plugin.prefix + "You don't have permissions to use FBroadcast");
   return true;
 }
Ejemplo n.º 7
0
  public boolean checkPermissions(CommandSender sender) {
    if (!(sender instanceof Player) || sender.isOp()) return true;

    for (String p : permissions) {
      if (sender.hasPermission(p)) return true;
    }

    return false;
  }
Ejemplo n.º 8
0
 public boolean checkPlayerPermission(CommandSender sender, String permission) {
   if (!(sender instanceof Player) || sender.isOp()) {
     return true;
   } else if (!permissions.has(sender, permission.toLowerCase())) {
     sender.sendMessage("You don't have permission to use this command!");
     return false;
   }
   return true;
 }
Ejemplo n.º 9
0
 public boolean isAdmin(CommandSender s) {
   if (!plugin.PermissionUse && s.isOp()) return true;
   if (!plugin.PermissionUse) return false;
   if (s instanceof Player) {
     if (plugin.PermissionH.has((Player) s, "lc.admin")) return true;
   } else {
     return false;
   }
   return false;
 }
Ejemplo n.º 10
0
  /**
   * Checks permissions.
   *
   * @param sender
   * @param perm
   * @return
   */
  public boolean hasPermission(CommandSender sender, String perm) {
    if (sender.isOp()) {
      return true;
    }

    // Invoke the permissions resolver
    if (sender instanceof Player) {
      return perms.hasPermission(((Player) sender).getName(), perm);
    }

    return false;
  }
Ejemplo n.º 11
0
  @Override
  public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (cmd.getName().equalsIgnoreCase("kit")) {
      if (1 > args.length) return false;

      if (args[0].equalsIgnoreCase("list")) {
        listPackages(sender);
      } else if (args[0].equalsIgnoreCase("reload")) {
        if (sender.isOp()) {
          sender.sendMessage(ChatColor.DARK_GRAY + "[kits] Reloading kits.");
          reloadPackages();
        } else {
          sender.sendMessage(
              ChatColor.DARK_GRAY
                  + "[kits] "
                  + ChatColor.RED
                  + "ERROR: This command is restricted to Admins.");
        }
      } else if (args[0].equalsIgnoreCase("cooling")) {
        if (sender.isOp()) {
          listPackageCooldowns(sender);
        } else {
          sender.sendMessage(
              ChatColor.DARK_GRAY
                  + "[kits] "
                  + ChatColor.RED
                  + "ERROR: This command is restricted to Admins.");
        }
      } else {
        if (!(sender instanceof Player)) {
          sender.sendMessage(ChatColor.RED + "[kits] ERROR: Kits can only be spawned by players.");
        } else {
          givePlayerPackage((Player) sender, args[0]);
        }
      }
      return true;
    }

    return false;
  }
Ejemplo n.º 12
0
  @Override
  public boolean execute(CommandSender commandSender, Command command, String s, String[] args)
      throws InsufficientPermissionException {

    if (!commandSender.hasPermission(new Permission("wh.reload")) && !commandSender.isOp()) {
      throw new InsufficientPermissionException();
    }

    Main.getInstance().onDisable();
    Main.getInstance().onEnable();

    commandSender.sendMessage("message.reload.success");

    return true;
  }
Ejemplo n.º 13
0
 public boolean check(CommandSender sender, String permNode) {
   if (sender instanceof Player) {
     if (Permissions == null) {
       if (sender.isOp()) {
         return true;
       }
       return false;
     } else {
       Player player = (Player) sender;
       return Permissions.has(player, permNode);
     }
   } else if (sender instanceof ConsoleCommandSender) {
     return true;
   } else {
     return false;
   }
 }
Ejemplo n.º 14
0
    public static CommandBlockerRank getSenderRank(CommandSender sender) {
      if (!TFM_AdminList.isSuperAdmin(sender)) {
        if (sender.isOp()) {
          return OP;
        }

        return ANYONE;
      } else {
        if (TFM_AdminList.isSeniorAdmin(sender)) {
          return SENIOR;
        }

        if (!(sender instanceof Player)) {
          return TELNET;
        }

        return SUPER;
      }
    }
Ejemplo n.º 15
0
  @Override
  public boolean onCommand(CommandSender cs, Command command, String label, String[] args) {

    if (!cs.isOp()) {
      sendMessage(cs, ChatColor.RED + "You must be an OP to reload filters");
      return true;
    }
    if ((args.length == 0) || (args.length == 1 && "help".equals(args[0]))) {
      sendMessage(cs, ChatColor.YELLOW + "Usage: /tlmd reload");
      return true;
    }

    if ("reload".equals(args[0])) {
      initializeMasterFilter();
      loadFilters();
      sendMessage(cs, ChatColor.GREEN + (this.masterFilter.filterCount() + " filter(s) loaded"));
      return true;
    }
    return super.onCommand(cs, command, label, args);
  }
Ejemplo n.º 16
0
 public boolean onCommand(CommandSender s, Command c, String l, String[] args) {
   if (l.equalsIgnoreCase("createcode")) {
     if (args.length < 2) {
       return false;
     } else {
       if (s instanceof Player) {
         if (s.isOp()) {
           CFVouchers.pl.getConfig().set("vouchers." + args[0], args[1]);
           ((Player) s).sendMessage(ChatColor.GREEN + "Voucher code '" + args[0] + "' created!");
         } else {
           ((Player) s).sendMessage(ChatColor.RED + "You have no permisson to create vouchers.");
         }
       } else {
         CFVouchers.pl.getConfig().set("vouchers." + args[0], args[1]);
         System.out.println(ChatColor.GREEN + "Voucher code created!");
       }
     }
   }
   return true;
 }
Ejemplo n.º 17
0
  // todo: multispawns support
  public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { // Reload
      // todo: permissions
      if (!(sender instanceof Player) || sender.hasPermission("setspawn.reload") || sender.isOp()) {
        sender.sendMessage("[SetSpawn] Configuration reloaded.");
        plugin.cm.save("spawn");
        plugin.cm.loadAll();
        return true;
      }
    } else {
      if (!(sender instanceof Player)) {
        sender.sendMessage("This command can be executed only by player.");
        return true;
      }

      Player p = (Player) sender;
      Location l = p.getLocation();
      String spawnName;
      if (args.length == 1) {
        spawnName = args[0].toLowerCase();
      } else {
        spawnName = "default";
      }
      plugin.setSpawnLocation(
          spawnName,
          l.getWorld().getName(),
          l.getX(),
          l.getY(),
          l.getZ(),
          l.getYaw(),
          l.getPitch());
      p.sendMessage(plugin.getMessage("messages.spawnset"));
      return true;
    }

    return true;
  }
Ejemplo n.º 18
0
 @Override
 public boolean execute(
     CommandSender sender, String alias, Map<String, Object> data, String... args) {
   if (!CommandManager.isRequirementsMet(sender, this)) {
     return false;
   }
   if (args.length == 0 || (args.length == 1 && args[0].matches(HELP_PATTERN))) {
     showUsage(sender, 1);
   } else if (args.length > 1 && args[0].matches(HELP_PATTERN)) {
     showUsage(sender, args[1]);
   } else if (args.length > params.length) {
     String cmdName = args[params.length].toLowerCase();
     Command cmd = aliasMap.get(cmdName);
     String[] subArgs = new String[args.length - 1 - params.length];
     System.arraycopy(args, 1 + params.length, subArgs, 0, subArgs.length);
     int ix = 0;
     for (String p : params) {
       data.put(p, args[ix++]);
     }
     if (!hasAccess(cmd, sender)) {
       if (cmd != null && sender.isOp()) {
         sender.sendMessage(
             MessageFormat.format(
                 "\u00a7eYou do not have access (\u00a74{0}\u00a7e)", cmd.getPermission()));
       } else {
         sender.sendMessage("\u00a7eYou do not have access");
       }
       showUsage(sender, args[0]);
     } else if (!cmd.execute(sender, cmdName, data, subArgs)) {
       showUsage(sender, args[0]);
     }
   } else {
     showUsage(sender, 1);
   }
   return true;
 }
  @Override
  public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    boolean permissionButtonlock = false;
    boolean permissionButtonlockOp = false;

    if (sender instanceof Player) {

      if (ButtonLock.permissions()) {
        // use Permission
        if (ButtonLock.hasPermission(
            (Player) sender, ButtonLock.PERMISSION_NODE_ButtonLock_buttonlock_normal)) {
          permissionButtonlock = true;
        }

        if (ButtonLock.hasPermission(
            (Player) sender, ButtonLock.PERMISSION_NODE_ButtonLock_buttonlock_op)) {
          permissionButtonlock = true;
          permissionButtonlockOp = true;
        }

        if (!permissionButtonlock && !permissionButtonlockOp) {
          printErrorPermissionButtonLockNormal(sender);
          printErrorPermissionButtonLockOP(sender);
        }
      } else {
        // no Permission installed ! (op only)
        if (!sender.isOp() && ButtonLock.getButtonLockConfig().oPOnly) {
          sender.sendMessage(ButtonLock.getCurrentLanguage().COMMAND_OP_ONLY);
          return true;
        } else {
          permissionButtonlock = true;
          permissionButtonlockOp = true;
        }
      }

    } else {
      permissionButtonlockOp = true;
    }

    if (args.length == 1) {
      // version ...
      if (args[0].equalsIgnoreCase("version")
          || args[0].equalsIgnoreCase("ver")
          || args[0].equalsIgnoreCase("v")) {

        String msg =
            ButtonLock.getPluginDescriptionFile().getName()
                + " "
                + ButtonLock.getPluginDescriptionFile().getVersion()
                + " "
                + ButtonLock.getPluginDescriptionFile().getAuthors();
        if (sender instanceof Player) {
          msg =
              ChatColor.RED
                  + ButtonLock.getPluginDescriptionFile().getName()
                  + " "
                  + ChatColor.GRAY
                  + ButtonLock.getPluginDescriptionFile().getVersion()
                  + " "
                  + ChatColor.GOLD
                  + ButtonLock.getPluginDescriptionFile().getAuthors();
        }

        sender.sendMessage(msg);
        return true;
      }

      if (args[0].equalsIgnoreCase("clearpasswordlist")
          || args[0].equalsIgnoreCase("clearpwlist")
          || args[0].equalsIgnoreCase("clrpwl")) {
        if (sender instanceof Player) {
          PlayerVars currentVars = ButtonLock.getPlayerVars((Player) sender);

          if (currentVars != null) {
            currentVars.clearEnteredPasswords();
            sender.sendMessage(ButtonLock.getCurrentLanguage().PASSWORDLIST_CLEAR);
          }
        } else {
          sender.sendMessage(
              String.format(
                  ButtonLock.getCurrentLanguage().COMMAND_INGAME_ONLY,
                  ButtonLock.getConsoleOutputHeader()));
        }
        return true;
      }
    }

    if (args.length >= 1 && permissionButtonlockOp) {

      if (args[0].equalsIgnoreCase("debug")) {

        if (args.length == 1) {
          ButtonLock.debugmode = !ButtonLock.debugmode;

          if (ButtonLock.debugmode == true) {
            if (sender instanceof Player)
              sender.sendMessage(
                  ChatColor.GOLD
                      + ButtonLock.getConsoleOutputHeader()
                      + ChatColor.GRAY
                      + " Debug mode"
                      + ChatColor.GOLD
                      + " enabled");
            ButtonLock.getButtonlockLogger()
                .info(ButtonLock.getConsoleOutputHeader() + " Debug mode enabled");
          } else {
            if (sender instanceof Player)
              sender.sendMessage(
                  ChatColor.GOLD
                      + ButtonLock.getConsoleOutputHeader()
                      + ChatColor.GRAY
                      + " Debug mode"
                      + ChatColor.GOLD
                      + " disabled");
            ButtonLock.getButtonlockLogger()
                .info(ButtonLock.getConsoleOutputHeader() + " Debug mode disabled");
          }
        } else if (args.length == 3) {
          if (args[1].equalsIgnoreCase("deactivate")
              || args[1].equalsIgnoreCase("deactiv")
              || args[1].equalsIgnoreCase("da")) {
            ButtonLock.notDebugedEvents.add(args[2]);
            if (sender instanceof Player)
              sender.sendMessage(
                  ChatColor.GOLD
                      + ButtonLock.getConsoleOutputHeader()
                      + ChatColor.GRAY
                      + " Disabled debug for all events which contains '"
                      + ChatColor.GOLD
                      + args[2]
                      + ChatColor.GRAY
                      + "' in there name");
            ButtonLock.getButtonlockLogger()
                .info(
                    ButtonLock.getConsoleOutputHeader()
                        + " Disabled debug for all events which contains '"
                        + args[2]
                        + "' in there name");
          }

          if (args[1].equalsIgnoreCase("activate")
              || args[1].equalsIgnoreCase("activ")
              || args[1].equalsIgnoreCase("a")) {
            ButtonLock.notDebugedEvents.remove(args[2]);
            if (sender instanceof Player)
              sender.sendMessage(
                  ChatColor.GOLD
                      + ButtonLock.getConsoleOutputHeader()
                      + ChatColor.GRAY
                      + " Enabled debug for all events which contains '"
                      + ChatColor.GOLD
                      + args[2]
                      + ChatColor.GRAY
                      + "' in there name");
            ButtonLock.getButtonlockLogger()
                .info(
                    ButtonLock.getConsoleOutputHeader()
                        + " Enabled debug for all events which contains '"
                        + args[2]
                        + "' in there name");
          }

          if (args[1].equalsIgnoreCase("activate")
              || args[1].equalsIgnoreCase("activ")
              || args[1].equalsIgnoreCase("a") && args[2].equalsIgnoreCase("all")) {
            ButtonLock.notDebugedEvents.clear();
            if (sender instanceof Player)
              sender.sendMessage(
                  ChatColor.GOLD
                      + ButtonLock.getConsoleOutputHeader()
                      + ChatColor.GRAY
                      + " Enabled debug for "
                      + ChatColor.GOLD
                      + "all"
                      + ChatColor.GRAY
                      + " events");
            ButtonLock.getButtonlockLogger()
                .info(ButtonLock.getConsoleOutputHeader() + " Enabled debug for all events");
          }
        }
        return true;
      }

      if (args[0].equalsIgnoreCase("getall")) {

        String output = ButtonLock.getCurrentLanguage().GROUP_INFO + "\n";
        int index = 1;

        for (LockedBlockGroup group : ButtonLock.grouplist) {
          output +=
              ChatColor.DARK_RED
                  + "----------- GROUP # "
                  + ChatColor.GOLD
                  + String.format("%10s", index)
                  + ChatColor.DARK_RED
                  + " -----------\n";

          ArrayList<Material> materials = new ArrayList<Material>();

          String status = ButtonLock.getCurrentLanguage().LOCKED;
          String protectionMode = ButtonLock.getCurrentLanguage().PASSWORD;
          String costs = String.format(ButtonLock.getCurrentLanguage().COSTS, group.costs);

          if (group.costs == 0 && ButtonLock.getButtonLockConfig().economyIsFreeAsDefault == false)
            costs = ButtonLock.getCurrentLanguage().COSTS_FREE;
          if (group.isUnlocked()) status = ButtonLock.getCurrentLanguage().UNLOCKED;
          if (group.getProtectionMode() == PROTECTION_MODE.PRIVATE)
            protectionMode = ButtonLock.getCurrentLanguage().PRIVATE;
          if (group.getProtectionMode() == PROTECTION_MODE.PUBLIC)
            protectionMode = ButtonLock.getCurrentLanguage().PUBLIC;

          output +=
              String.format(ButtonLock.getCurrentLanguage().PROTECTION_MODE_IS, protectionMode)
                  + "\n";
          output += String.format(ButtonLock.getCurrentLanguage().STATUS, status) + "\n";
          output += costs + "\n";
          output +=
              String.format(
                      ButtonLock.getCurrentLanguage().PROTECTION_OWNER_LIST,
                      ButtonLock.getCurrentLanguage().getList(group.getOwnerList()))
                  + "\n";
          output +=
              String.format(
                      ButtonLock.getCurrentLanguage().ONE_TIME_PASSWORDS,
                      group.getOneTimePasswords())
                  + "\n";
          output +=
              String.format(ButtonLock.getCurrentLanguage().GROUP_SIZE, "" + group.getGroupSize())
                  + "\n";

          for (int blockIndex = 0; blockIndex < group.getGroupSize(); blockIndex++) {
            materials.add(group.getBlock(blockIndex).getType());
          }

          String materialID = String.valueOf(group.getBlock(0).getTypeId());
          if (group.getBlock(0).getData() > 0)
            materialID += ":" + Integer.valueOf(group.getBlock(0).getData());
          output +=
              String.format(
                      ButtonLock.getCurrentLanguage().MATERIAL,
                      ButtonLock.getCurrentLanguage().getList(materials.toArray()),
                      materialID)
                  + "\n";
          output += ChatColor.DARK_RED + "-----------------------------------------\n";
        }

        output += ButtonLock.getCurrentLanguage().GROUP_INFO_ENDE;
        sender.sendMessage(output);
        return true;
      }

      // save all ...
      if (args[0].equalsIgnoreCase("save") || args[0].endsWith("s")) {
        ButtonLock.getButtonLockConfig().write();
        ButtonLock.lockedGroupsFile.write();

        String msg = "All config-files saved ... ";
        if (sender instanceof Player) sender.sendMessage(ChatColor.GRAY + msg);
        ButtonLock.getButtonlockLogger().info(ButtonLock.getConsoleOutputHeader() + " " + msg);
        return true;
      }

      // reload all ...
      if (args[0].equalsIgnoreCase("reload") || args[0].endsWith("rl")) {
        ButtonLock.setButtonLockConfig(new Config());
        ButtonLock.grouplist = new ArrayList<LockedBlockGroup>();

        ButtonLock.getButtonLockConfig().read();
        ButtonLock.lockedGroupsFile.read();

        String msg = "All config-files reloaded ... ";
        if (sender instanceof Player) sender.sendMessage(ChatColor.GRAY + msg);
        ButtonLock.getButtonlockLogger().info(ButtonLock.getConsoleOutputHeader() + " " + msg);
        return true;
      }

      // remove a locked group ...
      if (args[0].equalsIgnoreCase("remove") || args[0].equalsIgnoreCase("r")) {
        if (sender instanceof Player) {
          PlayerVars currentVars = ButtonLock.getPlayerVars((Player) sender);

          if (currentVars != null) {
            LockedBlockGroup group = currentVars.getCurrentClickedLockedGroup();

            if (group != null) {
              ButtonLock.removeLockedBlock(group);
              sender.sendMessage(ButtonLock.getCurrentLanguage().PROTECTION_REMOVED);
            } else {
              sender.sendMessage(ButtonLock.getCurrentLanguage().WHICH_BLOCK);
            }
          }
        } else {
          sender.sendMessage(
              String.format(
                  ButtonLock.getCurrentLanguage().COMMAND_INGAME_ONLY,
                  ButtonLock.getConsoleOutputHeader()));
        }
        return true;
      }
    }

    if (args.length == 2 && permissionButtonlockOp) {

      // reset ...
      if (args[0].equalsIgnoreCase("reset")) {

        boolean all = false;
        boolean langs = false;
        boolean config = false;
        boolean groups = false;

        if (args[1].equalsIgnoreCase("all")) all = true;
        if (args[1].equalsIgnoreCase("lang") || args[1].equalsIgnoreCase("langs")) langs = true;
        if (args[1].equalsIgnoreCase("config")) config = true;
        if (args[1].equalsIgnoreCase("group") || args[1].equalsIgnoreCase("groups")) groups = true;

        if (langs || all) {
          // reset language ...
          LanguageLoader.updateLanguages(true);

          String msg = ButtonLock.getConsoleOutputHeader() + " Languages reseted ...";
          if (sender instanceof Player) sender.sendMessage(ChatColor.GRAY + msg);
          ButtonLock.getButtonlockLogger().info(msg);
        }

        if (config || all) {
          // reset config ...
          ButtonLock.setButtonLockConfig(new Config());
          ButtonLock.getButtonLockConfig().update(true);

          String msg = ButtonLock.getConsoleOutputHeader() + " Config reseted ... ";
          if (sender instanceof Player) sender.sendMessage(ChatColor.GRAY + msg);
          ButtonLock.getButtonlockLogger().info(msg);
        }

        if (groups || all) {
          // reset grouplist ...
          ButtonLock.grouplist = new ArrayList<LockedBlockGroup>();
          ButtonLock.lockedGroupsFile.write();

          String msg = ButtonLock.getConsoleOutputHeader() + " Locked Groups reseted ... ";
          if (sender instanceof Player) sender.sendMessage(ChatColor.GRAY + msg);
          ButtonLock.getButtonlockLogger().info(msg);
        }

        return true;
      }
    }

    if (args.length >= 2 && permissionButtonlockOp) {

      if (args[0].equalsIgnoreCase("protectableBlocks")
          || args[0].equalsIgnoreCase("protectableBlock")
          || args[0].equalsIgnoreCase("pab")) {

        PlayerVars currentPlayerVars = null;
        if (sender instanceof Player) currentPlayerVars = ButtonLock.getPlayerVars((Player) sender);

        ArrayList<Material> materials = new ArrayList<Material>();

        if (currentPlayerVars != null && args.length == 2) {
          if (currentPlayerVars.getCurrentClickedBlock() != null) {
            materials.add(currentPlayerVars.getCurrentClickedBlock().getType());
          }
        }

        if (materials.isEmpty() && args.length == 3) {
          for (Material currentMatrial : Material.values()) {

            String[] material = new String[2];
            if (args[2].contains(":")) {
              material = args[2].split(":");
            } else if (args[2].contains("-")) {
              material = args[2].split("-");
            } else {
              material[0] = args[2];
              material[1] = "0";
            }

            boolean argIsID = true;

            int id = 0;

            @SuppressWarnings("unused")
            int data = 0;
            try {
              id = Integer.valueOf(material[0]);
              data = Integer.valueOf(material[1]);
            } catch (Exception e) {
              argIsID = false;
            }

            if (argIsID) {
              if (currentMatrial.getId() == id) {
                materials.add(currentMatrial);
              }
            } else {
              if (currentMatrial.name().toLowerCase().startsWith(args[2].toLowerCase())) {
                materials.add(currentMatrial);
              }
            }
          }
        }

        if (materials.isEmpty()) {
          if (sender instanceof Player) {
            sender.sendMessage(ButtonLock.getCurrentLanguage().WHICH_BLOCK);
          } else {
            sender.sendMessage(
                String.format(
                    ButtonLock.getCurrentLanguage().CONSOLE_WHICH_MATERIAL,
                    ButtonLock.getConsoleOutputHeader()));
          }
          return true;
        }

        if (args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("a")) {
          for (Material material : materials) {
            if (!ButtonLock.lockableBlocksList.contains(materials))
              ButtonLock.lockableBlocksList.add(material);
          }

          if (sender instanceof Player) {
            sender.sendMessage(
                String.format(
                    ButtonLock.getCurrentLanguage().MATERIALS_ADDED,
                    ButtonLock.getCurrentLanguage().getList(materials.toArray())));
          } else {
            sender.sendMessage(
                String.format(
                    ButtonLock.getCurrentLanguage().CONSOLE_MATERIALS_ADDED,
                    ButtonLock.getConsoleOutputHeader(),
                    ButtonLock.getCurrentLanguage().getList(materials.toArray(), false)));
          }
          return true;
        }

        if (args[1].equalsIgnoreCase("remove") || args[1].equalsIgnoreCase("r")) {
          for (Material material : materials) {
            if (ButtonLock.lockableBlocksList.contains(materials))
              ButtonLock.lockableBlocksList.remove(material);
          }
          if (sender instanceof Player) {
            sender.sendMessage(
                String.format(
                    ButtonLock.getCurrentLanguage().MATERIALS_REMOVED,
                    ButtonLock.getCurrentLanguage().getList(materials.toArray())));
          } else {
            sender.sendMessage(
                String.format(
                    ButtonLock.getCurrentLanguage().CONSOLE_MATERIALS_REMOVED,
                    ButtonLock.getConsoleOutputHeader(),
                    ButtonLock.getCurrentLanguage().getList(materials.toArray(), false)));
          }
          return true;
        }
      }
    }

    if (sender instanceof Player) {
      if (args.length == 1) {

        if (args[0].equalsIgnoreCase("information")
            || args[0].equalsIgnoreCase("info")
            || args[0].equalsIgnoreCase("i")) {

          PlayerVars currentPlayerVars = ButtonLock.getPlayerVars((Player) sender);

          if (currentPlayerVars != null) {
            LockedBlockGroup group = currentPlayerVars.getCurrentClickedLockedGroup();
            Block block = currentPlayerVars.getCurrentClickedBlock();

            sender.sendMessage(ButtonLock.getCurrentLanguage().GROUP_INFO);

            ArrayList<Material> materials = new ArrayList<Material>();

            if (group != null) {
              String status = ButtonLock.getCurrentLanguage().LOCKED;
              String protectionMode = ButtonLock.getCurrentLanguage().PASSWORD;
              String costs = String.format(ButtonLock.getCurrentLanguage().COSTS, group.costs);

              if (group.costs == 0
                  && ButtonLock.getButtonLockConfig().economyIsFreeAsDefault == false)
                costs = ButtonLock.getCurrentLanguage().COSTS_FREE;
              if (group.isUnlocked()) status = ButtonLock.getCurrentLanguage().UNLOCKED;
              if (group.getProtectionMode() == PROTECTION_MODE.PRIVATE)
                protectionMode = ButtonLock.getCurrentLanguage().PRIVATE;
              if (group.getProtectionMode() == PROTECTION_MODE.PUBLIC)
                protectionMode = ButtonLock.getCurrentLanguage().PUBLIC;

              sender.sendMessage(
                  String.format(
                      ButtonLock.getCurrentLanguage().PROTECTION_MODE_IS, protectionMode));
              sender.sendMessage(String.format(ButtonLock.getCurrentLanguage().STATUS, status));
              sender.sendMessage(costs);
              sender.sendMessage(
                  String.format(
                      ButtonLock.getCurrentLanguage().PROTECTION_OWNER_LIST,
                      ButtonLock.getCurrentLanguage().getList(group.getOwnerList())));
              sender.sendMessage(
                  String.format(
                      ButtonLock.getCurrentLanguage().ONE_TIME_PASSWORDS,
                      group.getOneTimePasswords()));
              sender.sendMessage(
                  String.format(
                      ButtonLock.getCurrentLanguage().GROUP_SIZE, "" + group.getGroupSize()));

              for (int blockIndex = 0; blockIndex < group.getGroupSize(); blockIndex++) {
                materials.add(group.getBlock(blockIndex).getType());
              }
            } else if (block != null) {
              Boolean protectable = ButtonLock.isProtectable(block);

              sender.sendMessage(
                  String.format(
                      ButtonLock.getCurrentLanguage().PROTECTABLE,
                      ButtonLock.getCurrentLanguage().getBoolean(protectable)));

              materials.add(block.getType());
            }

            String materialID = String.valueOf(block.getTypeId());
            if (block.getData() > 0) materialID += ":" + Integer.valueOf(block.getData());
            sender.sendMessage(
                String.format(
                    ButtonLock.getCurrentLanguage().MATERIAL,
                    ButtonLock.getCurrentLanguage().getList(materials.toArray()),
                    materialID));

            sender.sendMessage(ButtonLock.getCurrentLanguage().GROUP_INFO_ENDE);
            return true;
          }
        }
      }

      if (args.length >= 2) {

        if (args[0].equalsIgnoreCase("group")
            || args[0].equalsIgnoreCase("g") && permissionButtonlock) {

          PlayerVars currentPlayerVars = ButtonLock.getPlayerVars((Player) sender);

          if (currentPlayerVars != null) {
            LockedBlockGroup group = currentPlayerVars.getCurrentClickedLockedGroup();
            Block block = currentPlayerVars.getCurrentClickedBlock();

            if (group != null) {

              if (!group.hasAccess((Player) sender)) {
                sender.sendMessage(ButtonLock.getCurrentLanguage().DENIED);
                return true;
              }

              if (args.length >= 2) {
                if (args[1].equalsIgnoreCase("costs")
                    || args[1].equalsIgnoreCase("cost")
                    || args[1].equalsIgnoreCase("c")) {
                  if (group.isUnlocked()) {

                    double setting = ButtonLock.getButtonLockConfig().economyCosts;

                    if (args.length == 3) {
                      setting = Double.valueOf(args[2]);
                    }

                    if (setting < 0) setting = 0;

                    group.costs = setting;
                    group.ChangedSetting_costs = true;

                    if (setting == 0) {
                      sender.sendMessage(ButtonLock.getCurrentLanguage().GROUP_COSTS_CHANGED_FREE);
                    } else {
                      sender.sendMessage(
                          String.format(
                              ButtonLock.getCurrentLanguage().GROUP_COSTS_CHANGED_COSTS, setting));
                    }
                  } else {
                    sender.sendMessage(ButtonLock.getCurrentLanguage().DENIED);
                  }
                  currentPlayerVars.getCurrentClickedLockedGroup().setUnlock(false);
                  return true;
                }
              }

              if (args.length == 3) {
                if (args[1].equalsIgnoreCase("setlockedstate")
                    || args[1].equalsIgnoreCase("setls")
                    || args[1].equalsIgnoreCase("sls")) {
                  if (group.isUnlocked()) {

                    LOCKED_STATE setting = null;
                    LOCKED_STATE settingBefore = group.getLockedState();
                    for (LOCKED_STATE state : LOCKED_STATE.values()) {
                      if (state.name().toUpperCase().startsWith(args[2].toUpperCase()))
                        setting = state;
                    }

                    if (setting != null) {
                      if (setting != settingBefore) {

                        if (BlockFunctions.isaDoorAsStateType(block)) {
                          if (setting == LOCKED_STATE.ON) setting = LOCKED_STATE.OPEN;
                          if (setting == LOCKED_STATE.OFF) setting = LOCKED_STATE.CLOSE;
                        }

                        if (BlockFunctions.isaLeverAsStateType(block)) {
                          if (setting == LOCKED_STATE.OPEN) setting = LOCKED_STATE.ON;
                          if (setting == LOCKED_STATE.CLOSE) setting = LOCKED_STATE.OFF;
                        }

                        group.setLockedState(setting);
                        sender.sendMessage(
                            String.format(
                                ButtonLock.getCurrentLanguage().STATE_CHANGED,
                                setting.name().toLowerCase()));
                      }
                    } else {
                      // invalid state ...
                      sender.sendMessage(ButtonLock.getCurrentLanguage().INVALID_STATE);
                    }

                  } else {
                    sender.sendMessage(ButtonLock.getCurrentLanguage().DENIED);
                  }
                  currentPlayerVars.getCurrentClickedLockedGroup().setUnlock(false);
                  return true;
                }

                if (args[1].equalsIgnoreCase("forcePassword")
                    || args[1].equalsIgnoreCase("forcepw")
                    || args[1].equalsIgnoreCase("fpw")) {
                  if (group.isUnlocked()) {
                    boolean setting = Boolean.parseBoolean(args[2]);

                    System.out.println(
                        args[2]
                            + " "
                            + ButtonLock.getCurrentLanguage().TRUE
                            + " "
                            + args[2].equalsIgnoreCase(ButtonLock.getCurrentLanguage().TRUE));
                    if (args[2].equalsIgnoreCase(ButtonLock.getCurrentLanguage().FALSE))
                      setting = false;
                    if (args[2].equalsIgnoreCase(ButtonLock.getCurrentLanguage().TRUE))
                      setting = true;
                    if (args[2].equalsIgnoreCase("0")) setting = false;
                    if (args[2].equalsIgnoreCase("1")) setting = true;

                    boolean settingBefore = group.isForceingEnterPasswordEveryTime();
                    if (setting != settingBefore)
                      group.changedSetting_forceEnterPasswordEveryTime = true;

                    group.setForceEnterPasswordEveryTime(setting);

                    if (setting) {
                      sender.sendMessage(ButtonLock.getCurrentLanguage().GROUP_FORCEPW);
                    } else {
                      sender.sendMessage(ButtonLock.getCurrentLanguage().GROUP_NOT_FORCEPW);
                    }
                  } else {
                    sender.sendMessage(ButtonLock.getCurrentLanguage().DENIED);
                  }
                  currentPlayerVars.getCurrentClickedLockedGroup().setUnlock(false);
                  return true;
                }
              }

              if (args.length >= 4) {
                if (args[1].equalsIgnoreCase("owner") || args[1].equalsIgnoreCase("o")) {

                  if (group.isUnlocked()) {

                    ArrayList<String> addedOrRemovedPlayerNames = new ArrayList<String>();

                    if (args[2].equalsIgnoreCase("add") || args[2].equalsIgnoreCase("a")) {

                      for (int argIndex = 3; argIndex < args.length; argIndex++) {
                        String name = group.addOwner(args[argIndex]);
                        if (!name.isEmpty()) addedOrRemovedPlayerNames.add(name);
                      }

                      if (addedOrRemovedPlayerNames.size() >= 1) {
                        sender.sendMessage(
                            String.format(
                                ButtonLock.getCurrentLanguage().PROTECTION_OWNER_ADDED,
                                ButtonLock.getCurrentLanguage()
                                    .getList(addedOrRemovedPlayerNames.toArray())));
                      } else {
                        sender.sendMessage(ButtonLock.getCurrentLanguage().PLAYER_NOT_FOUND);
                      }

                    } else if (args[2].equalsIgnoreCase("remove")
                        || args[2].equalsIgnoreCase("r")) {

                      for (int argIndex = 3; argIndex < args.length; argIndex++) {
                        String name = group.removeOwner(args[argIndex]);
                        if (!name.isEmpty()) addedOrRemovedPlayerNames.add(name);
                      }

                      if (addedOrRemovedPlayerNames.size() >= 1) {
                        sender.sendMessage(
                            String.format(
                                ButtonLock.getCurrentLanguage().PROTECTION_OWNER_REMOVED,
                                ButtonLock.getCurrentLanguage()
                                    .getList(addedOrRemovedPlayerNames.toArray())));
                      } else {
                        sender.sendMessage(ButtonLock.getCurrentLanguage().PLAYER_NOT_FOUND);
                      }
                    }

                  } else {
                    sender.sendMessage(ButtonLock.getCurrentLanguage().DENIED);
                  }

                  currentPlayerVars.getCurrentClickedLockedGroup().setUnlock(false);
                  return true;
                }
              }

              if (block != null) {
                if (group.isUnlocked()) {
                  if (args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("a")) {
                    currentPlayerVars.groupToAddBlocks = group;
                    sender.sendMessage(ButtonLock.getCurrentLanguage().GROUP_BLOCK_ADD);
                    currentPlayerVars.getCurrentClickedLockedGroup().setUnlock(false);
                    return true;
                  }

                  if (args[1].equalsIgnoreCase("remove") || args[1].equalsIgnoreCase("r")) {
                    currentPlayerVars.groupToRemoveBlocks = group;
                    sender.sendMessage(ButtonLock.getCurrentLanguage().GROUP_BLOCK_REMOVE);
                    currentPlayerVars.getCurrentClickedLockedGroup().setUnlock(false);
                    return true;
                  }
                } else {
                  sender.sendMessage(ButtonLock.getCurrentLanguage().DENIED);
                  currentPlayerVars.getCurrentClickedLockedGroup().setUnlock(false);
                  return true;
                }

              } else {
                sender.sendMessage(ButtonLock.getCurrentLanguage().WHICH_BLOCK);
                currentPlayerVars.getCurrentClickedLockedGroup().setUnlock(false);
                return true;
              }
            } else {
              sender.sendMessage(ButtonLock.getCurrentLanguage().WHICH_BLOCK);
              return true;
            }
          } else {
            sender.sendMessage(ButtonLock.getCurrentLanguage().WHICH_BLOCK);
            return true;
          }
        }
      }
    } else {
      sender.sendMessage(
          String.format(
              ButtonLock.getCurrentLanguage().COMMAND_INGAME_ONLY,
              ButtonLock.getConsoleOutputHeader()));
    }

    return false;
  }
Ejemplo n.º 20
0
 public static boolean hasChunkUnprotect(final CommandSender sender) {
   return sender.isOp() || sender.hasPermission(CMD_CHUNKUNPROTECT) || sender.hasPermission(ADMIN);
 }
Ejemplo n.º 21
0
 public static boolean hasNb(final CommandSender sender) {
   return sender.isOp()
       || sender.hasPermission(CMD_NB)
       || sender.hasPermission(USER)
       || sender.hasPermission(ADMIN);
 }
Ejemplo n.º 22
0
 public static boolean hasRespawn(final CommandSender sender) {
   return sender.isOp() || sender.hasPermission(CMD_RESPAWN) || sender.hasPermission(ADMIN);
 }
Ejemplo n.º 23
0
 public static boolean hasReload(final CommandSender sender) {
   return sender.isOp() || sender.hasPermission(CMD_RELOAD) || sender.hasPermission(ADMIN);
 }
Ejemplo n.º 24
0
  @Override
  public boolean onCommand(
      CommandSender sender, Command command, String commandLabel, String[] args) {
    String commandName = command.getName().toLowerCase();
    try {

      lastCommand =
          (sender instanceof Player ? "player:" : "console:")
              + commandName
              + " "
              + Str.argStr(args);

      // i don't like seeing these messages all the time..
      // Log(((Player) sender).getName() + " used command " + command.getName());

      if (BetterShop.iConomy == null && BetterShop.economy == null) {
        BSutils.sendMessage(
            sender, "\u00A74 BetterShop is missing a dependency. Check the console.");
        Log(Level.SEVERE, "Missing: iConomy or BOSEconomy", false);
        return true;
      }

      if (stock != null && config.useItemStock) {
        stock.checkStockRestock();
      }

      if (commandName.equals("shop")) {
        if (args.length > 0) {
          if (args[0].equalsIgnoreCase("list")) {
            commandName = "shoplist";
          } else if (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("?")) {
            commandName = "shophelp";
          } else if (args[0].equalsIgnoreCase("buy")) {
            commandName = "shopbuy";
          } else if (args[0].equalsIgnoreCase("sell")) {
            commandName = "shopsell";
          } else if (args[0].equalsIgnoreCase("add")) {
            commandName = "shopadd";
          } else if (args[0].equalsIgnoreCase("remove")) {
            commandName = "shopremove";
          } else if (args[0].equalsIgnoreCase("load") || args[0].equalsIgnoreCase("reload")) {
            commandName = "shopload";
          } else if (args[0].equalsIgnoreCase("check")) {
            commandName = "shopcheck";
          } else if (args[0].equalsIgnoreCase("sellall")) {
            commandName = "shopsellall";
          } else if (args[0].equalsIgnoreCase("sellstack")) {
            commandName = "shopsellstack";
          } else if (args[0].equalsIgnoreCase("buystack")) {
            commandName = "shopbuystack";
          } else if (args[0].equalsIgnoreCase("buyall")) {
            commandName = "shopbuyall";
          } else if (args[0].equalsIgnoreCase("sellagain")) {
            commandName = "shopsellagain";
          } else if (args[0].equalsIgnoreCase("buyagain")) {
            commandName = "shopbuyagain";
          } else if (args[0].equalsIgnoreCase("listkits")) {
            commandName = "shoplistkits";
          } else if (args[0].equalsIgnoreCase("restock")) {
            if (BSutils.hasPermission(sender, BSutils.BetterShopPermission.ADMIN_RESTOCK, true)) {
              stock.Restock(true);
              sender.sendMessage("Stock set to initial values");
            }
          } else if (args[0].equalsIgnoreCase("backup")) {
            if (BSutils.hasPermission(sender, BSutils.BetterShopPermission.ADMIN_BACKUP, true)) {
              SimpleDateFormat formatter = new SimpleDateFormat("_yyyy_MM_dd_HH-mm-ss");
              String backFname =
                  BSConfig.pluginFolder.getPath()
                      + File.separatorChar
                      + config.tableName
                      + formatter.format(new java.util.Date())
                      + ".csv";
              try {
                if (pricelist.saveFile(new File(backFname))) {
                  sender.sendMessage("Backup saved as " + backFname);
                }
              } catch (IOException ex) {
                Log(Level.SEVERE, "Failed to save backup file " + backFname, ex);
                sender.sendMessage("\u00A74Failed to save backup file " + backFname);
              }
            }
            return true;
          } else if (args[0].equalsIgnoreCase("import")) {
            return bscommand.importDB(sender, args);
          } else if (args[0].equalsIgnoreCase("restore")) {
            return bscommand.restoreDB(sender, args);
          } else if (args[0].equalsIgnoreCase("update")) {
            if (sender.isOp()) {
              Log("Downloading & Installing Update");
              BSutils.sendMessage(sender, "Downloading & Installing Update");
              ServerReload sreload = new ServerReload(getServer());
              if (Updater.downloadUpdate()) {
                Log("Update Downloaded: Restarting Server..");
                BSutils.sendMessage(sender, "Download Successful.. reloading server");
                // this.setEnabled(false);
                // this.getServer().dispatchCommand((CommandSender) new CommanderSenderImpl(this),
                // "stop");
                // this.getServer().dispatchCommand(new AdminCommandSender(this), "stop");

                // this.getServer().reload();
                sreload.start(500);
              }
            } else {
              BSutils.sendMessage(sender, "Only an OP can update the shop plugin");
            }
            return true;
          } else if (args[0].equalsIgnoreCase("ver") || args[0].equalsIgnoreCase("version")) {
            // allow admin.info or developers access to plugin status (so if i find a bug i can see
            // if it's current)
            if (BSutils.hasPermission(sender, BSutils.BetterShopPermission.ADMIN_INFO, false)
                || (sender instanceof Player
                    && (((Player) sender).getDisplayName().equals("jascotty2")
                        || ((Player) sender).getDisplayName().equals("jjfs85")))) {
              BSutils.sendMessage(sender, "version " + pdfFile.getVersion());
              if (Updater.isUpToDate()) {
                BSutils.sendMessage(sender, "Version is up-to-date");
              } else {
                BSutils.sendMessage(sender, "Newer Version Avaliable");
              }
              return true;
            }
          } else {
            return false;
          }
          // now remove [0]
          if (args.length > 1) {
            String newArgs[] = new String[args.length - 1];
            for (int i = 1; i < args.length; ++i) {
              newArgs[i - 1] = args[i];
            }
            args = newArgs;
          } else {
            args = new String[0];
          }

        } else {
          return false;
        }
      }

      // check if using history
      if (commandName.equals("shopbuyagain") || commandName.equals("shopsellagain")) {
        if (args.length > 0 || BSutils.anonymousCheck(sender)) {
          return false;
        }
        if (commandName.equals("shopbuyagain")) {
          String action = bscommand.userbuyHistory.get(((Player) sender).getDisplayName());
          if (action == null) {
            BSutils.sendMessage(sender, "You have no recent buying history");
            return true;
          } else {
            // trim command & put into args
            String cm[] = action.split(" ");
            commandName = cm[0];
            args = new String[cm.length - 1];
            for (int i = 1; i < cm.length; ++i) {
              args[i - 1] = cm[i];
            }
          }
        } else { // if (commandName.equals("shopsellagain")) {
          String action = bscommand.usersellHistory.get(((Player) sender).getDisplayName());
          if (action == null) {
            BSutils.sendMessage(sender, "You have no recent sell history");
            return true;
          } else {
            // trim command & put into args
            String cm[] = action.split(" ");
            commandName = cm[0];
            args = new String[cm.length - 1];
            for (int i = 1; i < cm.length; ++i) {
              args[i - 1] = cm[i];
            }
          }
        }
        // System.out.println("new command: " + commandName);
        // System.out.println(BSCommand.argStr(args));
      }
      if (!config.useGlobalCommandShop()
          && Str.isIn(
              commandName,
              new String[] {
                "shopbuy", "shopbuyall", "shopbuystack",
                "shopsell", "shopsellall",
                    "shopsellstack", /*"shoplist", "shopitems", "shopcheck", "shoplistkits",
                                     "shopadd", "shopremove"*/
              })) {

        BSutils.sendMessage(sender, "Shop is disabled from here");
        return true;
      }

      if (commandName.equals("shoplist")) {
        return bscommand.list(sender, args);
      } else if (commandName.equals("shopitems")) {
        return bscommand.listitems(sender, args);
      } else if (commandName.equals("shophelp")) {
        return bscommand.help(sender, args);
      } else if (commandName.equals("shopbuy")) {
        return bscommand.buy(sender, args);
      } else if (commandName.equals("shopbuyall")) {
        ArrayList<String> arg = new ArrayList<String>();
        arg.addAll(Arrays.asList(args));
        arg.add("all");
        return bscommand.buy(sender, arg.toArray(new String[0]));
      } else if (commandName.equals("shopbuystack")) {
        return bscommand.buystack(sender, args);
      } else if (commandName.equals("shopsell")) {
        return bscommand.sell(sender, args);
      } else if (commandName.equals("shopsellall")) {
        return bscommand.sellall(sender, args);
      } else if (commandName.equals("shopsellstack")) {
        return bscommand.sellstack(sender, args);
      } else if (commandName.equals("shopadd")) {
        return bscommand.add(sender, args);
      } else if (commandName.equals("shopremove")) {
        return bscommand.remove(sender, args);
      } else if (commandName.equals("shopload")) {
        return bscommand.load(sender);
      } else if (commandName.equals("shopcheck")) {
        return bscommand.check(sender, args);
      } else if (commandName.equals("shoplistkits")) {
        return bscommand.listkits(sender, args);
      }

      return false;
    } catch (Exception e) {
      BSutils.sendMessage(sender, "Unexpected Error!");
      Log(Level.SEVERE, e);
    }
    return true;
  }
 public boolean verify(CommandSender sender) {
   return (sender.isOp() || sender.hasPermission(node));
 }
Ejemplo n.º 26
0
  public boolean onCommand(
      final CommandSender sender, Command command, String label, final String[] args) {
    if (!sender.hasPermission("pregenerator.use") && !sender.isOp()) {
      sender.sendMessage(
          ChatColor.DARK_RED
              + "You don't have permissions to use PreGenerator! (pregenerator.use)");
      return true;
    }
    if (args.length < 5) {
      if (running
          && args.length > 0
          && (args[0].equalsIgnoreCase("stop") || args[0].equalsIgnoreCase("cancel"))) {
        if (thread != null) {
          cancel();
        }

        log(ChatColor.DARK_RED + "Task cancelled succesfull. Progress saved.");
        return true;
      }
      sender.sendMessage(
          ChatColor.DARK_RED
              + "Usage: "
              + ChatColor.RED
              + "/pregenerate <World> <StartX> <StartZ> <EndX> <EndZ>");
      sender.sendMessage(
          ChatColor.DARK_RED + "Usage: " + ChatColor.RED + "/pregenerate stop/cancel");
      return true;
    }
    //
    thread =
        new Thread() {
          public void run() {
            final World world = Bukkit.getWorld(args[0]);
            if (world == null) {
              sender.sendMessage(
                  ChatColor.DARK_RED + "World not found: " + ChatColor.RED + args[0]);
              return;
            }
            Integer startx = null;
            Integer startz = null;
            Integer endx = null;
            Integer endz = null;
            try {
              startx = Integer.valueOf(args[1]);
              startz = Integer.valueOf(args[2]);
              endx = Integer.valueOf(args[3]);
              endz = Integer.valueOf(args[4]);
            } catch (Exception ex) {
              sender.sendMessage(ChatColor.DARK_RED + "Coordinates not correct.");
              return;
            }
            if (startx == null || startz == null || endx == null || endz == null) {
              sender.sendMessage(ChatColor.DARK_RED + "Coordinates not correct.");
              return;
            }
            if (isRunning()) {
              sender.sendMessage(
                  ChatColor.DARK_RED
                      + "PreGenerator is already generating land. Wait for this task before starting a new one.");
              return;
            }
            running = true;
            Long start = System.currentTimeMillis();
            Bukkit.broadcastMessage(
                ChatColor.DARK_PURPLE + "PreGenerator started generating land!");
            sender.sendMessage(ChatColor.DARK_PURPLE + "Check console for details.");
            try {
              world.save();
            } catch (Exception ex) {
            }
            Cuboid region = new Cuboid(plugin, world, startx, 3, startz, endx, 3, endz);
            region.generateChunks();
            Long duration = System.currentTimeMillis() - start;
            Long seconds = duration / 1000;
            Long minutes = seconds / 60;
            Long hours = minutes / 60;
            Bukkit.broadcastMessage(
                ChatColor.DARK_PURPLE
                    + "Generating done! ("
                    + duration
                    + "ms, ="
                    + seconds
                    + "s, ="
                    + minutes
                    + "m, ="
                    + hours
                    + "h.)");
            running = false;
          }
        };
    thread.start();

    //

    return true;
  }
Ejemplo n.º 27
0
  @Override
  public boolean onCommand(CommandSender sender, Command cmd, String cmdLabel, String[] inargs) {

    if (inargs.length == 0 || inargs[0].equalsIgnoreCase("help")) {
      sender.sendMessage(
          ChatColor.GOLD
              + "----- DynMapNPC Help ["
              + ChatColor.GREEN
              + "V"
              + this.getDescription().getVersion()
              + ChatColor.GOLD
              + "]-----");
      if (sender.hasPermission("dynmapnpc.info") || sender.isOp()) {
        sender.sendMessage(
            ChatColor.GOLD + "settings " + ChatColor.RED + "-- Display current defaults");
        sender.sendMessage(
            ChatColor.GOLD
                + "npc      "
                + ChatColor.RED
                + "-- Display settings on the selected NPC");
      }
      if (sender.hasPermission("dynmapnpc.settings") || sender.isOp()) {
        sender.sendMessage(
            ChatColor.GOLD
                + "----- DynMapNPC General Commands ["
                + ChatColor.GREEN
                + "/dmnpc"
                + ChatColor.GOLD
                + "] Help -----");

        sender.sendMessage(
            ChatColor.GOLD + "Toggle " + ChatColor.RED + "   -- Toggle showing NPC's on or off ");
        sender.sendMessage(
            ChatColor.GOLD
                + "reload "
                + ChatColor.RED
                + "   -- Reload the config file (-s saves first)");

        sender.sendMessage(
            ChatColor.GOLD
                + "----- DynMapNPC Config Commands ["
                + ChatColor.GREEN
                + "/dmnpcd"
                + ChatColor.GOLD
                + "] Help -----");

        sender.sendMessage(
            ChatColor.GOLD
                + "icon "
                + ChatColor.GREEN
                + "<IconName>  "
                + ChatColor.RED
                + "-- Icon to display ");
        sender.sendMessage(
            ChatColor.GOLD
                + "minzoom "
                + ChatColor.GREEN
                + "<10-0>   "
                + ChatColor.RED
                + "-- Minimum Zoom to show this NPC");
        sender.sendMessage(
            ChatColor.GOLD
                + "maxzoom "
                + ChatColor.GREEN
                + "<10-0>  "
                + ChatColor.RED
                + "-- Maximum Zoom to show this NPC");
        sender.sendMessage(
            ChatColor.GOLD + "showonmap " + ChatColor.RED + "        -- Toggle NPC's Visiblility");
        sender.sendMessage(
            ChatColor.GOLD
                + "showhcinv "
                + ChatColor.RED
                + "        -- Toggle Hyperconomy shop info");
        sender.sendMessage(
            ChatColor.GOLD
                + "----- DynMapNPC NPC Subcommands ["
                + ChatColor.GREEN
                + "/dmnpcn"
                + ChatColor.GOLD
                + "] Help -----");

        sender.sendMessage(
            ChatColor.GOLD
                + "Use  "
                + ChatColor.GREEN
                + "/trait dynmapnpc "
                + ChatColor.GOLD
                + " to attach this to a citizen");
        sender.sendMessage(
            ChatColor.GOLD
                + "icon "
                + ChatColor.GREEN
                + "<IconName>   "
                + ChatColor.RED
                + " -- Icon to display ");
        sender.sendMessage(
            ChatColor.GOLD
                + "name "
                + ChatColor.GREEN
                + "<NPC Name>   "
                + ChatColor.RED
                + " -- Text displayed on map ");
        sender.sendMessage(
            ChatColor.GOLD
                + "desc"
                + ChatColor.GREEN
                + "<Description> "
                + ChatColor.RED
                + " -- Secondary text to show");
        sender.sendMessage(
            ChatColor.GOLD
                + "minzoom "
                + ChatColor.GREEN
                + "<10-0>    "
                + ChatColor.RED
                + " -- Minimum Zoom to show this NPC");
        sender.sendMessage(
            ChatColor.GOLD
                + "maxzoom "
                + ChatColor.GREEN
                + "<10-0>    "
                + ChatColor.RED
                + " -- Maximum Zoom to show this NPC");
        sender.sendMessage(
            ChatColor.GOLD
                + "showonmap "
                + ChatColor.RED
                + "          -- Toggle NPC's Visiblility");
      }
      return true;
    }

    if (cmd.getName().equalsIgnoreCase("dmnpc")) {
      if (inargs[0].equalsIgnoreCase("toggle")) {
        if (!sender.hasPermission("dynmapnpc.settings") && !sender.isOp()) {
          sender.sendMessage(ChatColor.DARK_RED + "You do not have permission");
          return true;
        } else {
          if (cProcessing_Task == null) {
            // Schedule the main thread to monitor for NPCs
            cProcessing_Task =
                new DynMapNPC_Task(this)
                    .runTaskTimer(
                        this,
                        this.getConfig().getLong("interval", 100L),
                        this.getConfig().getLong("interval", 100L));
            sender.sendMessage(
                ChatColor.GREEN + " NPC Processing has been " + ChatColor.YELLOW + "Started");
          } else {
            cProcessing_Task.cancel();
            cProcessing_Task = null;
            sender.sendMessage(
                ChatColor.GREEN + " NPC Processing has been " + ChatColor.RED + "Stopped");
          }
          return true;
        }
      }
      if (inargs[0].equalsIgnoreCase("reload")) {
        if (!sender.hasPermission("dynmapnpc.settings") && !sender.isOp()) {
          sender.sendMessage(ChatColor.DARK_RED + "You do not have permission");
          return true;
        } else {
          if (inargs.length > 1) {
            if (inargs[1].equalsIgnoreCase("-s")) {
              this.saveConfig();
              sender.sendMessage(ChatColor.GREEN + " Config file  " + ChatColor.YELLOW + "Saved");
            }
          }
          this.reloadConfig();

          sender.sendMessage(ChatColor.GREEN + " Config file  " + ChatColor.YELLOW + "reloaded");
          return true;
        }
      }
    }

    if (cmd.getName().equalsIgnoreCase("dmnpcd")) {
      if (inargs[0].equalsIgnoreCase("settings")) {
        if (!sender.hasPermission("dynmapnpc.info") || !sender.isOp()) {
          sender.sendMessage(ChatColor.DARK_RED + "You do not have permission");
          return true;
        } else {
          sender.sendMessage(ChatColor.GOLD + "----- DynMapNPC Default Settings -----");
          sender.sendMessage(
              ChatColor.GREEN
                  + "MarkersetName:   "
                  + ChatColor.YELLOW
                  + " "
                  + this.getConfig().getString("markerset_name", "DynMapNPCs"));
          sender.sendMessage(
              ChatColor.GREEN
                  + "Update Interval: "
                  + ChatColor.YELLOW
                  + " "
                  + this.getConfig().getString("interval", "100"));
          sender.sendMessage(ChatColor.GOLD + "----- DynMapNPC NPC Default Settings -----");
          sender.sendMessage(
              ChatColor.GREEN
                  + "Icon:      "
                  + ChatColor.YELLOW
                  + " "
                  + this.getConfig().getString("defaults.icon", "offlineuser"));
          sender.sendMessage(
              ChatColor.GREEN
                  + "ShowOnMap: "
                  + ChatColor.YELLOW
                  + " "
                  + this.getConfig().getString("defaults.showonmap", "true"));
          sender.sendMessage(
              ChatColor.GREEN
                  + "Min Zoom:  "
                  + ChatColor.YELLOW
                  + " "
                  + this.getConfig().getString("defaults.zoomlevels.min", "10"));
          sender.sendMessage(
              ChatColor.GREEN
                  + "Max Zoom:  "
                  + ChatColor.YELLOW
                  + " "
                  + this.getConfig().getString("defaults.zoomlevels.max", "1"));
          return true;
        }
      }
      if (inargs[0].equalsIgnoreCase("icon")) {
        if (!sender.hasPermission("dynmapnpc.settings") || !sender.isOp()) {
          sender.sendMessage(ChatColor.DARK_RED + "You do not have permission");
          return true;
        } else {
          if (inargs.length == 2) {
            this.getConfig().set("defaults.icon", inargs[1]);
            sender.sendMessage(
                ChatColor.GREEN + "Default Icon: Set to " + ChatColor.YELLOW + inargs[1]);
          } else {
            sender.sendMessage(
                ChatColor.GREEN
                    + " Icon Name needed "
                    + ChatColor.YELLOW
                    + "Usage: "
                    + ChatColor.RED
                    + "/dnpcd icon <icon name>");
          }
          this.saveConfig();
          return true;
        }
      }
      if (inargs[0].equalsIgnoreCase("minzoom")) {
        if (!sender.hasPermission("dynmapnpc.settings") || !sender.isOp()) {
          sender.sendMessage(ChatColor.DARK_RED + "You do not have permission");
          return true;
        } else {
          if (inargs.length == 2) {
            this.getConfig().set("defaults.zoomlevels.min", Integer.parseInt(inargs[1]));
            sender.sendMessage(
                ChatColor.GREEN + "Default MinZoom: Set to " + ChatColor.YELLOW + inargs[1]);
          } else {
            sender.sendMessage(
                ChatColor.GREEN
                    + "Zoom level needed  "
                    + ChatColor.YELLOW
                    + "Usage: "
                    + ChatColor.RED
                    + "/dnpcd minzoom <0-10>");
          }
          this.saveConfig();
          return true;
        }
      }
      if (inargs[0].equalsIgnoreCase("maxzoom")) {
        if (!sender.hasPermission("dynmapnpc.settings") || !sender.isOp()) {
          sender.sendMessage(ChatColor.DARK_RED + "You do not have permission");
          return true;
        } else {
          if (inargs.length == 2) {
            this.getConfig().set("defaults.zoomlevels.max", Integer.parseInt(inargs[1]));
            sender.sendMessage(
                ChatColor.GREEN + "Default MaxZoom: Set to " + ChatColor.YELLOW + inargs[1]);
          } else {
            sender.sendMessage(
                ChatColor.GREEN
                    + "Zoom level needed  "
                    + ChatColor.YELLOW
                    + "Usage: "
                    + ChatColor.RED
                    + "/dnpcd mxnzoom <0-10>");
          }
          this.saveConfig();
          return true;
        }
      }
      if (inargs[0].equalsIgnoreCase("showonmap")) {
        if (!sender.hasPermission("dynmapnpc.settings") || !sender.isOp()) {
          sender.sendMessage(ChatColor.DARK_RED + "You do not have permission");
          return true;
        } else {
          if (this.getConfig().getBoolean("defaults.showonmap", true)) {
            sender.sendMessage(
                ChatColor.GREEN + "Default Showonmap: Set to " + ChatColor.YELLOW + "false");
            this.getConfig().set("defaults.showonmap", false);
          } else {
            sender.sendMessage(
                ChatColor.GREEN + "Default Showonmap: Set to " + ChatColor.YELLOW + "true");
            this.getConfig().set("defaults.showonmap", true);
          }
          this.saveConfig();
          return true;
        }
      }
      if (inargs[0].equalsIgnoreCase("showhcinv")) {
        if (!sender.hasPermission("dynmapnpc.settings") || !sender.isOp()) {
          sender.sendMessage(ChatColor.DARK_RED + "You do not have permission");
          return true;
        } else {
          if (this.getConfig().getBoolean("defaults.showhcinv", true)) {
            sender.sendMessage(
                ChatColor.GREEN + "Default showhcinv: Set to " + ChatColor.YELLOW + "false");
            this.getConfig().set("defaults.showhcinv", false);
          } else {
            sender.sendMessage(
                ChatColor.GREEN + "Default showhcinv: Set to " + ChatColor.YELLOW + "true");
            this.getConfig().set("defaults.showhcinv", true);
          }
          this.saveConfig();
          return true;
        }
      }
    }
    if (!(sender instanceof Player)) {
      sender.sendMessage(
          "The command you used either does not exist, or is not available from the console.");
      return true;
    }

    Player player = (Player) sender;

    // Citizens default code, left mostly intact

    // This block of code will allow your users to specify
    // The first will run the command on the selected NPC, the second on the NPC with npcID #.
    int npcid = -1;
    int i = 0;
    // did player specify a id?
    try {
      npcid = Integer.parseInt(inargs[0]);
      i = 1;
    } catch (Exception e) {
    }
    String[] args = new String[inargs.length - i];
    for (int j = i; j < inargs.length; j++) {
      args[j - i] = inargs[j];
    }

    // Now lets find the NPC this should run on.
    NPC npc;
    if (npcid == -1) {
      npc =
          ((Citizens) this.getServer().getPluginManager().getPlugin("Citizens"))
              .getNPCSelector()
              .getSelected(sender);
      if (npc != null) {
        // Gets NPC Selected for this sender
        npcid = npc.getId();
      } else {
        // no NPC selected.
        sender.sendMessage(ChatColor.RED + "You must have a NPC selected to use this command");
        return true;
      }
    }

    npc = CitizensAPI.getNPCRegistry().getById(npcid);
    if (npc == null) {
      // specified number doesn't exist.
      sender.sendMessage(ChatColor.RED + "NPC with id " + npcid + " not found");
      return true;
    }

    //	If you need access to the instance of MyTrait on the npc, get it like this
    DynMapNPC_Trait trait = null;
    if (!npc.hasTrait(DynMapNPC_Trait.class)) {
      sender.sendMessage(
          ChatColor.RED + "That command must be performed on a npc with trait: DynMapNPC");
      return true;
    } else trait = npc.getTrait(DynMapNPC_Trait.class);

    if (inargs[0].equalsIgnoreCase("npc")) {
      if (!player.hasPermission("dynmapnpc.info")) {
        player.sendMessage(ChatColor.DARK_RED + "You do not have permission");
        return true;
      } else {
        sender.sendMessage(ChatColor.GOLD + "----- DynMapNPC Settings -----");
        sender.sendMessage(
            ChatColor.GREEN + "Icon:        " + ChatColor.YELLOW + " " + trait.markerIcon);
        sender.sendMessage(
            ChatColor.GREEN + "Name:        " + ChatColor.YELLOW + " " + trait.markerName);
        sender.sendMessage(
            ChatColor.GREEN + "Description: " + ChatColor.YELLOW + " " + trait.markerDescription);
        sender.sendMessage(
            ChatColor.GREEN + "Min Zoom:    " + ChatColor.YELLOW + " " + trait.markerMinZoom);
        sender.sendMessage(
            ChatColor.GREEN + "Max Zoom:    " + ChatColor.YELLOW + " " + trait.markerMaxZoom);
        sender.sendMessage(
            ChatColor.GREEN
                + "Visible:     "
                + ChatColor.YELLOW
                + " "
                + (trait.markerShowOnMap ? "Showing on DynMap" : "Not Shown On Map"));
        ;
        return true;
      }
    }

    if (cmd.getName().equalsIgnoreCase("dmnpcn")) {
      if (inargs[0].equalsIgnoreCase("icon")) {
        if (!player.hasPermission("dynmapnpc.settings")) {
          player.sendMessage(ChatColor.DARK_RED + "You do not have permission");
          return true;
        } else {
          if (inargs.length == 2) {
            for (MarkerIcon oMrkrIcon : this.cDyn_MarkAPI.getMarkerIcons()) {
              if (oMrkrIcon.getMarkerIconID().toString().equalsIgnoreCase(inargs[1])) {
                // Found
                trait.markerIcon = inargs[1];
                player.sendMessage(
                    ChatColor.GREEN + "Icon: Set to " + ChatColor.YELLOW + inargs[1]);
                return true;
              }
            }
            player.sendMessage(
                ChatColor.GREEN
                    + "Icon: Icon does not exist in dynmap "
                    + ChatColor.YELLOW
                    + inargs[1]);
            return true;
          } else {
            player.sendMessage(
                ChatColor.GREEN
                    + "con Name needed "
                    + ChatColor.YELLOW
                    + "Usage: "
                    + ChatColor.RED
                    + "/dnpcn icon <icon name>");
          }
          return true;
        }
      }
      if (inargs[0].equalsIgnoreCase("minzoom")) {
        if (!player.hasPermission("dynmapnpc.settings")) {
          player.sendMessage(ChatColor.DARK_RED + "You do not have permission");
          return true;
        } else {
          if (inargs.length == 2) {
            try {
              trait.markerMinZoom = Integer.parseInt(inargs[1]);
              player.sendMessage(
                  ChatColor.GREEN + "MinZoom: Set to " + ChatColor.YELLOW + inargs[1]);
              return true;
            } catch (Exception err) {
            }
          }
          player.sendMessage(
              ChatColor.GREEN
                  + "Zoom level needed  "
                  + ChatColor.YELLOW
                  + "Usage: "
                  + ChatColor.RED
                  + "/dnpcn minzoom <0-10>");
          return true;
        }
      }
      if (inargs[0].equalsIgnoreCase("maxzoom")) {
        if (!player.hasPermission("dynmapnpc.settings")) {
          player.sendMessage(ChatColor.DARK_RED + "You do not have permission");
          return true;
        } else {
          if (inargs.length == 2) {
            try {
              trait.markerMaxZoom = Integer.parseInt(inargs[1]);
              player.sendMessage(
                  ChatColor.GREEN + "MaxZoom: Set to " + ChatColor.YELLOW + inargs[1]);
              return true;
            } catch (Exception err) {
            }
          }
          player.sendMessage(
              ChatColor.GREEN
                  + "Zoom level needed  "
                  + ChatColor.YELLOW
                  + "Usage: "
                  + ChatColor.RED
                  + "/dnpcn maxzoom <0-10>");
          return true;
        }
      }
      if (inargs[0].equalsIgnoreCase("name")) {
        if (!player.hasPermission("dynmapnpc.settings")) {
          player.sendMessage(ChatColor.DARK_RED + "You do not have permission");
          return true;
        } else {
          if (inargs.length == 2) {
            trait.markerName = inargs[1];
            player.sendMessage(ChatColor.GREEN + "Name: Set to " + ChatColor.YELLOW + inargs[1]);
          } else {
            player.sendMessage(
                ChatColor.GREEN
                    + "Name needed "
                    + ChatColor.YELLOW
                    + "Usage: "
                    + ChatColor.RED
                    + "/dnpcn name <Display Name>");
          }
          return true;
        }
      }
      if (inargs[0].equalsIgnoreCase("desc")) {
        if (!player.hasPermission("dynmapnpc.settings")) {
          player.sendMessage(ChatColor.DARK_RED + "You do not have permission");
          return true;
        } else {
          if (inargs.length == 2) {
            trait.markerDescription = inargs[1];
            player.sendMessage(
                ChatColor.GREEN + "Description: Set to " + ChatColor.YELLOW + inargs[1]);
          } else {
            player.sendMessage(
                ChatColor.GREEN
                    + "Name needed "
                    + ChatColor.YELLOW
                    + "Usage: "
                    + ChatColor.RED
                    + "/dnpcn desc <Description>");
          }
          return true;
        }
      }
      if (inargs[0].equalsIgnoreCase("showonmap")) {
        if (!player.hasPermission("dynmapnpc.settings")) {
          player.sendMessage(ChatColor.DARK_RED + "You do not have permission");
          return true;
        } else {
          if (trait.markerShowOnMap) {
            player.sendMessage(ChatColor.GREEN + "Showonmap: Set to " + ChatColor.YELLOW + "false");
          } else {
            player.sendMessage(ChatColor.GREEN + "Showonmap: Set to " + ChatColor.YELLOW + "true");
          }
          trait.markerShowOnMap = !trait.markerShowOnMap;
          return true;
        }
      }
    }

    player.sendMessage(ChatColor.RED + "invalid command. try help");
    return true; // do this if you didn't handle the command.
  }
  public boolean setUp() {
    try {
      FileUtils.deleteFolder(invDirectory);
      FileUtils.deleteFolder(serverDirectory);
      invDirectory.mkdirs();
      Assert.assertTrue(invDirectory.exists());

      MockGateway.MOCK_STANDARD_METHODS = false;

      plugin = PowerMockito.spy(new MultiverseInventories());
      core = PowerMockito.spy(new MultiverseCore());

      // Let's let all MV files go to bin/test
      doReturn(invDirectory).when(plugin).getDataFolder();
      // Let's let all MV files go to bin/test
      doReturn(coreDirectory).when(core).getDataFolder();

      // Return a fake PDF file.
      PluginDescriptionFile pdf =
          PowerMockito.spy(
              new PluginDescriptionFile(
                  "Multiverse-Inventories",
                  "2.4-test",
                  "com.onarandombox.multiverseinventories.MultiverseInventories"));
      when(pdf.getAuthors()).thenReturn(new ArrayList<String>());
      doReturn(pdf).when(plugin).getDescription();
      doReturn(core).when(plugin).getCore();
      doReturn(true).when(plugin).isEnabled();
      PluginDescriptionFile pdfCore =
          PowerMockito.spy(
              new PluginDescriptionFile(
                  "Multiverse-Core", "2.2-Test", "com.onarandombox.MultiverseCore.MultiverseCore"));
      when(pdfCore.getAuthors()).thenReturn(new ArrayList<String>());
      doReturn(pdfCore).when(core).getDescription();
      doReturn(true).when(core).isEnabled();
      plugin.setServerFolder(serverDirectory);

      // Add Core to the list of loaded plugins
      JavaPlugin[] plugins = new JavaPlugin[] {plugin, core};

      // Mock the Plugin Manager
      PluginManager mockPluginManager = PowerMockito.mock(PluginManager.class);
      when(mockPluginManager.getPlugins()).thenReturn(plugins);
      when(mockPluginManager.getPlugin("Multiverse-Inventories")).thenReturn(plugin);
      when(mockPluginManager.getPlugin("Multiverse-Core")).thenReturn(core);
      when(mockPluginManager.getPermission(anyString())).thenReturn(null);

      // Make some fake folders to fool the fake MV into thinking these worlds exist
      File worldNormalFile = new File(plugin.getServerFolder(), "world");
      Util.log("Creating world-folder: " + worldNormalFile.getAbsolutePath());
      worldNormalFile.mkdirs();
      MockWorldFactory.makeNewMockWorld("world", Environment.NORMAL, WorldType.NORMAL);
      File worldNetherFile = new File(plugin.getServerFolder(), "world_nether");
      Util.log("Creating world-folder: " + worldNetherFile.getAbsolutePath());
      worldNetherFile.mkdirs();
      MockWorldFactory.makeNewMockWorld("world_nether", Environment.NETHER, WorldType.NORMAL);
      File worldSkylandsFile = new File(plugin.getServerFolder(), "world_the_end");
      Util.log("Creating world-folder: " + worldSkylandsFile.getAbsolutePath());
      worldSkylandsFile.mkdirs();
      MockWorldFactory.makeNewMockWorld("world_the_end", Environment.THE_END, WorldType.NORMAL);
      File world2File = new File(plugin.getServerFolder(), "world2");
      Util.log("Creating world-folder: " + world2File.getAbsolutePath());
      world2File.mkdirs();
      MockWorldFactory.makeNewMockWorld("world2", Environment.NORMAL, WorldType.NORMAL);

      // Initialize the Mock server.
      mockServer = mock(Server.class);
      when(mockServer.getName()).thenReturn("TestBukkit");
      Logger.getLogger("Minecraft").setParent(Util.logger);
      when(mockServer.getLogger()).thenReturn(Util.logger);
      when(mockServer.getWorldContainer()).thenReturn(worldsDirectory);
      when(plugin.getServer()).thenReturn(mockServer);
      when(core.getServer()).thenReturn(mockServer);
      when(mockServer.getPluginManager()).thenReturn(mockPluginManager);
      Answer<Player> playerAnswer =
          new Answer<Player>() {
            public Player answer(InvocationOnMock invocation) throws Throwable {
              String arg;
              try {
                arg = (String) invocation.getArguments()[0];
              } catch (Exception e) {
                return null;
              }
              Player player = players.get(arg);
              if (player == null) {
                player = new MockPlayer(arg, mockServer);
                players.put(arg, player);
              }
              return player;
            }
          };
      when(mockServer.getPlayer(anyString())).thenAnswer(playerAnswer);
      when(mockServer.getOfflinePlayer(anyString())).thenAnswer(playerAnswer);
      when(mockServer.getOfflinePlayers())
          .thenAnswer(
              new Answer<OfflinePlayer[]>() {
                public OfflinePlayer[] answer(InvocationOnMock invocation) throws Throwable {
                  return players.values().toArray(new Player[players.values().size()]);
                }
              });
      when(mockServer.getOnlinePlayers())
          .thenAnswer(
              new Answer<Player[]>() {
                public Player[] answer(InvocationOnMock invocation) throws Throwable {
                  return players.values().toArray(new Player[players.values().size()]);
                }
              });

      // Give the server some worlds
      when(mockServer.getWorld(anyString()))
          .thenAnswer(
              new Answer<World>() {
                public World answer(InvocationOnMock invocation) throws Throwable {
                  String arg;
                  try {
                    arg = (String) invocation.getArguments()[0];
                  } catch (Exception e) {
                    return null;
                  }
                  return MockWorldFactory.getWorld(arg);
                }
              });

      when(mockServer.getWorld(any(UUID.class)))
          .thenAnswer(
              new Answer<World>() {
                @Override
                public World answer(InvocationOnMock invocation) throws Throwable {
                  UUID arg;
                  try {
                    arg = (UUID) invocation.getArguments()[0];
                  } catch (Exception e) {
                    return null;
                  }
                  return MockWorldFactory.getWorld(arg);
                }
              });

      when(mockServer.getWorlds())
          .thenAnswer(
              new Answer<List<World>>() {
                public List<World> answer(InvocationOnMock invocation) throws Throwable {
                  return MockWorldFactory.getWorlds();
                }
              });

      when(mockServer.createWorld(Matchers.isA(WorldCreator.class)))
          .thenAnswer(
              new Answer<World>() {
                public World answer(InvocationOnMock invocation) throws Throwable {
                  WorldCreator arg;
                  try {
                    arg = (WorldCreator) invocation.getArguments()[0];
                  } catch (Exception e) {
                    return null;
                  }
                  // Add special case for creating null worlds.
                  // Not sure I like doing it this way, but this is a special case
                  if (arg.name().equalsIgnoreCase("nullworld")) {
                    return MockWorldFactory.makeNewNullMockWorld(
                        arg.name(), arg.environment(), arg.type());
                  }
                  return MockWorldFactory.makeNewMockWorld(
                      arg.name(), arg.environment(), arg.type());
                }
              });

      when(mockServer.unloadWorld(anyString(), anyBoolean())).thenReturn(true);

      // add mock scheduler
      BukkitScheduler mockScheduler = mock(BukkitScheduler.class);
      when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class), anyLong()))
          .thenAnswer(
              new Answer<Integer>() {
                public Integer answer(InvocationOnMock invocation) throws Throwable {
                  Runnable arg;
                  try {
                    arg = (Runnable) invocation.getArguments()[1];
                  } catch (Exception e) {
                    return null;
                  }
                  arg.run();
                  return null;
                }
              });
      when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class)))
          .thenAnswer(
              new Answer<Integer>() {
                public Integer answer(InvocationOnMock invocation) throws Throwable {
                  Runnable arg;
                  try {
                    arg = (Runnable) invocation.getArguments()[1];
                  } catch (Exception e) {
                    return null;
                  }
                  arg.run();
                  return null;
                }
              });
      when(mockServer.getScheduler()).thenReturn(mockScheduler);

      // Set InventoriesListener
      InventoriesListener il = PowerMockito.spy(new InventoriesListener(plugin));
      Field inventoriesListenerField =
          MultiverseInventories.class.getDeclaredField("inventoriesListener");
      inventoriesListenerField.setAccessible(true);
      inventoriesListenerField.set(plugin, il);

      // Set Core
      Field coreField = MultiverseInventories.class.getDeclaredField("core");
      coreField.setAccessible(true);
      coreField.set(plugin, core);

      // Set server
      Field serverfield = JavaPlugin.class.getDeclaredField("server");
      serverfield.setAccessible(true);
      serverfield.set(plugin, mockServer);

      // Set worldManager
      WorldManager wm = PowerMockito.spy(new WorldManager(core));
      Field worldmanagerfield = MultiverseCore.class.getDeclaredField("worldManager");
      worldmanagerfield.setAccessible(true);
      worldmanagerfield.set(core, wm);

      // Set playerListener
      MVPlayerListener pl = PowerMockito.spy(new MVPlayerListener(core));
      Field playerlistenerfield = MultiverseCore.class.getDeclaredField("playerListener");
      playerlistenerfield.setAccessible(true);
      playerlistenerfield.set(core, pl);

      // Set entityListener
      MVEntityListener el = PowerMockito.spy(new MVEntityListener(core));
      Field entitylistenerfield = MultiverseCore.class.getDeclaredField("entityListener");
      entitylistenerfield.setAccessible(true);
      entitylistenerfield.set(core, el);

      // Set weatherListener
      MVWeatherListener wl = PowerMockito.spy(new MVWeatherListener(core));
      Field weatherlistenerfield = MultiverseCore.class.getDeclaredField("weatherListener");
      weatherlistenerfield.setAccessible(true);
      weatherlistenerfield.set(core, wl);

      // Init our command sender
      final Logger commandSenderLogger = Logger.getLogger("CommandSender");
      commandSenderLogger.setParent(Util.logger);
      commandSender = mock(CommandSender.class);
      doAnswer(
              new Answer<Void>() {
                public Void answer(InvocationOnMock invocation) throws Throwable {
                  commandSenderLogger.info(
                      ChatColor.stripColor((String) invocation.getArguments()[0]));
                  return null;
                }
              })
          .when(commandSender)
          .sendMessage(anyString());
      when(commandSender.getServer()).thenReturn(mockServer);
      when(commandSender.getName()).thenReturn("MockCommandSender");
      when(commandSender.isPermissionSet(anyString())).thenReturn(true);
      when(commandSender.isPermissionSet(Matchers.isA(Permission.class))).thenReturn(true);
      when(commandSender.hasPermission(anyString())).thenReturn(true);
      when(commandSender.hasPermission(Matchers.isA(Permission.class))).thenReturn(true);
      when(commandSender.addAttachment(plugin)).thenReturn(null);
      when(commandSender.isOp()).thenReturn(true);

      Bukkit.setServer(mockServer);

      // Load Multiverse Core
      core.onLoad();
      plugin.onLoad();

      // Enable it.
      core.onEnable();
      plugin.onEnable();

      return true;
    } catch (Exception e) {
      e.printStackTrace();
    }

    return false;
  }
Ejemplo n.º 29
0
 public static boolean hasChunkInfo(final CommandSender sender) {
   return sender.isOp()
       || sender.hasPermission(CMD_CHUNKINFO)
       || sender.hasPermission(USER)
       || sender.hasPermission(ADMIN);
 }
Ejemplo n.º 30
0
  public boolean executeCMD(CommandSender sender, String label, String[] args, MCWorld mcworld) {
    if (args.length == 0) {
      if (sender instanceof Player) {
        if (sender.isOp()
            || ((sender.hasPermission("mcw.command.tp")
                    || sender.hasPermission(
                        "mcw.command.tp.world." + PlayerWorld.getWorld(sender).getName()))
                && !sender.hasPermission(
                    "mcw.command.tp.world.!" + PlayerWorld.getWorld(sender)))) {
          try {
            Player player = (Player) sender;
            NewMCWorldListener.ignoreList.add(player);
            if (PlayerWorld.getWorld(sender).getPlayers().contains(sender)) {
              player.teleport(PlayerWorld.getWorld(sender).getSpawnLocation());
            }
            player.teleport(PlayerWorld.getWorld(sender).getSpawnLocation());
            try {
              MCWorldProperties.getPropsFromWorld(PlayerWorld.getWorld(sender))
                  .savePlayerInfoNoLoc(player);
              MCWorldProperties.getPropsFromWorld(player.getWorld()).savePlayerLoc(player);
              player.getInventory().clear();
              MCWorldProperties.getPropsFromWorld(PlayerWorld.getWorld(sender))
                  .getPlayerInfo(player)
                  .teleport();
            } catch (NullPointerException e) {

            }
          } catch (NullPointerException e) {
            sender.sendMessage(ChatColor.RED + "You have not selected a world!");
          }
        } else {
          sender.sendMessage(
              ChatColor.DARK_RED + "You do not have permission to use this command.");
        }

      } else {
        sender.sendMessage("You are not in Minecraft!");
      }
    }
    if (args.length == 1) {
      if (sender instanceof Player) {
        try {
          if (sender.isOp()
              || ((sender.hasPermission("mcw.command.tp")
                      || sender.hasPermission("mcw.command.tp.world." + args[0]))
                  && !sender.hasPermission("mcw.command.tp.world.!" + args[0]))) {
            Player player = (Player) sender;
            NewMCWorldListener.ignoreList.add(player);
            player.teleport(Bukkit.getServer().getWorld(args[0]).getSpawnLocation());
            try {
              MCWorldProperties.getPropsFromString(args[0]).savePlayerInfoNoLoc(player);
              MCWorldProperties.getPropsFromWorld(player.getWorld()).savePlayerLoc(player);
              player.getInventory().clear();
              MCWorldProperties.getPropsFromString(args[0]).getPlayerInfo(player).teleport();
            } catch (NullPointerException e) {

            }
          } else {
            sender.sendMessage(
                ChatColor.DARK_RED + "You do not have permission to use this command.");
          }
        } catch (Exception e) {
          sender.sendMessage(
              ChatColor.DARK_RED + "Error has occured. Please ensure you have the world loaded.");
        }
      } else {
        sender.sendMessage("You are not in Minecraft!");
      }
    }
    if (args.length > 1) {
      if (sender instanceof Player) {
        try {
          Player player = (Player) sender;
          NewMCWorldListener.ignoreList.add(player);
          String worldname = "";
          for (String s : args) {
            if (s != args[args.length - 1]) {
              worldname += (s + " ");
            } else {
              worldname += (s);
            }
          }
          if (sender.isOp()
              || ((sender.hasPermission("mcw.command.tp")
                      || sender.hasPermission(
                          "mcw.command.tp.world." + worldname.replace(' ', '_')))
                  && !sender.hasPermission(
                      "mcw.command.tp.world.!" + worldname.replace(' ', '_')))) {
            player.teleport(Bukkit.getServer().getWorld(worldname).getSpawnLocation());
            try {
              MCWorldProperties.getPropsFromString(worldname).savePlayerInfoNoLoc(player);
              MCWorldProperties.getPropsFromWorld(player.getWorld()).savePlayerLoc(player);
              player.getInventory().clear();
              MCWorldProperties.getPropsFromString(worldname).getPlayerInfo(player).teleport();
            } catch (NullPointerException e) {

            }
          } else {
            sender.sendMessage(
                ChatColor.DARK_RED + "You do not have permission to use this command.");
          }
        } catch (Exception e) {
          sender.sendMessage(
              ChatColor.RED + "Error has occured. Please ensure you have the world loaded.");
        }
      } else {
        sender.sendMessage("You are not in Minecraft!");
      }
    }
    return true;
  }