Exemple #1
0
 /**
  * Initialize the updater
  *
  * @param plugin The plugin that is checking for an update.
  * @param slug The dev.bukkit.org slug of the project
  *     (http://dev.bukkit.org/server-mods/SLUG_IS_HERE)
  * @param file The file that the plugin is running from, get this by doing this.getFile() from
  *     within your main class.
  * @param type Specify the type of update this will be. See {@link UpdateType}
  * @param announce True if the program should announce the progress of new updates in console
  */
 public Updater(Plugin plugin, String slug, File file, UpdateType type, boolean announce) {
   this.plugin = plugin;
   this.type = type;
   this.announce = announce;
   this.file = file;
   try {
     // Obtain the results of the project's file feed
     url = new URL(DBOUrl + slug + "/files.rss");
   } catch (MalformedURLException ex) {
     // Invalid slug
     plugin
         .getLogger()
         .warning(
             "The author of this plugin ("
                 + plugin.getDescription().getAuthors().get(0)
                 + ") has misconfigured their Auto Update system");
     plugin
         .getLogger()
         .warning(
             "The project slug given ('"
                 + slug
                 + "') is invalid. Please nag the author about this.");
     result = Updater.UpdateResult.FAIL_BADSLUG; // Bad slug! Bad!
   }
   thread = new Thread(new UpdateRunnable());
   thread.start();
 }
Exemple #2
0
 private boolean versionCheck(String title) {
   if (type != UpdateType.NO_VERSION_CHECK) {
     String version = plugin.getDescription().getVersion();
     if (title.split("v").length == 2) {
       String remoteVersion =
           title.split("v")[1].split(" ")[0]; // Get the newest file's version number
       if (hasTag(version) || version.equalsIgnoreCase(remoteVersion)) {
         // We already have the latest version, or this build is tagged for no-update
         result = Updater.UpdateResult.NO_UPDATE;
         return false;
       }
     } else {
       // The file's name did not contain the string 'vVersion'
       plugin
           .getLogger()
           .warning("The author of this plugin has misconfigured their Auto Update system");
       plugin
           .getLogger()
           .warning(
               "Files uploaded to BukkitDev should contain the version number, seperated from the name by a 'v', such as PluginName v1.0");
       plugin
           .getLogger()
           .warning(
               "Please notify the author ("
                   + plugin.getDescription().getAuthors().get(0)
                   + ") of this error.");
       result = Updater.UpdateResult.FAIL_NOVERSION;
       return false;
     }
   }
   return true;
 }
Exemple #3
0
 public void check() {
   if (!isCurrent()) {
     plugin.getLogger().log(Level.INFO, "New Version " + version + " Out!");
     plugin.getLogger().log(Level.INFO, title + " published on: " + pubdate);
     plugin.getLogger().log(Level.INFO, "Download at " + link);
     warn = true;
   }
 }
Exemple #4
0
  /** Save an update from dev.bukkit.org into the server's update folder. */
  private void saveFile(File folder, String file, String u) {
    if (!folder.exists()) {
      folder.mkdir();
    }
    BufferedInputStream in = null;
    FileOutputStream fout = null;
    try {
      // Download the file
      URL url = new URL(u);
      int fileLength = url.openConnection().getContentLength();
      in = new BufferedInputStream(url.openStream());
      fout = new FileOutputStream(folder.getAbsolutePath() + "/" + file);

      byte[] data = new byte[BYTE_SIZE];
      int count;
      if (announce) plugin.getLogger().info("About to download a new update: " + versionTitle);
      long downloaded = 0;
      while ((count = in.read(data, 0, BYTE_SIZE)) != -1) {
        downloaded += count;
        fout.write(data, 0, count);
        int percent = (int) (downloaded * 100 / fileLength);
        if (announce & (percent % 10 == 0)) {
          plugin
              .getLogger()
              .info("Downloading update: " + percent + "% of " + fileLength + " bytes.");
        }
      }
      // Just a quick check to make sure we didn't leave any files from last time...
      for (File xFile : new File("plugins/" + updateFolder).listFiles()) {
        if (xFile.getName().endsWith(".zip")) {
          xFile.delete();
        }
      }
      // Check to see if it's a zip file, if it is, unzip it.
      File dFile = new File(folder.getAbsolutePath() + "/" + file);
      if (dFile.getName().endsWith(".zip")) {
        // Unzip
        unzip(dFile.getCanonicalPath());
      }
      if (announce) plugin.getLogger().info("Finished updating.");
    } catch (Exception ex) {
      plugin
          .getLogger()
          .warning("The auto-updater tried to download a new update, but was unsuccessful.");
      result = Updater.UpdateResult.FAIL_DOWNLOAD;
    } finally {
      try {
        if (in != null) {
          in.close();
        }
        if (fout != null) {
          fout.close();
        }
      } catch (Exception ex) {
      }
    }
  }
