Example #1
0
  public ThirstSchedule(JavaPlugin plugin) {
    ThirstSchedule.plugin = plugin;

    // Schedule to calculate thirst
    plugin
        .getServer()
        .getScheduler()
        .scheduleSyncRepeatingTask(
            plugin,
            new Runnable() {
              public void run() {
                ThirstSchedule.calculateThirst();
              }
            },
            20L,
            Settings.getConfig().getLong(Thirst.TICKS));

    // Schedule to damage due to thirst
    plugin
        .getServer()
        .getScheduler()
        .scheduleSyncRepeatingTask(
            plugin,
            new Runnable() {
              public void run() {
                ThirstSchedule.calculateThirstDamage();
              }
            },
            20L,
            Settings.getConfig().getLong(Thirst.DAMAGE_TICKS));
  }
  // Checks the item to the list in the config, gets the price, sees if the player has enough money,
  // gives the item to the player.
  private boolean itemChecker(String shop, Player player, ItemStack clickedItem) {

    // Checks to make sure the shop exists.
    Map<String, Object> shopItems;
    if (mobfighter.getConfig().getConfigurationSection("Shops").isConfigurationSection(shop))
      shopItems =
          mobfighter
              .getConfig()
              .getConfigurationSection("Shops")
              .getConfigurationSection(shop)
              .getValues(false);
    else return false;

    double price;

    // Double check that the shop has items then runs the rest.
    if (shopItems != null)
      for (String s : shopItems.keySet())
        if (clickedItem.getType().toString().equalsIgnoreCase(s)) {
          price = Double.parseDouble(shopItems.get(s).toString());
          if (VaultEco.getEconomy().getBalance(player) < price) {
            player.sendMessage(ChatColor.RED + "You do not have enough money!");
            return true;
          }
          VaultEco.getEconomy().withdrawPlayer(player, price);
          ItemStack item = new ItemStack(clickedItem);
          ItemMeta itemMeta = item.getItemMeta();
          itemMeta.setLore(null);
          item.setItemMeta(itemMeta);
          player.getInventory().addItem(item);
          player.updateInventory();
        }

    return true;
  }
Example #3
0
 // --------------------------------------------------------------------------- extractDefaultFile
 public static void extractDefaultFile(JavaPlugin plugin, String filePath) {
   String[] split = filePath.split("/");
   String fileName = split[split.length - 1];
   File actual = new File(filePath);
   if (!actual.exists()) {
     InputStream input = plugin.getClass().getResourceAsStream("/default/" + fileName);
     if (input != null) {
       plugin
           .getServer()
           .getLogger()
           .log(Level.INFO, "Create default file " + fileName + " for " + filePath);
       FileOutputStream output = null;
       try {
         output = new FileOutputStream(actual);
         byte[] buf = new byte[8192];
         int length = 0;
         while ((length = input.read(buf)) > 0) {
           output.write(buf, 0, length);
         }
         plugin.getServer().getLogger().log(Level.INFO, "Default file written " + filePath);
       } catch (Exception e) {
         e.printStackTrace();
       }
       try {
         input.close();
       } catch (Exception e) {
       }
       try {
         output.close();
       } catch (Exception e) {
       }
     }
   }
 }
  /**
   * Get all Command instances, that NCP can get hold of. Attempt to get a SimpleCommandMap instance
   * from the server to get the actually registered commands, but also get commands from JavaPlugin
   * instances.
   *
   * @return
   */
  public static Collection<Command> getCommands() {
    final Collection<Command> commands = new LinkedHashSet<Command>(500);

    // All (?) commands from the SimpleCommandMap of the server, if available.
    final CommandMap commandMap = getCommandMap();
    if (commandMap != null && commandMap instanceof SimpleCommandMap) {
      commands.addAll(((SimpleCommandMap) commandMap).getCommands());
    }
    // TODO: Fall-back for Vanilla / CB commands? [Fall-back should be altering permission defaults,
    // though negating permissions is the right way.]

    // Fall-back: plugin commands.
    for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
      if (plugin instanceof JavaPlugin) {
        final JavaPlugin javaPlugin = (JavaPlugin) plugin;
        final Map<String, Map<String, Object>> map = javaPlugin.getDescription().getCommands();
        if (map != null) {
          for (String label : map.keySet()) {
            Command command = javaPlugin.getCommand(label);
            if (command != null) {
              commands.add(command);
            }
          }
        }
      }
    }

    return commands;
  }
