undefined config error

Discussion in 'Plugin Development' started by Azolex, Mar 8, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    Azolex

    I'm pretty new to a plugin scene and I bumped on error right now which i cannot solve for couple of days already. I'm pretty sure it's easy one to solve for any of plugin developer, any help is highly appriceated.
    Code:
    package rc.vanilla;
    
    import java.util.ArrayList;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    
    public class CommandActivator
      implements CommandExecutor
    {
      private Snowball plugin;
      
      public CommandActivator(Snowball plugin)
      {
        this.plugin = plugin;
      }
      
      public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args)
      {
        Player player = (Player)sender;
        if (cmd.getName().equalsIgnoreCase("ESB"))
        {
          if (args.length == 0)
          {
            if ((sender instanceof Player))
            {
              if (player.hasPermission("esb.use"))
              {
                if (this.plugin.players.contains(player.getName()))
                {
                  this.plugin.players.remove(player.getName());
                  player.sendMessage(ChatColor.GRAY + "[" + 
                    ChatColor.DARK_PURPLE + "ESB" + 
                    ChatColor.GRAY + "] " + ChatColor.GREEN + 
                    "Explosive Snow Ball has been disabled!");
                  return true;
                }
                this.plugin.players.add(player.getName());
                player.sendMessage(ChatColor.GRAY + 
                  "[" + 
                  ChatColor.DARK_PURPLE + 
                  "ESB" + 
                  ChatColor.GRAY + 
                  "] " + 
                  ChatColor.RED + 
                  "Explosive Snow Ball has been enabled! Be Careful!");
                return true;
              }
              player.sendMessage(ChatColor.GRAY + "[" + 
                ChatColor.DARK_PURPLE + "ESB" + 
                ChatColor.GRAY + "] " + ChatColor.DARK_RED + 
                "You do not have permission.");
              return true;
            }
            player.sendMessage(ChatColor.GRAY + "[" + 
              ChatColor.DARK_PURPLE + "ESB" + ChatColor.GRAY + 
              "] " + ChatColor.DARK_RED + 
              "Sorry, this command can only be used in-game.");
            return true;
          }
          if (args.length == 1)
          {
            if ((args[0].equalsIgnoreCase("stat")) || 
              (args[0].equalsIgnoreCase("status")))
            {
              if (player.hasPermission("ebs.stats"))
              {
                if (this.plugin.players.contains(player.getName()))
                {
                  player.sendMessage(ChatColor.GRAY + "[" + 
                    ChatColor.DARK_PURPLE + "ESB" + 
                    ChatColor.GRAY + "] " + ChatColor.BLUE + 
                    "Explosive Snowball is activiated!");
                  return true;
                }
                player.sendMessage(ChatColor.GRAY + 
                  "[" + 
                  ChatColor.DARK_PURPLE + 
                  "ESB" + 
                  ChatColor.GRAY + 
                  "] " + 
                  ChatColor.BLUE + 
                  "Explosive Snowball is not activiated! Type /esb to turn it on.");
                return true;
              }
              player.sendMessage(ChatColor.GRAY + "[" + 
                ChatColor.DARK_PURPLE + "ESB" + 
                ChatColor.GRAY + "] " + ChatColor.DARK_RED + 
                "You do not have permission.");
              return true;
            }
            if ((args[0].equalsIgnoreCase("?")) || 
                    (args[0].equalsIgnoreCase("help")))
                  {
                    player.sendMessage(ChatColor.BLACK + "" + ChatColor.STRIKETHROUGH + "===============" + 
                      ChatColor.AQUA + ChatColor.BOLD + 
                      " Explosive SnowBall " + ChatColor.BLACK + 
                      ChatColor.STRIKETHROUGH + "===============");
                    player.sendMessage(ChatColor.LIGHT_PURPLE + "Info:");
                    player.sendMessage(ChatColor.YELLOW + 
                      "SimpleExplosiveSnowBall Plugin (V 1.1.0) is made by ddarkpolice from the Karbon Group.");
                    player.sendMessage(ChatColor.YELLOW + 
                      "Website: www.teamkarbon.com");
                    player.sendMessage(ChatColor.YELLOW + 
                      "Bukkit Dev Link: www.dev.bukkit.org/bukkit-plugins/esb/");
                    player.sendMessage(ChatColor.LIGHT_PURPLE + "Commands:");
                    player.sendMessage(ChatColor.GRAY + "1)" + ChatColor.GREEN + 
                      "/esb" + ChatColor.WHITE + 
                      " - Toggle the Explosive Snowball On and Off");
                    player.sendMessage(ChatColor.GRAY + "2)" + ChatColor.GREEN + 
                      "/esb ? | /esb help" + ChatColor.WHITE + 
                      " - This menu would appear");
                    player.sendMessage(ChatColor.GRAY + 
                      "3)" + 
                      ChatColor.GREEN + 
                      "/esb stat | /esb status" + 
                      ChatColor.WHITE + 
                      " - Check if Explosive Snowball is Toggled  On or Off");
                    return true;
            }
            if (args[0].equalsIgnoreCase("reload"))
            {
              if (player.hasPermission("ebs.reload"))
              {
                this.plugin.reloadConfig();
                sender.sendMessage(ChatColor.GRAY + "[" + 
                  ChatColor.DARK_PURPLE + "ESB" + 
                  ChatColor.GRAY + "] " + ChatColor.BLUE + "Configuration has been reloaded!");
                return true;
              }
              player.sendMessage(ChatColor.GRAY + "[" + 
                ChatColor.DARK_PURPLE + "ESB" + 
                ChatColor.GRAY + "] " + ChatColor.DARK_RED + 
                "You do not have permission.");
              return true;
            }
          }
        }
        return false;
      }
    }
    
    
    
    Code:
    package rc.vanilla;
    
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.PrintStream;
    import java.io.UnsupportedEncodingException;
    import java.net.Proxy;
    import java.net.URL;
    import java.net.URLConnection;
    import java.net.URLEncoder;
    import java.util.UUID;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import java.util.zip.GZIPOutputStream;
    import org.bukkit.Bukkit;
    import org.bukkit.Server;
    import org.bukkit.configuration.InvalidConfigurationException;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.configuration.file.YamlConfigurationOptions;
    import org.bukkit.plugin.Plugin;
    import org.bukkit.plugin.PluginDescriptionFile;
    import org.bukkit.scheduler.BukkitScheduler;
    import org.bukkit.scheduler.BukkitTask;
    
    public class MetricsLite
    {
      private static final int REVISION = 7;
      private static final String BASE_URL = "http://report.mcstats.org";
      private static final String REPORT_URL = "/plugin/%s";
      private static final int PING_INTERVAL = 15;
      private final Plugin plugin;
      private final YamlConfiguration configuration;
      private final File configurationFile;
      private final String guid;
      private final boolean debug;
      private final Object optOutLock = new Object();
      private volatile BukkitTask task = null;
      
      public MetricsLite(Plugin plugin)
        throws IOException
      {
        if (plugin == null) {
          throw new IllegalArgumentException("Plugin cannot be null");
        }
        this.plugin = plugin;
        
    
        this.configurationFile = getConfigFile();
        this.configuration = YamlConfiguration.loadConfiguration(this.configurationFile);
        
    
        this.configuration.addDefault("opt-out", Boolean.valueOf(false));
        this.configuration.addDefault("guid", UUID.randomUUID().toString());
        this.configuration.addDefault("debug", Boolean.valueOf(false));
        if (this.configuration.get("guid", null) == null)
        {
          this.configuration.options().header("http://mcstats.org").copyDefaults(true);
          this.configuration.save(this.configurationFile);
        }
        this.guid = this.configuration.getString("guid");
        this.debug = this.configuration.getBoolean("debug", false);
      }
      
      public boolean start()
      {
        synchronized (this.optOutLock)
        {
          if (isOptOut()) {
            return false;
          }
          if (this.task != null) {
            return true;
          }
          this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable()
          {
            private boolean firstPost = true;
            
            public void run()
            {
              try
              {
                synchronized (MetricsLite.this.optOutLock)
                {
                  if ((MetricsLite.this.isOptOut()) && (MetricsLite.this.task != null))
                  {
                    MetricsLite.this.task.cancel();
                    MetricsLite.this.task = null;
                  }
                }
                MetricsLite.this.postPlugin(!this.firstPost);
                
    
    
                this.firstPost = false;
              }
              catch (IOException e)
              {
                if (MetricsLite.this.debug) {
                  Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
                }
              }
            }
          }, 0L, 18000L);
          
          return true;
        }
      }
      
      public boolean isOptOut()
      {
        synchronized (this.optOutLock)
        {
          try
          {
            this.configuration.load(getConfigFile());
          }
          catch (IOException ex)
          {
            if (this.debug) {
              Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
            }
            return true;
          }
          catch (InvalidConfigurationException ex)
          {
            if (this.debug) {
              Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
            }
            return true;
          }
          return this.configuration.getBoolean("opt-out", false);
        }
      }
      
      public void enable()
        throws IOException
      {
        synchronized (this.optOutLock)
        {
          if (isOptOut())
          {
            this.configuration.set("opt-out", Boolean.valueOf(false));
            this.configuration.save(this.configurationFile);
          }
          if (this.task == null) {
            start();
          }
        }
      }
      
      public void disable()
        throws IOException
      {
        synchronized (this.optOutLock)
        {
          if (!isOptOut())
          {
            this.configuration.set("opt-out", Boolean.valueOf(true));
            this.configuration.save(this.configurationFile);
          }
          if (this.task != null)
          {
            this.task.cancel();
            this.task = null;
          }
        }
      }
      
      public File getConfigFile()
      {
        File pluginsFolder = this.plugin.getDataFolder().getParentFile();
        
    
        return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
      }
      
      private void postPlugin(boolean isPing)
        throws IOException
      {
        PluginDescriptionFile description = this.plugin.getDescription();
        String pluginName = description.getName();
        boolean onlineMode = Bukkit.getServer().getOnlineMode();
        String pluginVersion = description.getVersion();
        String serverVersion = Bukkit.getVersion();
        int playersOnline = Bukkit.getServer().getOnlinePlayers().length;
        
    
    
    
        StringBuilder json = new StringBuilder(1024);
        json.append('{');
        
    
        appendJSONPair(json, "guid", this.guid);
        appendJSONPair(json, "plugin_version", pluginVersion);
        appendJSONPair(json, "server_version", serverVersion);
        appendJSONPair(json, "players_online", Integer.toString(playersOnline));
        
    
        String osname = System.getProperty("os.name");
        String osarch = System.getProperty("os.arch");
        String osversion = System.getProperty("os.version");
        String java_version = System.getProperty("java.version");
        int coreCount = Runtime.getRuntime().availableProcessors();
        if (osarch.equals("amd64")) {
          osarch = "x86_64";
        }
        appendJSONPair(json, "osname", osname);
        appendJSONPair(json, "osarch", osarch);
        appendJSONPair(json, "osversion", osversion);
        appendJSONPair(json, "cores", Integer.toString(coreCount));
        appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0");
        appendJSONPair(json, "java_version", java_version);
        if (isPing) {
          appendJSONPair(json, "ping", "1");
        }
        json.append('}');
        
    
        URL url = new URL("http://report.mcstats.org" + String.format("/plugin/%s", new Object[] { urlEncode(pluginName) }));
        URLConnection connection;
      //  URLConnection connection;
        if (isMineshafterPresent()) {
          connection = url.openConnection(Proxy.NO_PROXY);
        } else {
          connection = url.openConnection();
        }
        byte[] uncompressed = json.toString().getBytes();
        byte[] compressed = gzip(json.toString());
        
    
        connection.addRequestProperty("User-Agent", "MCStats/7");
        connection.addRequestProperty("Content-Type", "application/json");
        connection.addRequestProperty("Content-Encoding", "gzip");
        connection.addRequestProperty("Content-Length", Integer.toString(compressed.length));
        connection.addRequestProperty("Accept", "application/json");
        connection.addRequestProperty("Connection", "close");
        
        connection.setDoOutput(true);
        if (this.debug) {
          System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
        }
        OutputStream os = connection.getOutputStream();
        os.write(compressed);
        os.flush();
        
    
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String response = reader.readLine();
        
    
        os.close();
        reader.close();
        if ((response == null) || (response.startsWith("ERR")) || (response.startsWith("7")))
        {
          if (response == null) {
            response = "null";
          } else if (response.startsWith("7")) {
            response = response.substring(response.startsWith("7,") ? 2 : 1);
          }
          throw new IOException(response);
        }
      }
      
      public static byte[] gzip(String input)
      {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gzos = null;
        try
        {
          gzos = new GZIPOutputStream(baos);
          gzos.write(input.getBytes("UTF-8"));
        }
        catch (IOException e)
        {
          e.printStackTrace();
          if (gzos != null) {
            try
            {
              gzos.close();
            }
            catch (IOException localIOException1) {}
          }
        }
        finally
        {
          if (gzos != null) {
            try
            {
              gzos.close();
            }
            catch (IOException localIOException2) {}
          }
        }
        return baos.toByteArray();
      }
      
      private boolean isMineshafterPresent()
      {
        try
        {
          Class.forName("mineshafter.MineServer");
          return true;
        }
        catch (Exception e) {}
        return false;
      }
      
      private static void appendJSONPair(StringBuilder json, String key, String value)
        throws UnsupportedEncodingException
      {
        boolean isValueNumeric = false;
        try
        {
          if ((value.equals("0")) || (!value.endsWith("0")))
          {
            Double.parseDouble(value);
            isValueNumeric = true;
          }
        }
        catch (NumberFormatException e)
        {
          isValueNumeric = false;
        }
        if (json.charAt(json.length() - 1) != '{') {
          json.append(',');
        }
        json.append(escapeJSON(key));
        json.append(':');
        if (isValueNumeric) {
          json.append(value);
        } else {
          json.append(escapeJSON(value));
        }
      }
      
      private static String escapeJSON(String text)
      {
        StringBuilder builder = new StringBuilder();
        
        builder.append('"');
        for (int index = 0; index < text.length(); index++)
        {
          char chr = text.charAt(index);
          switch (chr)
          {
          case '"': 
          case '\\': 
            builder.append('\\');
            builder.append(chr);
            break;
          case '\b': 
            builder.append("\\b");
            break;
          case '\t': 
            builder.append("\\t");
            break;
          case '\n': 
            builder.append("\\n");
            break;
          case '\r': 
            builder.append("\\r");
            break;
          default: 
            if (chr < ' ')
            {
              String t = "000" + Integer.toHexString(chr);
              builder.append("\\u" + t.substring(t.length() - 4));
            }
            else
            {
              builder.append(chr);
            }
            break;
          }
        }
        builder.append('"');
        
        return builder.toString();
      }
      
      private static String urlEncode(String text)
        throws UnsupportedEncodingException
      {
        return URLEncoder.encode(text, "UTF-8");
      }
    }
    
    
    Code:
    package rc.vanilla;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.logging.Logger;
    import org.bukkit.ChatColor;
    import org.bukkit.Server;
    import org.bukkit.command.PluginCommand;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.FileConfigurationOptions;
    import org.bukkit.plugin.PluginManager;
    import org.bukkit.plugin.java.JavaPlugin;
    
    public class Snowball
      extends JavaPlugin
    {
      ArrayList<String> players = new ArrayList(0);
      
      public void onEnable()
      {
        getCommand("ESB").setExecutor(new CommandActivator(this));
        
        File file = new File(getDataFolder() + File.separator + "config.yml");
        if (!file.exists())
        {
          getLogger().info("Config not found, generating....");
          getConfig().options().copyDefaults(true);
          saveConfig();
        }
        PluginManager manager = getServer().getPluginManager();
        manager.registerEvents(new ValuesListener((org.bukkit.entity.Snowball) this), this);
        try
        {
          MetricsLite metrics = new MetricsLite(this);
          metrics.start();
        }
        catch (IOException localIOException) {}
        getLogger().info("SimpleExplosiveSnowBall Plugin" + ChatColor.GREEN + "Enabled");
      }
      
      public void onDisable()
      {
        saveConfig();
        getLogger().info(
          "SimpleExplosiveSnowBall Plugin has been safely" + ChatColor.DARK_RED + 
          "Disabled");
      }
    }
    
    
    Code:
    package rc.vanilla;
    
    import java.util.ArrayList;
    import org.bukkit.Location;
    import org.bukkit.World;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.entity.Entity;
    import org.bukkit.entity.Player;
    import org.bukkit.entity.Snowball;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.entity.ProjectileHitEvent;
    import org.bukkit.configuration.file.FileConfigurationOptions;
    
    public class ValuesListener
      implements Listener
    {
      private Snowball plugin;
      
      public ValuesListener(Snowball plugin)
      {
        this.plugin = plugin;
      }
      
      @EventHandler
      public void onProjectileHit(ProjectileHitEvent event)
      {
        Entity entity = event.getEntity();
        
    
        float size = plugin.getConfig().getInt("Size of Explosion");
        boolean damage = this.plugin.getConfig().getBoolean("Block Damage");
        boolean fire = this.plugin.getConfig().getBoolean("Set Fire");
        if ((entity instanceof Snowball))
        {
          Snowball snowball = (Snowball)entity;
          Entity shooter = snowball.getShooter();
          if ((shooter instanceof Player))
          {
            Player player = (Player)shooter;
            Location sb = snowball.getLocation();
            if (this.plugin.players.contains(player.getName())) {
              player.getWorld().createExplosion(sb.getX(), sb.getY(), sb.getZ(), size, fire, damage);
            }
          }
        }
      }
    }
    
    
    
    Error is in last class file where is gives this output:
    Description Resource Path Location Type
    The method getConfig() is undefined for the type Snowball ValuesListener.java /snowball explode/src/rc/vanilla line 31 Java Problem
     
  2. Offline

    Mmarz11

    Azolex The issue is that you named your plugin main class Snowball. The class is trying to call the getConfig() method in the org.bukkit.entity.Snowball class due to that being what you have imported and it can not find it. You meant for it to be using the rc.vanilla.Snowball class. It would be best if you renamed the class to something that doesn't conflict with Bukkit classes so you do not have the issue in the future.
     
Thread Status:
Not open for further replies.

Share This Page