Exemple #5
0
  /** @author CraftCraft */
  public void loadPlugins() {
    pluginManager.registerInterface(JavaPluginLoader.class);

    File pluginFolder = theServer.getFile("plugins");

    if (pluginFolder.exists()) {
      this.theLogger.info("Plugins are being loaded...");
      Plugin[] plugins = pluginManager.loadPlugins(pluginFolder);
      for (Plugin plugin : plugins) {
        try {
          String message = String.format("Loading %s", plugin.getDescription().getFullName());
          plugin.getLogger().info(message);
          plugin.onLoad();
        } catch (Throwable ex) {
          Logger.getLogger(CraftServer.class.getName())
              .log(
                  Level.SEVERE,
                  ex.getMessage()
                      + " initializing "
                      + plugin.getDescription().getFullName()
                      + " (Is it up to date?)",
                  ex);
        }
      }
    } else {
      theLogger.info("Plugin folder doesn't exist: " + pluginFolder.getAbsolutePath());
      pluginFolder.mkdir();
    }
  }
  public void mergeConfig() {

    // options().copyDefaults(false);
    // System.out.println("merging
    // config?"+contains("settings.restrictions.ProtectInventoryBeforeLogIn")+checkDefaults());
    if (!contains("settings.restrictions.ProtectInventoryBeforeLogIn")) {
      set("settings.restrictions.enablePasswordVerifier", true);
      set("settings.restrictions.ProtectInventoryBeforeLogIn", true);
    }

    if (!contains("settings.security.passwordMaxLength")) {
      set("settings.security.passwordMaxLength", 20);
    }

    if (!contains("BackupSystem.ActivateBackup")) {
      set("BackupSystem.ActivateBackup", false);
      set("BackupSystem.OnServerStart", false);
      set("BackupSystem.OnServeStop", false);
    }

    if (!contains("BackupSystem.MysqlWindowsPath")) {
      set("BackupSystem.MysqlWindowsPath", "C:\\Program Files\\MySQL\\MySQL Server 5.1\\");
    }

    if (!contains("settings.messagesLanguage")) {
      set("settings.messagesLanguage", "en");
    } else return;

    plugin.getLogger().info("Merge new Config Options..");
    plugin.saveConfig();

    return;
  }
Exemple #7
0
 /**
  * As the result of Updater output depends on the thread's completion, it is necessary to wait for
  * the thread to finish before allowing anyone to check the result.
  */
 private void waitForThread() {
   if ((this.thread != null) && this.thread.isAlive()) {
     try {
       this.thread.join();
     } catch (final InterruptedException e) {
       plugin.getLogger().log(Level.SEVERE, null, e);
     }
   }
 }
Exemple #8
0
 private boolean checkState(boolean newState, boolean restart) {
   if (enabled != newState) {
     enabled = newState;
     plugin
         .getLogger()
         .info("[AutoUpdate] v" + version + (enabled ? " enabled" : " disabled") + "!");
     if (restart) return restartMainTask();
   }
   return enabled;
 }
  /** Save an update from dev.bukkit.org into the server's update folder. */
  private void saveFile(final File folder, final String file, final String u) {
    if (!folder.exists()) {
      folder.mkdir();
    }
    BufferedInputStream in = null;
    FileOutputStream fout = null;
    try {
      // Download the file
      URL url = new URL(u);
      int fileLength = url.openConnection().getContentLength();
      in = new BufferedInputStream(url.openStream());
      fout = new FileOutputStream(folder.getAbsolutePath() + "/" + file);

      byte[] data = new byte[BYTE_SIZE];
      int count;
      long downloaded = 0;
      while ((count = in.read(data, 0, BYTE_SIZE)) != -1) {
        downloaded += count;
        fout.write(data, 0, count);
        int percent = (int) ((downloaded * 100) / fileLength);
        if (((percent % 10) == 0)) {
          plugin
              .getLogger()
              .info("Downloading update: " + percent + "% of " + fileLength + " bytes.");
        }
      }
      plugin.getLogger().info("Finished updating.");
      result = DevUpdateResult.SUCCESS;
    } catch (Exception ex) {
      result = DevUpdateResult.FAILED;
    } finally {
      try {
        if (in != null) {
          in.close();
        }
        if (fout != null) {
          fout.close();
        }
      } catch (Exception ex) {
        result = DevUpdateResult.FAILED;
      }
    }
  }