Example #5
0
  @SuppressWarnings("ConstantConditions")
  public static ConfigImpl loadConfig(
      final ConfigFile config,
      final JavaPlugin plugin,
      final ClassLoader classLoader,
      final File dataFolder) {
    // Plugin or classloader must be specified
    Validate.isTrue(plugin != null || classLoader != null, "Plugin or classloader can't be null");

    final ConfigImpl cached;
    if ((cached = ConfigImpl.cache.get(config)) != null) {
      cached.reload(); // Make sure the config is up-to-date
      return cached;
    }

    final File file =
        new File(
            dataFolder != null ? dataFolder : (plugin != null ? plugin.getDataFolder() : null),
            config.getFileName());

    if (!file.exists()) // Copy the config from jar file
    {
      final InputStream inJarFile =
          classLoader != null
              ? classLoader.getResourceAsStream(config.getFileName())
              : plugin.getResource(config.getFileName());

      IOUtils.saveToFile(inJarFile, file);
    }

    final ConfigImpl configuration =
        new ConfigImpl(YamlConfiguration.loadConfiguration(file), file, config);
    ConfigImpl.cache.put(config, configuration);
    return configuration;
  }
  public void enablePlugin(final Plugin plugin) {
    if (!(plugin instanceof JavaPlugin)) {
      throw new IllegalArgumentException("Plugin is not associated with this PluginLoader");
    }

    if (!plugin.isEnabled()) {
      JavaPlugin jPlugin = (JavaPlugin) plugin;

      String pluginName = jPlugin.getDescription().getName();

      if (!loaders.containsKey(pluginName)) {
        loaders.put(pluginName, (PluginClassLoader) jPlugin.getClassLoader());
      }

      try {
        jPlugin.setEnabled(true);
      } catch (Throwable ex) {
        server
            .getLogger()
            .log(
                Level.SEVERE,
                "Error occurred while enabling "
                    + plugin.getDescription().getFullName()
                    + " (Is it up to date?): "
                    + ex.getMessage(),
                ex);
      }

      // Perhaps abort here, rather than continue going, but as it stands,
      // an abort is not possible the way it's currently written
      server.getPluginManager().callEvent(new PluginEnableEvent(plugin));
    }
  }
  public void registerCommands(Class<?> clazz, CommandContainer base) {
    Validate.notNull(clazz);

    Set<CommandContainer> commands =
        CommandContainer.create(clazz, base, instantiator, execution, logger);
    Iterator<CommandContainer> iterator = commands.iterator();

    while (iterator.hasNext()) {
      CommandContainer command = iterator.next();

      if (base == null) {
        if (commandMap.containsKey(command.getName())) {
          logger.warning("duplicate command " + command.getName() + "!");
          continue;
        }

        commandMap.put(command.getName(), command);

        PluginCommand bukkitCommand = plugin.getCommand(command.getName());
        if (bukkitCommand != null) {
          bukkitCommand.setExecutor(this);
        } else {
          logger.warning(
              "Command "
                  + command.getName()
                  + " registered but could not find a matching command for plugin "
                  + plugin.getName()
                  + ". Did you forget to add the command to your plugin.yml?");
        }
      } else {
        // Just add it as a child
        base.addChild(command);
      }
    }
  }
Example #8
0
  /**
   * Called when the sender is invalid for the command
   *
   * @param sender The sender of the command
   */
  public void invalidSender(CommandSender sender) {
    if (sender instanceof Player)
      sender.sendMessage("[" + plugin.getName() + "] You cannot use this command as a player");

    if (sender instanceof ConsoleCommandSender)
      sender.sendMessage("[" + plugin.getName() + "] You cannot use this command from the console");
  }
 // Sets the configuration file's info in regards to the player's max health when they log off.
 @EventHandler(priority = EventPriority.NORMAL)
 public void logOff(PlayerQuitEvent e) {
   Player p = e.getPlayer();
   if (p.getMaxHealth() > 20) {
     mobfighter.getConfig().set("HealthBoost." + p.getDisplayName(), p.getMaxHealth());
     mobfighter.saveConfig();
   }
 }
