Package com.kellerkindt.scs

Source Code of com.kellerkindt.scs.ShowCaseStandalone$ShowCaseStandalonePluginListener

/**
* ShowCaseStandalone
* Copyright (C) 2012 Kellerkindt <copyright at kellerkindt.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package com.kellerkindt.scs;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;

import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;

import com.avaje.ebean.config.ServerConfig;
import com.earth2me.essentials.Essentials;
import com.kellerkindt.scs.balance.BOSEconomyBalance;
import com.kellerkindt.scs.balance.DummyBalance;
import com.kellerkindt.scs.balance.EssentialsBalance;
import com.kellerkindt.scs.balance.VaultBalance;
import com.kellerkindt.scs.balance.iConomy5Balance;
import com.kellerkindt.scs.balance.iConomy6Balance;
import com.kellerkindt.scs.balance.iConomy8Balance;
import com.kellerkindt.scs.events.ShowCaseEvent;
import com.kellerkindt.scs.interfaces.Balance;
import com.kellerkindt.scs.interfaces.ShopHandler;
import com.kellerkindt.scs.interfaces.StorageHandler;
import com.kellerkindt.scs.internals.MetricsHandler;
import com.kellerkindt.scs.internals.SimpleShopHandler;
import com.kellerkindt.scs.internals.Todo;
import com.kellerkindt.scs.listeners.BlockListener;
import com.kellerkindt.scs.listeners.CommandExecutorListener;
import com.kellerkindt.scs.listeners.DropChestListener;
import com.kellerkindt.scs.listeners.DropChestListenerV2;
import com.kellerkindt.scs.listeners.EntityListener;
import com.kellerkindt.scs.listeners.ILogTransactionListener;
import com.kellerkindt.scs.listeners.InventoryListener;
import com.kellerkindt.scs.listeners.PlayerListener;
import com.kellerkindt.scs.listeners.ShowCaseExecutingListener;
import com.kellerkindt.scs.listeners.ShowCaseVerifyingListener;
import com.kellerkindt.scs.listeners.SignListener;
import com.kellerkindt.scs.listeners.TownyListener;
import com.kellerkindt.scs.listeners.WorldGuardListener;
import com.kellerkindt.scs.listeners.WorldListener;
import com.kellerkindt.scs.shops.BuyShop;
import com.kellerkindt.scs.shops.DisplayShop;
import com.kellerkindt.scs.shops.ExchangeShop;
import com.kellerkindt.scs.shops.SellShop;
import com.kellerkindt.scs.shops.Shop;
import com.kellerkindt.scs.storage.SQLShopStorage;
import com.kellerkindt.scs.storage.YamlStorage;
import com.kellerkindt.scs.utilities.Messaging;
import com.kellerkindt.scs.utilities.Metrics;
import com.kellerkindt.scs.utilities.PlayerSessionVariables;
import com.kellerkindt.scs.utilities.Properties;
import com.kellerkindt.scs.utilities.Properties.EconomySystem;
import com.kellerkindt.scs.utilities.SCSLogger;
import com.kellerkindt.scs.utilities.Term;
import com.kellerkindt.scs.utilities.TermLoader;
import com.kellerkindt.scs.utilities.Utilities;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;

import cosine.boseconomy.BOSEconomy;


//TODO: Dropchest listener not working with DC fork in 1.1
//Amounts on sell are wrong (default items
public class ShowCaseStandalone extends JavaPlugin {
 
  public static final String ALIAS_SHOP_BUY    = "scs.buy";
  public static final String ALIAS_SHOP_SELL    = "scs.sell";
  public static final String ALIAS_SHOP_DISPLAY  = "scs.display";
  public static final String ALIAS_SHOP_EXCHANGE  = "scs.exchange";
 
  static {
    // register for deserialization
    ConfigurationSerialization.registerClass(BuyShop.class,     ALIAS_SHOP_BUY);
    ConfigurationSerialization.registerClass(SellShop.class,     ALIAS_SHOP_SELL);
    ConfigurationSerialization.registerClass(DisplayShop.class,   ALIAS_SHOP_DISPLAY);
    ConfigurationSerialization.registerClass(ExchangeShop.class,   ALIAS_SHOP_EXCHANGE);
  }
 
  private static Date            startup      = null;
  private static HashMap<Date, String>  warnings    = new HashMap<Date, String>();
 
  private Permission        permission     = null;
  private Balance        balance      = null;
  private ShopHandler      shopHandler    = null;
  private StorageHandler    shopStorage    = null;
 
  private MetricsHandler    metricsHandler  = null;
  private Metrics        metrics      = null;
 
  private static ShowCaseStandalone   scs;
  private static final   Logger     logr     = Logger.getLogger("Minecraft");
  public static       SCSLogger   logDebug   = null;
  private static       SCSLogger   logTrans   = null;
 
  private Map<Class<? extends Shop>, String>  createPerms = new HashMap<Class<? extends Shop>, String>();
  private Map<Class<? extends Shop>, Double>  createCosts  = new HashMap<Class<? extends Shop>, Double>();
  private Map<String, Integer>        sneakAmount  = new HashMap<String, Integer>();
 
  // manuel hook and un-hook
//  private TownyListener        townyListener;
 
  public static final PlayerSessionVariables pv = new PlayerSessionVariables();
 
  private Map<Player, Todo>  todos  = new HashMap<Player, Todo>();

  @Override
  public void onLoad() {
    getDataFolder().mkdirs();
  }
 
  @Override
  public void onDisable() {
    try {
      log(Level.INFO, "Stopping shop update task.", true);
      shopHandler.stop();
     
      log(Level.INFO, "Saving any remaining shop changes.", true);
      shopStorage.save(shopHandler);
      shopStorage.flush();
     
      log(Level.INFO, "Removing display items.", true);
      shopHandler.hideAll();
     
    } catch (Exception ioe) {
      this.log(Level.WARNING, "Exception on onDisable: " + ioe, false);
    }
  }

  @Override
  public void onEnable() {
    logr.log(Level.INFO, "[SCS] Starting build "+Properties.buildNumber +", made on "+Properties.buildDate +" by "+Properties.buildAuthor +" with help by "+Properties.buildContributor);
   
    // setup startup
    startup    = new Date();
    warnings  = new HashMap<Date, String>();
   
   
    // Register our commands
    ShowCaseStandalone.scs   = this;
    getCommand("scs").setExecutor(new CommandExecutorListener(this));
   
    //Load our configuration
    log(Level.INFO, "Loading configuration.", true);
    loadSCSConfig(this.getConfig());
    this.saveDefaultConfig();   
   
   
    //Initialize the customer loggers
    if(Properties.logTransactions)
      logTrans = new SCSLogger("ShowCaseStandlone", getDataFolder() + File.separator + "transactions.log");
   
    if(Properties.threadDebug || Properties.chunkDebug || Properties.interactDebug || Properties.saveDebug)
      logDebug = new SCSLogger("ShowCaseStandalone", getDataFolder() + File.separator + "debug.log");
   
    // ShopHandler, ShopStorage
    log(Level.INFO, "Initializing ShopHandler and ShopStorage", true);
    log(Level.INFO, "Using " + Properties.storageType + " as storage type.", true);
    log(Level.INFO, "getDatafolder: " + getDataFolder(), true);
   
    try {
      log(Level.INFO, "Loading shops", true);
     
      // TODO check again
//      // bukkits configuration file
//      if ("sql_bukkit".equalsIgnoreCase(Properties.storageType)) {
//        shopStorage  = getSQLShopStorageBukkit();
//      }
//     
//      // my configuration file
//      else if ("sql_scs".equalsIgnoreCase(Properties.storageType)) {
//        shopStorage  = getSQLShopStorageThis();
//       
//      // default: ffss
//      } else {
//        shopStorage  = new FastFileShopStorage(this);
//      }
     
     
      shopHandler  = new SimpleShopHandler (this);
      shopStorage  = new YamlStorage(this, new File(getDataFolder(), "yaml-storage"));
     
      shopStorage.load(shopHandler);
     
      log(Level.INFO, "Shops loaded: " + shopHandler.size(), true);
    } catch (Exception e) {
      log(Level.WARNING, "Exception while loading shops: " + e, false);
      e.printStackTrace();
    }
   
   
    // Initialize localization
    log(Level.INFO, "Loaded localization: " + Properties.localizationFileName, true);
    try {
      TermLoader.loadTerms(new File(getDataFolder(), Properties.localizationFileName));
    } catch (IOException ioe){
      log(Level.WARNING, "IOError: could not find/connect to localization file.", false);
      ioe.printStackTrace();
      log(Level.WARNING, "Disabling SCS.", false);
      getPluginLoader().disablePlugin(this);
    }
   
    // Searching for other plugins
    log(Level.INFO, "Searching for other Plugins...", true);
   
    // try to manually hook into plugins
    for (Plugin p : this.getServer().getPluginManager().getPlugins())
      hookInto(p);
   
    // Not found any economy system?
    if (this.balance == null) {
      log(Level.WARNING, "No economy system found, using dummy economy system!", false);
      log(Level.WARNING, "Please get a plugin, either iMonies, EssentialsEco, iConomy, or BOSEconomy!", false);
      this.balance = new DummyBalance(this);
    }
   
    //Instantiate and Register the listeners.  Do this last to avoid NPEs for chunk load events.
    log(Level.INFO, "Register event listeners.", true);
    registerEvents(new PlayerListener  (this));
    registerEvents(new BlockListener   (this));
    registerEvents(new WorldListener   (this));
    registerEvents(new InventoryListener(this));
    registerEvents(new EntityListener  (this));
   
    registerEvents(new ShowCaseStandalonePluginListener(this));
   
    // main listener
    registerEvents(new ShowCaseExecutingListener(this));
    registerEvents(new ShowCaseVerifyingListener(this));
   
    // set the prices
    setCreatePrice(SellShop    .class, Properties.sellShopCreatePrice);
    setCreatePrice(BuyShop    .class, Properties.buyShopCreatePrice);
    setCreatePrice(DisplayShop  .class,  Properties.displayCreatePrice);
    setCreatePrice(ExchangeShop  .class,  Properties.exchangeCreatePrice);
   
    // set the permissions
    setCreatePermission(SellShop  .class, Properties.permCreateSell);
    setCreatePermission(BuyShop    .class, Properties.permCreateBuy);
    setCreatePermission(DisplayShop  .class, Properties.permCreateDisplay);
    setCreatePermission(ExchangeShop.class, Properties.permCreateExchange);
   
   
    // init listeners
    if (Properties.useSigns) {
      registerEvents(new SignListener(this));
    }
   
    // iLogTransaction listener
    if (Bukkit.getPluginManager().getPlugin("iLogTransactions") != null) {
      registerEvents(new ILogTransactionListener(this));
    }
   
    try {
      log(Level.INFO, "Initilazing Metrics", true);
      // init metrics
      this.metrics    = new Metrics(this);
     
      // does the server owner want to use this?
      if (!metrics.isOptOut()) {
       
        // init handler
        this.metricsHandler  = new MetricsHandler(shopHandler, metrics);
       
        // add listener
        registerEvents(metricsHandler);
       
        // start metrics
        this.metrics.start();
       
        log(Level.INFO, "Metrics successfully initialized", true);
      } else {
        log(Level.INFO, "Metrics is deactivated, ShowCaseStandalone respects your decision and won't use Metrics", true);
      }
   
    } catch (IOException ioe) {
      log(Level.WARNING, "Couldn't initialize Metrics", false);
    }
   
   
//    // for debuging only
//    UUID uuid = UUID.fromString("c38df931-b545-462c-84e2-45b85c1a81ca");
//   
//    if (shopHandler.size() == 0) {
//      World  world  = getServer().getWorlds().get(0);
//      BuyShop shop  = new BuyShop(uuid, "kellerkindt", new Location(world, 1, 2, 3), new ItemStack(Material.FIREWORK));
//     
//      shop.setAmount(123);
//     
//      shopHandler.addShop(shop);
//     
//    } else {
//      Shop shop = shopHandler.getShop(uuid);
//      shop.setAmount(shop.getAmount() * 2);
//    }
   
   

    // Warning if this is a dev-build
    if (Properties.buildIsDev)
      Messaging.send(getServer().getConsoleSender(), Term.WARNING_DEV_VERSION.get());
  }
 
  /**
   * Registers the given Listener
   * @param listener  Listener to register
   */
  private void registerEvents(Listener listener) {
    getServer().getPluginManager().registerEvents(listener, this);
    log(Level.INFO, "Registered "+listener.getClass().getSimpleName(), true);
  }
 
  /**
   * @param shopClass  Class to bind the permission to
   * @param perm    Permission needed to create a shop of the given class
   */
  public void setCreatePermission (Class<? extends Shop> shopClass, String perm) {
    createPerms.put(shopClass, perm);
  }
 
  /**
   * @param shopClass The class to check the permissions for
   * @return The needed permission to create a shop of the given class or the admin permission
   */
  public String getCreatePermission (Class<? extends Shop> shopClass) {
   
    // get the permission
    String perm = createPerms.get(shopClass);
   
    // check whether the permission is valid
    if (perm == null) {
      // unknown, so only the admin is allowed to
      return Properties.permAdmin;
     
    } else {
      return perm;
    }
  }
 
 
  /**
   * @param shopClass  Class to set the price for
   * @param price    Price to set for the given class
   */
  public void setCreatePrice (Class<? extends Shop> shopClass, double price) {
    createCosts.put(shopClass, price);
  }
 
  /**
   * @param shopClass Class to get the price for
   * @return The price to create a Shop of the given Class
   */
  public double getCreatePrice (Class<? extends Shop> shopClass) {
    // get the cost
    Double cost = createCosts.get(shopClass);
   
    if (cost == null) {
      log(Level.WARNING, "Price for unknown class requested: "+shopClass, true);
      return 0;
     
    } else {
      return cost;
    }
  }
 
 
 
  /**
   * Creates a new SQLShoStorage instance with bukkits configuration file
   * @return
   * @throws SQLException
   * @Deprecated SQLStorage cannot save at the moment
   */
  public SQLShopStorage getSQLShopStorageBukkit () throws SQLException {
    ServerConfig  serverConfig  = new ServerConfig();
    scs.getServer().configureDbConfig(serverConfig);
   
    String   url      = serverConfig.getDataSourceConfig().getUrl();
    String  username  = serverConfig.getDataSourceConfig().getUsername();
    String  password  = serverConfig.getDataSourceConfig().getPassword();
    return new SQLShopStorage    (this, url, username, password);
  }
 
  /**
   * Creates a new SQLShoStorage instance with this configuration file
   * @return
   * @throws SQLException
   * @throws ClassNotFoundException
   * @Deprecated SQLStorage cannot save at the moment
   */
  public SQLShopStorage getSQLShopStorageThis () throws SQLException, ClassNotFoundException {
    String   url      = Properties.sqlURL;
    String  username  = Properties.sqlUserame;
    String  password  = Properties.sqlPass;
   
    // load class
    Class.forName(Properties.sqlDriver);
   
    return new SQLShopStorage    (this, url, username, password);
  }
 
  /**
   * @param player  Player to get the amount for
   * @return The amount while this player is sneaking
   */
  public int getSneakAmount (Player player) {
    Integer amount = sneakAmount.get(player.getName());
   
    if (amount == null) {
      return 64// TODO
    } else {
      return amount;
    }
  }
 
  /**
   * Sets the amount a player wants to interact
   * while he is sneaking
   * @param player  Player to set for
   * @param amount  Amount to set
   */
  public void setSneakAmount (Player player, int amount) {
    sneakAmount.put(player.getName(), amount);
  }
 
  /**
   * Logging for this module only.
   * @param l Log Level
   * @param message
   * @param debug Whether to log the message only if debuging is enabled
   */
  public void log (Level l, String message, boolean debug) {
    // log only for debug reasons?
    if(debug && Properties.startupDebugging) {
      ShowCaseStandalone.slog(l, message);
     
    } else {
      // just log it
      ShowCaseStandalone.slog(l, message);
    }
  }
 
  /**
   * Static logger for the minecraft.log
   * @param l Log Level
   * @param message
   */
  public static void slog(Level l, String message) {
    if(Properties.showExtraMessages)
      ShowCaseStandalone.get().getLogger().log(l, message);
    else
      ShowCaseStandalone.logr.log(l, "[SCS] " + message);
   
    // warning log
    if (Level.WARNING == l || Level.SEVERE == l) {
      warnings.put(new Date(), message);
    }
  }
 
 
  /**
     * Calls the given ShowCaseEvent
     * @param event Event to call
     * @return Whether the event was cancelled
     */
    public boolean callShowCaseEvent (ShowCaseEvent event) {
      getServer().getPluginManager().callEvent(event);
      return event.isCancelled();
  }
   
   
  /**
   * @return The time this plugin was enabled
   */
  public static Date getStartup () {
    return startup;
  }
 
  /**
   * @return The date of the last warnings since startup
   */
  public static HashMap<Date, String> getWarnings () {
    return warnings;
  }
 
  /**
   * @return The amount of warnings since this plugin was enabled
   */
  public static int getTotalWarnings () {
    return warnings.size();
  }
 
  /**
   * Thread Debug logger.  Logs to debug.log when activated.
   * @param l Log level
   * @param message
   */
  public static void dlog(String message){
    if(logDebug != null)
      logDebug.log(Level.INFO, message);
  }
 
  /**
   * Transaction logger.  Logs to transaction.log when activated.
   * If mysql is active, we should be sending this to that module for
   * storage in the transaction table.
   * @param customer
   * @param owner
   * @param action
   * @param quantity
   * @param price
   * @param item
   * @param sha1
   * @param inventory
   */
  public static void tlog(String customer, String owner, String action,
      int quantity, double price, String item, UUID uuid, int inventory){
    if(Properties.logTransactions){
      StringBuilder msg = new StringBuilder();
      msg.append("Transaction: ");
      msg.append("c:").append(customer).append(", o:").append(owner);
      msg.append(", a:").append(action);
      msg.append(", q:").append(quantity);
      msg.append(", i:").append(item);
      msg.append(", pr:").append(price);
      msg.append(", shp:").append(uuid.toString());
      msg.append(", inv:").append(inventory);
     
      if(logTrans != null)
        logTrans.log(Level.INFO, msg.toString());
    }
  }
 
  /*
   * Makes the current instance for all accessible
   */
  public static ShowCaseStandalone get () {
    return ShowCaseStandalone.scs;
  }
 
  /**
   * Adds the given player and tood
   * @param player  Player that caused the todo
   * @param todo    Todo the player requested
   */
  public void addTodo (Player player, Todo todo) {
    todos.put(player, todo);
  }
 
 
  /**
   * Removes the todo for the given player
   * @param player  Player to remove the todo for
   * @return The removed todo
   */
  public Todo removeTodo (Player player) {
    return todos.remove(player);
  }
 
  /**
   * @param player  Player to get the todo for
   * @return The todo for the given Player
   */
  public Todo getTodo (Player player) {
    return todos.get(player);
  }
 
  /**
   * @param player Player to check
   * @return Whether the given player is a SCS-Admin
   */
  public boolean isAdmin (Player player) {
    return player.isOp() || hasPermission(player, Properties.permAdmin);
  }
 
  /**
   * @param player  Player to check
   * @param per    Additional permission to check, if the player is not an admin
   * @return Whether the given player is an admin or has the given permission
   */
  public boolean isAdminOrHasPermission (Player player, String per) {
    return hasOnePermission(player, Properties.permAdmin, per);
  }
 
  /**
   * @param player Player to check
   * @return Whether the given player can use a shop
   */
  public boolean canUse (Player player) {
    return hasOnePermission(player, Properties.permAdmin, Properties.permUse);
  }
 
  /**
   * Checks whether the given player can manage
   * the given shop
   * @param player    Player to check
   * @param shop      Shop to manage
   * @param checkOwner  Whether the given player has to be the owner, if false, it can also be a member
   * @return whether the given player can manage the given shop
   */
  public boolean canManage (Player player, Shop shop, boolean checkOwner) {
    return hasPermission(player, Properties.permAdmin)
        || ((!checkOwner || shop.isOwner(player.getName()))
            && (checkOwner || shop.isOwnerOrMember(player.getName()))
            && hasPermission(player, Properties.permManage));
  }
 
  /**
   * @param cs  CommandSender to check
   * @param pers  Requested permissions
   * @return Whether the given CommandSender has one of the requested permissions
   */
  public boolean hasOnePermission (CommandSender cs, String ... pers) {
    for (String per : pers) {
      if (hasPermission(cs, per)) {
        return true;
      }
    }
   
    return false;
  }
 
  /**
   * @param cs  CommandSender to check
   * @param pers  Requested permissions
   * @return Whether the given CommandSender has all of the requested permissions
   */
  public boolean hasAllPermissions (CommandSender cs, String ... pers) {
    for (String per : pers) {
      if (!hasPermission(cs, per)) {
        return false;
      }
    }
   
    return true;
  }
 
 
  /**
   * Checks whether the given CommandSenderhas the requested
   * permission, console will always have all permissions
   * @param cs      CommandSender to check
   * @param permission  Requested permission
   * @return Whether the given CommandSender has the requested permission
   */
  public boolean hasPermission (CommandSender cs, String permission) {
    if (cs instanceof Player) {
      return hasPermission((Player)cs, permission);
    } else {
      return (cs instanceof ConsoleCommandSender);
    }
  }
 
  /*
   * Checks if the given player has the given permission
   * First uses Permissions plugin if available, if not
   * it uses bukkit-permission
   */
  /**
   * @param player  Player to check
   * @param perm    Requested permission
   * @return Whether the given Player has the given permission or not
   */
  public boolean hasPermission (Player player, String perm) {
   
    boolean hasPer   = false;
   
    if (permission != null) {
      // ask the permission plugin
      hasPer = permission.has(player, perm);
     
    } else {
      // ask bukkit
      hasPer = player.hasPermission(perm);
    }
   
    // only log on debug
    if (Properties.permDebug) {
      if (hasPer) {
        log(Level.FINEST, String.format("%s [DisplayName=%s] was granted the permission '%s'", player.getName(), player.getDisplayName(), perm), true);
      } else {
        log(Level.INFO, String.format("%s [DisplayName=%s] was denied the permission '%s'", player.getName(), player.getDisplayName(), perm), true);
      }
    }
   
    return hasPer;
  }
 
  /*
   * Returns the BalanceHandler
   */
  public Balance getBalanceHandler () {
    return this.balance;
  }
 
  public void setBalanceHandler (Balance bh) {
    this.balance = bh;
  }
 
  /**
   * @return The current ShopHandler
   */
  public ShopHandler getShopHandler () {
    return this.shopHandler;
  }
 
  /**
   * @return The current StorageHandler
   */
  public StorageHandler getStorageHandler(){
    return this.shopStorage;
  }
     
  /*
   * Returns formatted money amounts.
   */
  public String formatCurrency(double amount){
    return balance.format(amount);
  }
 
  /**
   * Checks if the economy system is allowed
   * @param   className  ClassName of the economy system
   * @return  true if it is allowed, false if it isn't allowed
   */
  public boolean isAllowedEconomySystem (String className) {
    String names[]  = Properties.economySystem.classNames;
    for (String s : names)
      if (s.equals(className))
        return true;
    return false;
  }
 
  /*
   * Configuration file loader
   */
  public void loadSCSConfig(FileConfiguration config){
    config.options().copyDefaults(true);
    Properties.showExtraMessages      = config.getBoolean("Debug.ShowExtraMessages", false);
   
    Properties.defaultUnit         = config.getInt      ("DefaultUnit");
    Properties.maxUndoTime         = config.getInt      ("UndoTime") * 1000;
    Properties.buyShopCreatePrice     = config.getDouble    ("CreatePrice.BuyShop");
    Properties.sellShopCreatePrice     = config.getDouble    ("CreatePrice.SellShop");
    Properties.displayCreatePrice     = config.getDouble    ("CreatePrice.Display");
    Properties.exchangeCreatePrice    = config.getDouble    ("CreatePrice.Exchange");
   
    Properties.storageType         = config.getString    ("Database.Type"); //we'll catch potential errors later.
    Properties.blackList         = config.getBoolean    ("BlockList.Blacklist");
    Properties.blockList         = convertListStringToMaterial(config.getStringList("BlockList.Blocks"));
    Properties.buyBlackList       = config.getBoolean    ("BuyItemList.Blacklist");
    Properties.buyList          = convertListStringToMaterial(config.getStringList("BuyItemList.Items"));
    Properties.sellBlackList      = config.getBoolean    ("SellItemList.Blacklist");
    Properties.sellList         = convertListStringToMaterial(config.getStringList("SellItemList.Items"));
   
    Properties.sqlDriver        = config.getString    ("Database.driver");
    Properties.sqlURL          = config.getString    ("Database.url");
    Properties.sqlUserame          = config.getString    ("Database.username");
    Properties.sqlPass          = config.getString    ("Database.password");
   
    Properties.blacklistedWorlds     = config.getStringList  ("WorldBlacklist");
    Properties.cancelExplosion       = config.getBoolean    ("CancelExplosion");
    Properties.logTransactions       = config.getBoolean    ("LogTransactions");
    Properties.hideInactiveShops     = config.getBoolean    ("HideInactiveShops");
    Properties.maxAmountOnCreative    = config.getBoolean    ("MaxAmountOnCreative", true);
   
    Properties.startupDebugging      = config.getBoolean    ("StartupDebugging", false);
   
    Properties.threadDebug         = config.getBoolean    ("Debug.Thread",     false);
    Properties.permDebug        = config.getBoolean    ("Debug.Permissions",   false);
    Properties.interactDebug      = config.getBoolean    ("Debug.Interact",     false);
    Properties.chunkDebug         = config.getBoolean    ("Debug.Chunk",     false);
    Properties.saveDebug        = config.getBoolean    ("Debug.Save",       false);
   
    Properties.towny_needsResident    = config.getBoolean    ("Towny.needsResident",   true);
    Properties.towny_needsToBeOwner    = config.getBoolean    ("Towny.needsToBeOwner",   false);
    Properties.towny_allowInWilderness  = config.getBoolean    ("Towny.allowInWilderness", false);
   
    Properties.requireObjectToDisplay   = config.getBoolean    ("RequireObjectToDisplay");
    Properties.allowUnsafeEnchantments  = config.getBoolean   ("AllowUnsafeEnchantments");
    Properties.economySystem      = convertToEconomySystem( config.getString("EconomySystem") );
   
    Properties.intervall        = config.getLong    ("Save.Interval");

    Properties.stackToMaxAmount      = config.getBoolean    ("Display.StackToMaxAmount", false);
    Properties.useSigns          = config.getBoolean    ("Display.UseSigns", true);
    Properties.DISPLAY_USE_STORAGE    = config.getBoolean     ("Display.UseStorage", true);
   
    Properties.maxShopAmountPerPlayer  = config.getInt      ("Limitation.MaxAmount");
   
    Properties.localizationFileName   = config.getString    ("Localization.File", "locale_EN");
    //Check for extension.  If not found, then add .yml
    if(!Properties.localizationFileName.contains("."))
      Properties.localizationFileName += ".yml";
   
    //now check locale version.  If different from the one we hardcode in Properties, then overwrite default locale file.
    //this indicates that we've added or modified the default locale file(s).
   
    log(Level.INFO, "locale vs. config: " + Properties.localeVersion + " v " + config.getDouble("Localization.Version"), true);
   
    if(Properties.localeVersion != config.getDouble("Localization.Version")){
      log(Level.INFO, "Locale file has changed.  Overwriting default locale files with new versions.", false);
      log(Level.INFO, "If you are using a custom locale file, please update with any changes you need.", false);
      for(String defaultName : Properties.defaultLocaleFiles){
        this.saveResource(defaultName, true);
      }
      config.set("Localization.Version", Properties.localeVersion);
    }
  }
 
 
  /**
   * Converts the given String to a EconomySystem variable
   * By default, it returns EconomySystem.AUTO
   * @param   value  Name of the economy system
   * @return  The EconomySystem for the value or EconomySystem.AUTO
   */
  private EconomySystem convertToEconomySystem (String value) {
    EconomySystem system = EconomySystem.AUTO;
   
    for (EconomySystem es : EconomySystem.values())
      if (es.toString().equalsIgnoreCase(value))
        system = es;
    return system;
  }
 
 
  /*
   * Converts a list of Strings to a list of materials.
   */
  private List<MaterialData> convertListStringToMaterial(List<String> list){
    List<MaterialData> result = new ArrayList<MaterialData>();
    MaterialData m = null;
   
    for(String mat : list){
      try{
        m = Utilities.getMaterialsFromString(mat);
        result.add(m);
      } catch (IOException ioe){}
    }
    return result;
  }
 
  public static void spam(String m){
    Bukkit.getServer().broadcastMessage(m);
  }
 
  /**
   * Sends to all of the registered player
   * the given message
   * @param shop  Shop to get the players from
   * @param msg  Message to send
   */
  public void msgAll (Shop shop, String msg) {
    msgOwner(shop, msg);
   
    for (String member : shop.getMembers()) {
      msgPlayer(getServer().getPlayerExact(member), msg);
    }
  }
 
  /**
   * Sends the owner of this shop the given Message
   * @param shop  Shop to get the owner of
   * @param msg  Message to send
   */
  public void msgOwner (Shop shop, String msg) {
    msgPlayer(getServer().getPlayerExact(shop.getOwner()), msg);
  }
 
 
  /**
   * Sends the given Player the given message
   * @param player  Player to send the message to
   * @param msg    Message to send
   */
  public void msgPlayer (Player player, String msg) {
    if (player != null) {
      Messaging.send(player, msg);
    }
  }
 
  /**
   * @param stack ItemStack to check
   * @return Whether the material of the given ItemStack needs to check the ItemMeta
   */
  public boolean compareItemMeta (ItemStack stack) {
    switch (stack.getType())  {
      case WRITTEN_BOOK:
      case BOOK:
        return false;
       
      default:
        return true;
    }
  }
 
 
  /**
   * Tires to hook into the given Plugin
   * @param plugin
   */
  public void hookInto (Plugin plugin) {
    String className  = plugin.getClass().getName();
   
    // WorldGuard
    if (className.equals("com.sk89q.worldguard.bukkit.WorldGuardPlugin")) {
      registerEvents(new WorldGuardListener(this, (WorldGuardPlugin)plugin));
      log(Level.INFO, "Hooked into WorldGuard", true);
    }
   
    // Essentials Economy
    if (className.equals("com.earth2me.essentials.Essentials") && isAllowedEconomySystem(className)) {
      log(Level.INFO, "Hooked into EssentialsEconomy", true);
      this.balance  = new EssentialsBalance(this, (Essentials)plugin);
    }
   
    // iConomy 5
    if (className.equals("com.iConomy.iConomy") && isAllowedEconomySystem(className)) {
      log(Level.INFO, "Hooked into iConomy5", true);
      this.balance = new iConomy5Balance (this, (com.iConomy.iConomy)plugin);
    }
   
    // iConomy 6
    if (className.equals("com.iCo6.iConomy") && isAllowedEconomySystem(className)) {
      log(Level.INFO, "Hooked into iConomy6", true);
      this.balance = new iConomy6Balance (this, (com.iCo6.iConomy)plugin);
    }
   
    // iConomy
    if (className.equals("com.iCo8.iConomy") && isAllowedEconomySystem(className)) {
      log(Level.INFO, "Hooked into iConomy8", true);
      this.balance = new iConomy8Balance (this, (com.iCo8.iConomy)plugin);
    }
   
    // BOSEconomy
    if (className.equals("cosine.boseconomy.BOSEconomy") && isAllowedEconomySystem(className)) {
      log(Level.INFO, "Hooked into BOSEconomy", true);
      this.balance = new BOSEconomyBalance (this, (BOSEconomy)plugin);
    }
    // Towny
    if (className.equals("com.palmergames.bukkit.towny.Towny")) {
      log(Level.INFO, "Hooked into Towny", true);
      registerEvents(new TownyListener());
    }
   
    // Vault
    if (className.equals("net.milkbowl.vault.Vault") && isAllowedEconomySystem(className)) {
      RegisteredServiceProvider<Economy> economyProvider = scs.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
      if (economyProvider != null) {
          log(Level.INFO, "Hooked into " + economyProvider.getPlugin().getName(), true);
          balance = new VaultBalance(economyProvider.getProvider());
      }
      RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
      if (permissionProvider != null) {
          log(Level.INFO, "Hooked into Vault Permissions", true);
          permission = permissionProvider.getProvider();
      }
    }
   
    //Attach to DropChest API, if loaded
    if (className.equals("com.narrowtux.dropchest.dropchest")){
      log(Level.INFO, "Found Old DropChest.  Attempting to hook api.", true);

      try {
        registerEvents(new DropChestListener(this));
        log(Level.INFO, "Hooked OLD DropChest listener.", true);
      } catch (Exception e) {}
    }
   
    //This supports a fork that was done to upgrade DC to 1.1.
    if (className.equals("com.noheroes.dropchest.dropchest")){
      log(Level.INFO, "Found New DropChest.  Attempting to hook api.", true);
      try{
        registerEvents(new DropChestListenerV2(this));
        log(Level.INFO, "Hooked NEW DropChest listener.", true);
      } catch (Exception e){}
    }
  }
 
  /**
   * Tires to unhook from the given plugin
   * @param plugin
   */
  public void unHookPlugin (Plugin plugin) {
    String className  = plugin.getClass().getName();
   
    if (className.equals("com.iConomy.iConomy")) {
      log(Level.INFO, "Un-hooked iConomy", true);
      this.balance = new DummyBalance(this);
    }
   
    if (className.equals("com.iCo6.iConomy")) {
      log(Level.INFO, "Un-hooked iConomy", true);
      this.balance = new DummyBalance(this);
    }
   
    if (className.equals("com.iCo8.iConomy")) {
      log(Level.INFO, "Un-hooked iConomy", true);
      this.balance = new DummyBalance(this);
    }
   
    if (this.permission != null) {
      if (!this.permission.isEnabled()) {
        log(Level.INFO, "Un-hooked Permissions", true);
        this.permission = null;
      }
    }

    if (className.equals("cosine.boseconomy.BOSEconomy")) {
      log(Level.INFO, "Un-hooked BOSEconomy", true);
      this.balance = new DummyBalance(this);
    }
   
    // Towny
    if (className.equals("com.palmergames.bukkit.towny.Towny")) {
      log(Level.INFO, "Un-hooked Towny", true);
      // TODO why !?
//      this.getServer().getPluginManager().registerEvents(townyListener, this);
    }
  }
 
  /* Allows late binding.
   * Class used to hook in Plugins like:
   * - iConomy
   * - BOSEconomy
   * - Permission
   */
  private class ShowCaseStandalonePluginListener implements Listener {
   
//    private ShowCaseStandalone scs;

    public ShowCaseStandalonePluginListener(ShowCaseStandalone plugin) {
//      this.scs = plugin;
    }

    @EventHandler(priority = EventPriority.MONITOR)
    public void onPluginEnable(PluginEnableEvent event) {
      // Try to hook into the plugin
      hookInto(event.getPlugin());
    }
   
    /*
     * Listen for Permissions, iConomy and BOSEconomy
     */
    //This is causing all sorts of erros in the new system.  Disable change to dummy class.
    @EventHandler(priority = EventPriority.MONITOR)
    public void onPluginDisable(PluginDisableEvent event) {
      // Try to hook into the plugin
      unHookPlugin(event.getPlugin());
    }
  }
}
TOP

Related Classes of com.kellerkindt.scs.ShowCaseStandalone$ShowCaseStandalonePluginListener

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.