Exemple #10
0
 /** Open the RSS feed */
 private InputStream read() {
   try {
     return url.openStream();
   } catch (IOException e) {
     plugin
         .getLogger()
         .warning(
             "Could not reach BukkitDev file stream for update checking. Is dev.bukkit.org offline?");
     return null;
   }
 }
    public void load() {
        try {
            synchronized (mutex) {
                plugin.getLogger().log(Level.INFO, "Loading configuration file: " + name);
                onLoad(plugin);
            }
        } catch (Exception e) {
            ErrorLogger.generateErrorLog(e);
        }

    }
 /**
  * * Initialize the updater * * @param plugin * The plugin that is checking for an update.
  * * @param slug * The dev.bukkit.org slug of the project
  * (http://dev.bukkit.org/server-mods/SLUG_IS_HERE) * @param file * The file that the plugin is
  * running from, get this by doing this.getFile() from within your main class. * @param type *
  * Specify the type of update this will be. See {@link UpdateType} * @param announce * True if the
  * program should announce the progress of new updates in console
  */
 public Updater(Plugin plugin, String slug, File file, UpdateType type, boolean announce) {
   this.plugin = plugin;
   this.type = type;
   this.announce = announce;
   try {
     // Obtain the results of the project's file feed
     url = new URL(DBOUrl + slug + "/files.rss");
   } catch (MalformedURLException ex) {
     // The slug doesn't exist
     plugin
         .getLogger()
         .warning("The author of this plugin has misconfigured their Auto Update system");
     plugin
         .getLogger()
         .warning(
             "The project slug added ('"
                 + slug
                 + "') is invalid, and does not exist on dev.bukkit.org");
     result = Updater.UpdateResult.FAIL_BADSLUG;
     // Bad slug! Bad!
   }
   if (url != null) {
     // Obtain the results of the project's file feed
     readFeed();
     if (versionCheck(versionTitle)) {
       String fileLink = getFile(versionLink);
       if (fileLink != null && type != UpdateType.NO_DOWNLOAD) {
         String name = file.getName();
         // If it's a zip file, it shouldn't be downloaded as the plugin's name
         if (fileLink.endsWith(".zip")) {
           String[] split = fileLink.split("/");
           name = split[split.length - 1];
         }
         saveFile(new File("plugins/" + updateFolder), name, fileLink);
       } else {
         result = UpdateResult.UPDATE_AVAILABLE;
       }
     }
   }
 }
Exemple #13
0
 /** Part of RSS Reader by Vogella, modified by H31IX for use with Bukkit */
 private boolean readFeed() {
   try {
     // Set header values intial to the empty string
     String title = "";
     String link = "";
     // First create a new XMLInputFactory
     XMLInputFactory inputFactory = XMLInputFactory.newInstance();
     // Setup a new eventReader
     InputStream in = read();
     if (in != null) {
       XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
       // Read the XML document
       while (eventReader.hasNext()) {
         XMLEvent event = eventReader.nextEvent();
         if (event.isStartElement()) {
           if (event.asStartElement().getName().getLocalPart().equals(TITLE)) {
             event = eventReader.nextEvent();
             title = event.asCharacters().getData();
             continue;
           }
           if (event.asStartElement().getName().getLocalPart().equals(LINK)) {
             event = eventReader.nextEvent();
             link = event.asCharacters().getData();
             continue;
           }
         } else if (event.isEndElement()) {
           if (event.asEndElement().getName().getLocalPart().equals(ITEM)) {
             // Store the title and link of the first entry we get - the first file on the list is
             // all we need
             versionTitle = title;
             versionLink = link;
             // All done, we don't need to know about older files.
             break;
           }
         }
       }
       return true;
     } else {
       return false;
     }
   } catch (XMLStreamException e) {
     plugin
         .getLogger()
         .warning("Could not reach dev.bukkit.org for update checking. Is it offline?");
     return false;
   }
 }