Example #10
0
  public void setupConfig() throws IOException {
    configFile = new File(plugin.getDataFolder(), fileName);

    if (!configFile.exists()) {
      configFile.createNewFile();
      copy(plugin.getResource(fileName), configFile);
    }
  }
Example #11
0
  /**
   * Constructor for the ConsoleLogger.
   *
   * @param instance - The JavaPlugin instance that initiated this logmanager.
   * @param debug - If set to true, it will output debug info to the console.
   */
  public ConsoleLogger(JavaPlugin instance, String loggerName) {
    plugin = instance;
    this.logger = instance.getLogger();
    this.name = loggerName;

    ConsoleLogger.debug = plugin.getConfig().getBoolean("debug");

    ConsoleLogger.template = "v" + plugin.getDescription().getVersion() + ": ";
  }
Example #12
0
 public synchronized void enable() {
   plugin
       .getServer()
       .getPluginManager()
       .registerEvent(Event.Type.PLAYER_COMMAND, new CommandListener(), Priority.Normal, plugin);
   plugin
       .getServer()
       .getPluginManager()
       .registerEvent(Event.Type.PLAYER_QUIT, new CommandListener(), Priority.Normal, plugin);
 }
Example #13
0
  private String replaceDatabaseString(String input) {
    input =
        input.replaceAll(
            "\\{DIR\\}", javaPlugin.getDataFolder().getPath().replaceAll("\\\\", "/") + "/");
    input =
        input.replaceAll(
            "\\{NAME\\}", javaPlugin.getDescription().getName().replaceAll("[^\\w_-]", ""));

    return input;
  }
Example #14
0
 @SuppressWarnings("deprecation")
 public ConfigFile(JavaPlugin plugin, String fileName) {
   if (plugin == null) throw new IllegalArgumentException("plugin cannot be null");
   if (!plugin.isInitialized()) throw new IllegalArgumentException("plugin must be initialized");
   this.plugin = plugin;
   this.fileName = fileName;
   File dataFolder = plugin.getDataFolder();
   if (dataFolder == null) throw new IllegalStateException();
   this.configFile = new File(plugin.getDataFolder(), fileName);
 }
 public FlatDatabase(
     final Class<S> clazz,
     final String[] defaultColumnNames,
     final JavaPlugin plugin,
     final String path) {
   super(DatabaseType.FLAT, clazz, defaultColumnNames);
   this.plugin = plugin;
   this.filePath = path;
   this.file = new File(plugin.getDataFolder(), filePath);
   this.backupFile = new File(plugin.getDataFolder().getPath(), filePath + "_old");
 }
 public FlatDatabase(
     final Class<S> clazz,
     final String[] defaultColumnNames,
     final String defaultPath,
     final JavaPlugin plugin,
     final ConfigurationSection config) {
   super(DatabaseType.FLAT, clazz, defaultColumnNames);
   this.plugin = plugin;
   this.filePath = config == null ? defaultPath : config.getString("FLAT.filePath", defaultPath);
   this.file = new File(plugin.getDataFolder().getPath(), filePath);
   this.backupFile = new File(plugin.getDataFolder().getPath(), filePath + "_old");
 }
  /** {@inheritDoc} */
  @Override
  public void loadLocale(Locale l) throws NoSuchLocalizationException {
    messages.remove(l);

    InputStream resstream = null;
    InputStream filestream = null;

    try {
      filestream = new FileInputStream(new File(plugin.getDataFolder(), l.getLanguage() + ".yml"));
    } catch (FileNotFoundException e) {
    }

    try {
      resstream =
          plugin.getResource(
              new StringBuilder(LOCALIZATION_FOLDER_NAME)
                  .append("/")
                  .append(l.getLanguage())
                  .append(".yml")
                  .toString());
    } catch (Exception e) {
    }

    if ((resstream == null) && (filestream == null)) throw new NoSuchLocalizationException(l);

    messages.put(l, new HashMap<Message, List<String>>(Message.values().length));

    FileConfiguration resconfig =
        (resstream == null) ? null : YamlConfiguration.loadConfiguration(resstream);
    FileConfiguration fileconfig =
        (filestream == null) ? null : YamlConfiguration.loadConfiguration(filestream);
    for (Message m : Message.values()) {
      List<String> values = m.getDefault();

      if (resconfig != null) {
        if (resconfig.isList(m.toString())) {
          values = resconfig.getStringList(m.toString());
        } else {
          values.add(resconfig.getString(m.toString(), values.get(0)));
        }
      }
      if (fileconfig != null) {
        if (fileconfig.isList(m.toString())) {
          values = fileconfig.getStringList(m.toString());
        } else {
          values.add(fileconfig.getString(m.toString(), values.get(0)));
        }
      }

      messages.get(l).put(m, values);
    }
  }
Example #18
0
 /*
  *  Инициализация файла с сообщениями
  */
 public void InitMsgFile() {
   try {
     lng = new YamlConfiguration();
     File f = new File(plg.getDataFolder() + File.separator + this.language + ".lng");
     if (f.exists()) lng.load(f);
     else {
       InputStream is = plg.getClass().getResourceAsStream("/language/" + this.language + ".lng");
       if (is != null) lng.load(is);
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #19
0
  // Load the conf file and search for configs in the jar memory
  public void ReloadConfig() {
    if (file == null) {
      file = new File(plugin.getDataFolder(), fname);
    }
    conf = YamlConfiguration.loadConfiguration(file);

    // Look for defaults in the jar
    InputStream isDefaults = plugin.getResource(fname);
    if (isDefaults != null) {
      YamlConfiguration confDefault = YamlConfiguration.loadConfiguration(isDefaults);
      conf.setDefaults(confDefault);
    }
  }
Example #20
0
 public void SaveConfig() {
   if (conf == null || file == null) {
     return;
   }
   try {
     conf.save(file); // Save the memory configurations to the config file
   } catch (IOException ex) {
     plugin
         .getLogger()
         .log(Level.SEVERE, "IOException: Error saving configuration file '" + fname + "'!");
     plugin.getLogger().log(Level.SEVERE, ex.toString());
   }
 }
Example #21
0
 private void registerChannels() {
   if (!plugin.getServer().getMessenger().isOutgoingChannelRegistered(plugin, "Iceball")) {
     plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, "Iceball");
   }
   if (!this.plugin
       .getServer()
       .getMessenger()
       .isOutgoingChannelRegistered(this.plugin, "BungeeCord")) {
     this.plugin
         .getServer()
         .getMessenger()
         .registerOutgoingPluginChannel(this.plugin, "BungeeCord");
   }
 }
Example #22
0
  public boolean doExecute(
      JavaPlugin plugin, CommandSender sender, Player player, String command, String[] args)
      throws Throwable {
    boolean retval = true;

    StringBuilder commandLine = new StringBuilder(command);
    for (int i = 0; i < args.length; i++) {
      commandLine.append(" ");
      commandLine.append(args[i]);
    }

    boolean cmdret = false;
    PermissionAttachment attachment = null;
    try {
      PluginCommand cmd = plugin.getServer().getPluginCommand(command);
      attachment =
          player.addAttachment(
              plugin, cmd.getPermission(), true, 20); // we add the permission to the player...
      // we let this expire after 20 ticks (one second) to make sure that he doesn't get it forever
      // by accident
    } catch (Throwable t) {
      // t.printStackTrace(); //No stacktrace since this can happen

      // apparently this failed. last chance: give him all permissions
      attachment = player.addAttachment(plugin, 20);
      for (Permission p : plugin.getServer().getPluginManager().getPermissions()) {
        attachment.setPermission(p, true);
      }
    }

    try {
      cmdret =
          plugin
              .getServer()
              .dispatchCommand(player, commandLine.toString()); // ... execute the command ...
    } catch (Exception e) {
      e.printStackTrace();
      retval = false;
    }

    if (attachment != null) player.removeAttachment(attachment); // ... and remove the permission.

    if (retval) {
      if (cmdret) sender.sendMessage("Done.");
      else sender.sendMessage("Couldn't find the specified command.");
    }

    return retval;
  }
Example #23
0
  public void reloadConfig() {
    if (configFile == null) {
      File dataFolder = plugin.getDataFolder();
      if (dataFolder == null) throw new IllegalStateException();
      configFile = new File(dataFolder, fileName);
    }
    fileConfiguration = YamlConfiguration.loadConfiguration(configFile);

    // Look for defaults in the jar
    InputStream defConfigStream = plugin.getResource(fileName);
    if (defConfigStream != null) {
      YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
      fileConfiguration.setDefaults(defConfig);
    }
  }
Example #24
0
  // First Join Detection
  @EventHandler(priority = EventPriority.LOWEST)
  public void firstJoinDetection(PlayerJoinEvent event) {
    // Define our variables.
    Player player = event.getPlayer();

    // Call the first join event.
    Boolean b = player.hasPlayedBefore();
    if (plugin.getConfig().getBoolean("settings.debug")) {
      b = false;
    }
    if (!b) {
      plugin.getServer().getPluginManager().callEvent(new FirstJoinEvent(event));
      return;
    }
  }
 @Override
 public S loadEntry(final String key) {
   final String rawData = entries.get(key);
   if (rawData == null) return null;
   try {
     return loadEntryWithData(key, rawData.trim());
   } catch (final InvocationTargetException e) {
     plugin.getLogger().log(Level.SEVERE, "Error occured while trying to load entry: " + key);
     try {
       plugin.getLogger().log(Level.SEVERE, "Trying to fix entry...");
       final String backupData = backupEntries.remove(key);
       if (backupData == null)
         try {
           if (e.getCause() instanceof ArrayIndexOutOfBoundsException)
             return loadEntryWithRepairedData(key, rawData.trim());
         } catch (final Exception e1) {
         }
       else
         try {
           return loadEntryWithData(key, backupData);
         } catch (final InvocationTargetException e1) {
           try {
             if (e.getCause() instanceof ArrayIndexOutOfBoundsException)
               return loadEntryWithRepairedData(key, rawData.trim());
           } catch (final InvocationTargetException e2) {
             try {
               if (e.getCause() instanceof ArrayIndexOutOfBoundsException)
                 return loadEntryWithRepairedData(key, backupData);
             } catch (final Exception e3) {
             }
           } catch (final Exception e2) {
           }
         } catch (final Exception e1) {
         }
     } finally {
       if (datas.containsKey(key.toLowerCase())) {
         plugin.getLogger().log(Level.SEVERE, "Repair success.");
         save(key);
       } else plugin.getLogger().log(Level.SEVERE, "Repair failed.");
     }
     shortPrintStackTrace(e, e.getCause());
     return null;
   } catch (final Exception e) {
     System.err.println("Error occured while trying to load entry: " + key);
     e.printStackTrace();
     return null;
   }
 }
  public void reloadDefaultLocalizedStrings() {
    String defaultLanguageFile = "default_lang.yml";
    File defaultLocalizedStringsFile =
        new File(plugin.getDataFolder().getPath() + "/localization/" + defaultLanguageFile);
    CivLog.warning(
        "Configuration file:" + defaultLanguageFile + " in use. Updating to disk from Jar.");
    try {
      CivSettings.streamResourceToDisk("/localization/" + defaultLanguageFile);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    defaultLocalizedStrings = YamlConfiguration.loadConfiguration(defaultLocalizedStringsFile);

    CivLog.info("Loading Configuration file:" + defaultLanguageFile);
    // read the config.yml into memory
    YamlConfiguration cfg = new YamlConfiguration();
    try {
      cfg.load(defaultLocalizedStringsFile);
    } catch (FileNotFoundException e1) {
      e1.printStackTrace();
    } catch (IOException e1) {
      e1.printStackTrace();
    } catch (InvalidConfigurationException e1) {
      e1.printStackTrace();
    }
    defaultLocalizedStrings.setDefaults(cfg);
  }
  public void reloadLocalizedStrings() {
    File localizedStringsFile =
        new File(plugin.getDataFolder().getPath() + "/localization/" + languageFile);
    if (this.isDefault()) {
      if (defaultLocalizedStrings == null) {
        localizedStrings = defaultLocalizedStrings;
      }
      return;
    } else if (!localizedStringsFile.exists()) {

      CivLog.warning(
          "Configuration file:"
              + languageFile
              + " was missing. You must create this file in plugins/Civcraft/localization/");
      CivLog.warning("Using default_lang.yml");
      this.setLanguageFile("");
      return;
    }
    localizedStrings = YamlConfiguration.loadConfiguration(localizedStringsFile);

    CivLog.info("Loading Configuration file:" + languageFile);
    // read the config.yml into memory
    YamlConfiguration cfg = new YamlConfiguration();
    try {
      cfg.load(localizedStringsFile);
    } catch (FileNotFoundException e1) {
      e1.printStackTrace();
    } catch (IOException e1) {
      e1.printStackTrace();
    } catch (InvalidConfigurationException e1) {
      e1.printStackTrace();
    }
    localizedStrings.setDefaults(cfg);
  }
Example #28
0
  private synchronized void broadcastToListeners(String level, String msg) {

    String label = null;

    switch (level) {
      case "info":
        label = ChatColor.GREEN + "INFO";
        break;
      case "warning":
        label = ChatColor.YELLOW + "WARNING";
        break;
      case "severe":
        label = ChatColor.DARK_RED + "SEVERE";
        break;
      case "debug":
        label = ChatColor.BLUE + "DEBUG";
        break;
      default:
        label = "Default label";
    }

    for (String playername : listeners) {
      Player player = plugin.getServer().getPlayer(playername);

      if (player != null) {
        player.sendMessage(label + " [" + this.name + "] - " + ChatColor.WHITE + msg);
      } else {
        listeners.remove(playername);
      }
    }
  }
Example #29
0
  @Override
  public void onEnable() {
    instance = this;

    this.getConfig().options().copyDefaults(true);
    this.saveConfig();

    /* COMMAND */
    this.getCommand("gspos").setExecutor(new PositionCommand());
    this.getCommand("gsitem").setExecutor(new ItemCommand());
    this.getCommand("gspunish").setExecutor(new PunishmentsManager());

    /* LISTENER */
    Bukkit.getPluginManager().registerEvents(new TaserListener(), this);
    Bukkit.getPluginManager().registerEvents(new BombJacketListener(), this);
    Bukkit.getPluginManager().registerEvents(new PositionListener(), this);
    Bukkit.getPluginManager().registerEvents(new GuillotioneListener(), this);
    Bukkit.getPluginManager().registerEvents(new MeteorListener(), this);
    Bukkit.getPluginManager().registerEvents(new RoketListener(), this);
    Bukkit.getPluginManager().registerEvents(new PunishmentsManager(), this);

    System.out.println(" --=<>=---==---===<(O)>===---==---=<>=-- ");
    System.out.println(
        "   "
            + JavaPlugin.getPlugin(this.getClass()).getDescription().getFullName()
            + " plugin loaded...");
    System.out.println("   Made by the PixelCrew Developer's:");
    System.out.println("        http://www.pixelcrew.org");
    System.out.println(" --=<>=---==---===<(O)>===---==---=<>=--");
  }
Example #30
0
  public NPCManager(JavaPlugin plugin) throws IOException {
    mcServer = ((CraftServer) plugin.getServer()).getServer();

    npcNetworkManager = new NPCNetworkManager();
    NPCManager.plugin = plugin;
    taskid =
        Bukkit.getServer()
            .getScheduler()
            .scheduleSyncRepeatingTask(
                plugin,
                new Runnable() {
                  public void run() {
                    HashSet<String> toRemove = new HashSet<String>();
                    for (String i : bankers.keySet()) {
                      Entity j = bankers.get(i).getEntity();
                      j.z();
                      if (j.dead) {
                        toRemove.add(i);
                      }
                    }
                    for (String n : toRemove) {
                      bankers.remove(n);
                    }
                  }
                },
                1L,
                1L);
    Bukkit.getServer().getPluginManager().registerEvents(new SL(), plugin);
    Bukkit.getServer().getPluginManager().registerEvents(new WL(), plugin);
  }