Exemple #14
0
 /**
  * This will use a custom configuration. Use this in onEnable().
  *
  * @param plugin The instance of your plugins main class.
  * @param config The configuration to use.
  * @throws Exception
  */
 public AutoUpdate(Plugin plugin, Configuration config) throws Exception {
   if (plugin == null) throw new Exception("Plugin can not be null");
   this.plugin = plugin;
   av = ymlPrefix + plugin.getDescription().getVersion() + ymlSuffix;
   if (bukkitdevSlug == null || bukkitdevSlug.equals("")) bukkitdevSlug = plugin.getName();
   bukkitdevSlug = bukkitdevSlug.toLowerCase();
   bukget = "http://bukget.v10lator.de/" + bukkitdevSlug;
   bukgetFallback = "http://bukget.org/api/plugin/" + bukkitdevSlug + "/latest";
   if (delay < 72000L) {
     plugin
         .getLogger()
         .info("[AutoUpdate] delay < 72000 ticks not supported. Setting delay to 72000.");
     delay = 72000L;
   }
   setConfig(config);
   plugin.getServer().getPluginManager().registerEvents(this, plugin);
 }
    private void onLoad(Plugin plugin) throws Exception {
        synchronized (mutex) {
            File fold;
            if (folder != null)
                fold = new File(plugin.getDataFolder() + folder.replace(".", File.separator));
            else fold = plugin.getDataFolder();

            if (!fold.exists()) {
                fold.mkdir();
            }
            File worldFile = new File(fold.getAbsoluteFile(), File.separator + name + ".yml");
            YamlConfiguration worlds = YamlConfiguration.loadConfiguration(worldFile);
            ((FileConfiguration) worlds).options().header(header);

            for (Field field : getClass().getDeclaredFields()) {
                if (doSkip(field))
                    continue;
                String path = prefix + "." + field.getName().replaceAll("__", " ").replaceAll("_", ".");
                if (worlds.isSet(path)) {
                    LimitInteger lim;
                    if ((lim = field.getAnnotation(LimitInteger.class)) != null) {
                        int limit = lim.limit();
                        boolean doCorrect = false;
                        try {
                            if (worlds.getInt(path) > limit) {
                                doCorrect = true;
                            }
                        } catch (Exception e) {
                            doCorrect = true;
                        }
                        if (doCorrect) {
                            plugin.getLogger().log(Level.SEVERE, lim.warning().replace("%node", "'" + path.substring(6) + "'").replace("%limit", limit + ""));
                            if (lim.correct())
                                worlds.set(path, lim.limit());
                        }
                    }
                    field.set(this, worlds.get(path));
                } else
                    worlds.set(path, field.get(this));
            }

            worlds.save(worldFile);
            Files.write(StringUtils.join(addComments(Files.toString(worldFile, Charset.defaultCharset()).split("\n")), "\n"), worldFile, Charset.defaultCharset());
        }
    }
Exemple #16
0
  public void initializeMasterFilter() {
    String pname = "";
    try {
      for (Plugin p : this.getServer().getPluginManager().getPlugins()) {
        pname = p.toString();
        p.getLogger().setFilter(this.masterFilter);
        // i++;
      }
      this.getServer().getLogger().setFilter(masterFilter);
      Bukkit.getLogger().setFilter(masterFilter);
      Logger.getLogger("Minecraft").setFilter(masterFilter);
    } catch (Exception e) {
      log(Level.INFO, "Cannot load filter in '" + pname + "'. Retrying later..");
    }
    this.getServer()
        .getScheduler()
        .scheduleSyncDelayedTask(
            this,
            new Runnable() {

              @Override
              public void run() {
                String pname = "";
                try {
                  for (Plugin p : getServer().getPluginManager().getPlugins()) {
                    pname = p.toString();
                    p.getLogger().setFilter(masterFilter);
                  }
                  getServer().getLogger().setFilter(masterFilter);
                  Bukkit.getLogger().setFilter(masterFilter);
                  Logger.getLogger("Minecraft").setFilter(masterFilter);
                } catch (Exception e) {
                  log(
                      Level.WARNING,
                      "Cannot load filter in '"
                          + pname
                          + "'. The logs of this plugin will not be filtered");
                }
              }
            },
            1);
  }
Exemple #17
0
  /** Obtain the direct download file url from the file's page. */
  private String getFile(String link) {
    String download = null;
    try {
      // Open a connection to the page
      URL url = new URL(link);
      URLConnection urlConn = url.openConnection();
      InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
      BufferedReader buff = new BufferedReader(inStream);

      int counter = 0;
      String line;
      while ((line = buff.readLine()) != null) {
        counter++;
        // Search for the download link
        if (line.contains("<li class=\"user-action user-action-download\">")) {
          // Get the raw link
          download = line.split("<a href=\"")[1].split("\">Download</a>")[0];
        }
        // Search for size
        else if (line.contains("<dt>Size</dt>")) {
          sizeLine = counter + 1;
        } else if (counter == sizeLine) {
          String size = line.replaceAll("<dd>", "").replaceAll("</dd>", "");
          multiplier = size.contains("MiB") ? 1048576 : 1024;
          size = size.replace(" KiB", "").replace(" MiB", "");
          totalSize = (long) (Double.parseDouble(size) * multiplier);
        }
      }
      urlConn = null;
      inStream = null;
      buff.close();
      buff = null;
    } catch (Exception ex) {
      ex.printStackTrace();
      plugin
          .getLogger()
          .warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful.");
      result = Updater.UpdateResult.FAIL_DBO;
      return null;
    }
    return download;
  }
Exemple #18
0
 public VersionChecker(Plugin _plugin, String u) {
   plugin = _plugin;
   try {
     DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
     url = new URL(u);
     Document doc = builder.parse(url.openStream());
     Element element = (Element) doc.getElementsByTagName("item").item(0);
     title = (getElementValue(element, "title"));
     link = (getElementValue(element, "link"));
     String[] pubdates = (getElementValue(element, "pubDate")).split(" ");
     pubdate = pubdates[0] + " " + pubdates[1] + " " + pubdates[2] + " " + pubdates[3];
     version =
         title
             .substring(title.indexOf('['))
             .replaceAll("\\[", "")
             .replaceAll("\\]", "")
             .replace(" ", "");
     thisversion = plugin.getDescription().getVersion().replace("-DEV", "");
     Bukkit.getPluginManager().registerEvents(this, plugin);
     check();
   } catch (Exception e) {
     plugin.getLogger().log(Level.WARNING, "Could not check versions due to connection problems!");
   }
 }
 /**
  * A little extension to logger, capable to send debug messages to a player This constructor
  * disables debug to player
  *
  * @param plugin The plugin using this logger
  * @param debug If true messages with level debug will be shown
  */
 public CraftGuardLogger(Plugin plugin) {
   this.plugin = plugin;
   this.logger = plugin.getLogger();
 }
Exemple #20
0
  /**
   * Initialize the updater
   *
   * @param plugin The plugin that is checking for an update.
   * @param id The dev.bukkit.org id of the project
   * @param file The file that the plugin is running from, get this by doing this.getFile() from
   *     within your main class.
   * @param type Specify the type of update this will be. See {@link UpdateType}
   * @param announce True if the program should announce the progress of new updates in console
   */
  public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) {
    this.plugin = plugin;
    this.type = type;
    this.announce = announce;
    this.file = file;
    this.id = id;
    this.updateFolder = plugin.getServer().getUpdateFolder();

    final File pluginFile = plugin.getDataFolder().getParentFile();
    final File updaterFile = new File(pluginFile, "Updater");
    final File updaterConfigFile = new File(updaterFile, "config.yml");

    if (!updaterFile.exists()) {
      updaterFile.mkdir();
    }
    if (!updaterConfigFile.exists()) {
      try {
        updaterConfigFile.createNewFile();
      } catch (final IOException e) {
        plugin
            .getLogger()
            .severe(
                "The updater could not create a configuration in " + updaterFile.getAbsolutePath());
        e.printStackTrace();
      }
    }
    this.config = YamlConfiguration.loadConfiguration(updaterConfigFile);

    this.config
        .options()
        .header(
            "This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )"
                + '\n'
                + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below."
                + '\n'
                + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration.");
    this.config.addDefault("api-key", "PUT_API_KEY_HERE");
    this.config.addDefault("disable", false);

    if (this.config.get("api-key", null) == null) {
      this.config.options().copyDefaults(true);
      try {
        this.config.save(updaterConfigFile);
      } catch (final IOException e) {
        plugin
            .getLogger()
            .severe(
                "The updater could not save the configuration in " + updaterFile.getAbsolutePath());
        e.printStackTrace();
      }
    }

    if (this.config.getBoolean("disable")) {
      this.result = UpdateResult.DISABLED;
      return;
    }

    String key = this.config.getString("api-key");
    if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) {
      key = null;
    }

    this.apiKey = key;

    try {
      this.url = new URL(Updater.HOST + Updater.QUERY + id);
    } catch (final MalformedURLException e) {
      plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid.");
      this.result = UpdateResult.FAIL_BADID;
      e.printStackTrace();
    }

    this.thread = new Thread(new UpdateRunnable());
    this.thread.start();
  }
Exemple #21
0
 /** Part of Zip-File-Extractor, modified by H31IX for use with Bukkit */
 private void unzip(String file) {
   try {
     File fSourceZip = new File(file);
     String zipPath = file.substring(0, file.length() - 4);
     ZipFile zipFile = new ZipFile(fSourceZip);
     Enumeration<? extends ZipEntry> e = zipFile.entries();
     while (e.hasMoreElements()) {
       ZipEntry entry = e.nextElement();
       File destinationFilePath = new File(zipPath, entry.getName());
       destinationFilePath.getParentFile().mkdirs();
       if (entry.isDirectory()) {
         continue;
       } else {
         BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
         int b;
         byte buffer[] = new byte[BYTE_SIZE];
         FileOutputStream fos = new FileOutputStream(destinationFilePath);
         BufferedOutputStream bos = new BufferedOutputStream(fos, BYTE_SIZE);
         while ((b = bis.read(buffer, 0, BYTE_SIZE)) != -1) {
           bos.write(buffer, 0, b);
         }
         bos.flush();
         bos.close();
         bis.close();
         String name = destinationFilePath.getName();
         if (name.endsWith(".jar") && pluginFile(name)) {
           destinationFilePath.renameTo(new File("plugins/" + updateFolder + "/" + name));
         }
       }
       entry = null;
       destinationFilePath = null;
     }
     e = null;
     zipFile.close();
     zipFile = null;
     // Move any plugin data folders that were included to the right place, Bukkit won't do this
     // for us.
     for (File dFile : new File(zipPath).listFiles()) {
       if (dFile.isDirectory()) {
         if (pluginFile(dFile.getName())) {
           File oFile = new File("plugins/" + dFile.getName()); // Get current dir
           File[] contents = oFile.listFiles(); // List of existing files in the current dir
           for (File cFile : dFile.listFiles()) // Loop through all the files in the new dir
           {
             boolean found = false;
             for (File xFile : contents) // Loop through contents to see if it exists
             {
               if (xFile.getName().equals(cFile.getName())) {
                 found = true;
                 break;
               }
             }
             if (!found) {
               // Move the new file into the current dir
               cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName()));
             } else {
               // This file already exists, so we don't need it anymore.
               cFile.delete();
             }
           }
         }
       }
       dFile.delete();
     }
     new File(zipPath).delete();
     fSourceZip.delete();
   } catch (IOException ex) {
     ex.printStackTrace();
     plugin
         .getLogger()
         .warning("The auto-updater tried to unzip a new update file, but was unsuccessful.");
     result = Updater.UpdateResult.FAIL_DOWNLOAD;
   }
   new File(file).delete();
 }
Exemple #22
0
  /**
   * Initialize the updater.
   *
   * @param plugin The plugin that is checking for an update.
   * @param id The dev.bukkit.org id of the project.
   * @param file The file that the plugin is running from, get this by doing this.getFile() from
   *     within your main class.
   * @param type Specify the type of update this will be. See {@link UpdateType}
   * @param announce True if the program should announce the progress of new updates in console.
   */
  public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) {
    this.plugin = plugin;
    this.type = type;
    this.announce = announce;
    this.file = file;
    this.id = id;
    this.updateFolder = plugin.getServer().getUpdateFolder();

    final File pluginFile = plugin.getDataFolder().getParentFile();
    final File updaterFile = new File(pluginFile, "Pay4Commands");
    final File updaterConfigFile = new File(updaterFile, "config.yml");
    this.config.addDefault("api-key", "cc983de73e2f0a00c737fc69e1d9e78ff290");
    this.config.addDefault("disable", false);

    if (!updaterFile.exists()) {
      updaterFile.mkdir();
    }

    boolean createFile = !updaterConfigFile.exists();
    try {
      if (createFile) {
        updaterConfigFile.createNewFile();
        this.config.options().copyDefaults(true);
        this.config.save(updaterConfigFile);
      } else {
        this.config.load(updaterConfigFile);
      }
    } catch (final Exception e) {
      if (createFile) {
        plugin
            .getLogger()
            .severe(
                "The updater could not create configuration at " + updaterFile.getAbsolutePath());
      } else {
        plugin
            .getLogger()
            .severe("The updater could not load configuration at " + updaterFile.getAbsolutePath());
      }
      plugin.getLogger().log(Level.SEVERE, null, e);
    }

    if (this.config.getBoolean("disable")) {
      this.result = UpdateResult.DISABLED;
      return;
    }

    String key = this.config.getString("api-key");
    if (key.equalsIgnoreCase("cc983de73e2f0a00c737fc69e1d9e78ff290") || key.equals("")) {
      key = null;
    }

    this.apiKey = key;

    try {
      this.url = new URL(Updater.HOST + Updater.QUERY + id);
    } catch (final MalformedURLException e) {
      plugin
          .getLogger()
          .log(Level.SEVERE, "The project ID provided for updating, " + id + " is invalid.", e);
      this.result = UpdateResult.FAIL_BADID;
    }

    this.thread = new Thread(new UpdateRunnable());
    this.thread.start();
  }
 protected CustomCommandExecutor(Plugin plugin, int commandIndex) {
   this.plugin = plugin;
   this.log = plugin.getLogger();
   this.commandIndex = commandIndex;
   addMethods(this, getClass().getMethods());
 }
  public void loadConfigOptions() {

    plugin.getLogger().info("Loading Configuration File...");

    mergeConfig();

    messagesLanguage = checkLang(configFile.getString("settings.messagesLanguage", "en"));
    isPermissionCheckEnabled = configFile.getBoolean("permission.EnablePermissionCheck", false);
    isForcedRegistrationEnabled = configFile.getBoolean("settings.registration.force", true);
    isRegistrationEnabled = configFile.getBoolean("settings.registration.enabled", true);
    isTeleportToSpawnEnabled =
        configFile.getBoolean("settings.restrictions.teleportUnAuthedToSpawn", false);
    getWarnMessageInterval = configFile.getInt("settings.registration.messageInterval", 5);
    isSessionsEnabled = configFile.getBoolean("settings.sessions.enabled", false);
    getSessionTimeout = configFile.getInt("settings.sessions.timeout", 10);
    getRegistrationTimeout = configFile.getInt("settings.restrictions.timeout", 30);
    isChatAllowed = configFile.getBoolean("settings.restrictions.allowChat", false);
    getMaxNickLength = configFile.getInt("settings.restrictions.maxNicknameLength", 20);
    getMinNickLength = configFile.getInt("settings.restrictions.minNicknameLength", 3);
    getPasswordMinLen = configFile.getInt("settings.security.minPasswordLength", 4);
    getNickRegex =
        configFile.getString("settings.restrictions.allowedNicknameCharacters", "[a-zA-Z0-9_?]*");
    isAllowRestrictedIp = configFile.getBoolean("settings.restrictions.AllowRestrictedUser", false);
    getRestrictedIp = configFile.getStringList("settings.restrictions.AllowedRestrictedUser");
    isMovementAllowed = configFile.getBoolean("settings.restrictions.allowMovement", false);
    getMovementRadius = configFile.getInt("settings.restrictions.allowedMovementRadius", 100);
    getJoinPermissions = configFile.getStringList("GroupOptions.Permissions.PermissionsOnJoin");
    isKickOnWrongPasswordEnabled =
        configFile.getBoolean("settings.restrictions.kickOnWrongPassword", false);
    isKickNonRegisteredEnabled =
        configFile.getBoolean("settings.restrictions.kickNonRegistered", false);
    isForceSingleSessionEnabled =
        configFile.getBoolean("settings.restrictions.ForceSingleSession", true);
    isForceSpawnLocOnJoinEnabled =
        configFile.getBoolean("settings.restrictions.ForceSpawnLocOnJoinEnabled", false);
    isSaveQuitLocationEnabled =
        configFile.getBoolean("settings.restrictions.SaveQuitLocation", false);
    isForceSurvivalModeEnabled =
        configFile.getBoolean("settings.GameMode.ForceSurvivalMode", false);
    isResetInventoryIfCreative =
        configFile.getBoolean("settings.GameMode.ResetInventotyIfCreative", false);
    getmaxRegPerIp = configFile.getInt("settings.restrictions.maxRegPerIp", 1);
    getPasswordHash = getPasswordHash();
    getUnloggedinGroup =
        configFile.getString("settings.security.unLoggedinGroup", "unLoggedInGroup");
    getDataSource = getDataSource();
    isCachingEnabled = configFile.getBoolean("DataSource.caching", true);
    getMySQLHost = configFile.getString("DataSource.mySQLHost", "127.0.0.1");
    getMySQLPort = configFile.getString("DataSource.mySQLPort", "3306");
    getMySQLUsername = configFile.getString("DataSource.mySQLUsername", "authme");
    getMySQLPassword = configFile.getString("DataSource.mySQLPassword", "12345");
    getMySQLDatabase = configFile.getString("DataSource.mySQLDatabase", "authme");
    getMySQLTablename = configFile.getString("DataSource.mySQLTablename", "authme");
    getMySQLColumnName = configFile.getString("DataSource.mySQLColumnName", "username");
    getMySQLColumnPassword = configFile.getString("DataSource.mySQLColumnPassword", "password");
    getMySQLColumnIp = configFile.getString("DataSource.mySQLColumnIp", "ip");
    getMySQLColumnLastLogin = configFile.getString("DataSource.mySQLColumnLastLogin", "lastlogin");
    getMySQLColumnSalt = configFile.getString("ExternalBoardOptions.mySQLColumnSalt");
    getMySQLColumnGroup = configFile.getString("ExternalBoardOptions.mySQLColumnGroup", "");
    getNonActivatedGroup = configFile.getInt("ExternalBoardOptions.nonActivedUserGroup", -1);
    unRegisteredGroup = configFile.getString("GroupOptions.UnregisteredPlayerGroup", "");
    getUnrestrictedName = configFile.getStringList("settings.unrestrictions.UnrestrictedName");
    getRegisteredGroup = configFile.getString("GroupOptions.RegisteredPlayerGroup", "");
    getEnablePasswordVerifier =
        configFile.getBoolean("settings.restrictions.enablePasswordVerifier", true);
    protectInventoryBeforeLogInEnabled =
        configFile.getBoolean("settings.restrictions.ProtectInventoryBeforeLogIn", true);
    passwordMaxLength = configFile.getInt("settings.security.passwordMaxLength", 20);
    isBackupActivated = configFile.getBoolean("BackupSystem.ActivateBackup", false);
    isBackupOnStart = configFile.getBoolean("BackupSystem.OnServerStart", false);
    isBackupOnStop = configFile.getBoolean("BackupSystem.OnServeStop", false);
    backupWindowsPath =
        configFile.getString(
            "BackupSystem.MysqlWindowsPath", "C:\\Program Files\\MySQL\\MySQL Server 5.1\\");

    saveDefaults();

    // System.out.println("[AuthMe debug] Config " + getEnablePasswordVerifier.toString());
    // System.out.println("[AuthMe debug] Config " + getEnablePasswordVerifier.toString());

  }