Resource Code List (In need of snippets!)

Discussion in 'Resources' started by Jnorr44, Jul 2, 2012.

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

    Jnorr44

    Resource Code List;
    This thread is a list of snippets of code that developers wish to share. If you want to use this code, feel free, but please give credit to the user who wrote it! Many players now just ask for the code, and don't care to learn from it at all, and although that is annoying to plugin developers, it's perfectly alright for starters. Just seeing code teaches new developers how to write their code, and I believe it actually makes more developers. If you do choose to post something on this list, make sure it is self-explanatory, and is not copied from an existing plugin (unless it is yours). If you wish to put some code on this list, please follow the template below:

    Code:
    [<user>] <**use**>
    <link> 
    Please make sure you send a pastie/pastebin link to the code, not just a direct snippet!

    ____________________________________​

    [Jnorr44] Preventing players from changing their inventory:
    http://pastie.org/4190446

    [one4me] Basic command outline:
    http://pastie.org/4200895

    [one4me] Remove consecutive spaces from a string:
    http://pastie.org/4200907

    [one4me] Turn an array into a string:
    http://pastie.org/4200901

    [one4me] Extract any file from the route of your .jar:
    http://pastie.org/4200933

    [one4me] Automatically update your plugin:
    http://pastie.org/4200943

    Reserved

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 26, 2016
  2. Offline

    chaseoes Retired Staff

    Code:java
    1. // Send a player a message!
    2. player.sendMessage("Your Message");
    Good?
     
  3. Offline

    one4me

    I know this isn't the correct format you want people to use.... but here are a few snippets I had used in my plugin. Feel free to use them if you want, they should be licensed under the GPLv3 if that matters.


    Basic Command Outline
    I figured this may be useful to some people.
    Code:
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
      if(cmd.getName().equalsIgnoreCase(/*CommandHere*/)) {
        if(sender instanceof Player) {
          if(sender.hasPermission(cmd.getPermission())) {
            if(args.length == 1) {
              if(getServer().getPlayer(args[0]) != null) {
                //Do stuff here
              }
              else {
                sender.sendMessage(ChatColor.YELLOW + "Player '" + args[0] + "' is not online.");
              }
            }
            else {
              sender.sendMessage(ChatColor.RED + cmd.getUsage());
            }
          }
          else {
            sender.sendMessage(ChatColor.RED + cmd.getPermissionMessage());
          }
        }
        else {
          sender.sendMessage("You must be logged in to use " + cmd.getName());
        }
      }
      return true;
    }
     
    /*
    Add to plugin.yml -
    commands:
          COMMAND:
            description: 'An example description'
            permission: node.example
            usage: 'Usage: /command player'
            permission-message: 'You do not have permission!'
        permissions:
          node.example:
            description: ''
            default: op
    */

    Message Builder
    This code is simple enough, it takes an array and turns it into one string.
    Code:
    public String buildMessage(String[] input, int start) {
      String message = "";
      for(int i = start; i < input.length; i++) {
        message = message + input[i] + " ";
      }
      return message.trim();
    }
    

    Message Formatter
    This code is more simple than the previous, it takes a string, replaces any amout of consecutive spaces with a single space, and removes all spaces from the beginning and of it.
    Code:
    public String formatMessage(String input) {
      input = input.trim().replaceAll("\\s+", " ");
      return input;
    }
    

    File Extractor
    This lets you extract any file from the root of you jar, it has it's uses.
    Code:
    public boolean extractFile(String filename, File destination) {
      File outputFile = new File(destination, filename);
      DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
      Date date = new Date();
      String theDate = dateFormat.format(date);
      File backup = new File(destination, theDate + filename);
      try {
        if(outputFile.exists()) {
          outputFile.renameTo(backup);
        }
        destination.mkdir();
        if(getClass().getResourceAsStream("/" + filename) == null) {
          if(backup.exists()) {
            backup.renameTo(outputFile);
          }
          System.out.println("File not found in jar: " + filename);
          return false;
        }
        outputFile.createNewFile();
        InputStream is = getClass().getResourceAsStream("/" + filename);
        FileOutputStream fos = new FileOutputStream(outputFile);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while((bytesRead = is.read(buffer)) > 0) {
          fos.write(buffer, 0, bytesRead);
        }
        fos.flush();
        fos.close();
        is.close();
      }
      catch (IOException e) {
        e.printStackTrace();
        System.out.println("Error extracting file: " + filename);
      }
      return true;
    }
    
    This next piece uses the previous code and checks for a file and extracts it if from the jar if it doesn't exist.
    Code:
    public boolean checkFile(String filename, File directory) {
      if(!(new File(directory, filename)).exists()) {
        if(!extractFile(filename, directory)) {
          return false;
        }
      }
      return true;
    }
    
    And finally this next piece of code shows an example of how to use the previous codes.
    Code:
    public void checkConfig() {
      if(!checkFile("config.txt", this.getDataFolder())) {
        getLogger().warning("Error creating config!");
        getServer().getPluginManager().disablePlugin(this);
      }
    }
    //You would just put checkConfig(); in onEnable(){} to run the check.
    

    Auto Updater
    I'm sure there's better code out there, but if anyone wants a simple way to check and update their plugin, just add the following code to your main. For it to work your files in Bukkit Dev need to end with -version #.#.#. and your Bukkit Dev link must equal http://dev.bukkit.org/server-mods/<PluginName>
    Code:
    public String checkUpdate(boolean forceUpdate) {
      String link = "";
      try {
        URL rss = new URL(http://dev.bukkit.org/server-mods/" + this.getDescription().getName() + "/files.rss");
        String search = "version-";
        ReadableByteChannel rbc = Channels.newChannel(rss.openStream());
        this.getDataFolder().mkdir();
        File outputFile = new File(this.getDataFolder(), this.getDescription().getName() + ".tmp");
        outputFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(outputFile);
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        fos.close();
        Scanner s = new Scanner(outputFile);
        int line = 0;
        while(s.hasNextLine()) {
          link = s.nextLine();
          if(link.contains("<link>")) {
            line++;
          }
          if(line == 2) {
            link = link.substring(link.indexOf(">") + 1);
            link = link.substring(0, link.indexOf("<"));
            break;
          }
        }
        s.close();
        outputFile.delete();
        String newVersion = link.substring(link.lastIndexOf(search) + find.search(), link.lastIndexOf("/")).replace("-", ".");
        String currentVersion = this.getDescription().getVersion();
        if(!newVersion.equals(currentVersion)) {
          if(forceUpdate) {
            downloadJar(downloadSite(link));
          }
        }
      }
      catch (IOException e) {
        e.printStackTrace();
      }
      return link;
    }
    public String downloadSite(String url) {
      String link = "";
      try {
        URL website = new URL(url);
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        File outputFile = new File(this.getDataFolder(), this.getDescription().getName() + ".tmp");
        this.getDataFolder().mkdir();
        outputFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(outputFile);
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        fos.close();
        Scanner s = new Scanner(outputFile);
        while(s.hasNextLine()) {
          link = s.nextLine();
          if(link.contains("user-action-download")) {
            link = link.substring(link.indexOf("href"));
            link = link.substring(link.indexOf("\"") + 1, link.lastIndexOf("\""));
            break;
          }
        }
        s.close();
        outputFile.delete();
      }
      catch (IOException e) {
        e.printStackTrace();
      }
      return link;
    }
    public void downloadJar(String url) {
      try {
        URL website = new URL(url);
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        File outputFile = new File("plugins", this.getDescription().getName() + ".jar");
        FileOutputStream fos = new FileOutputStream(outputFile);
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        fos.close();
        log.info("Reloading" + this.getDescription().getName() + " v" + this.getDescription().getVersion());
        unloadPlugin(this.getDescription().getName());
        loadPlugin(this.getDescription().getName());
      }
      catch(Exception e) {
        e.printStackTrace();
      }
    }
    @SuppressWarnings("unchecked")
    private void unloadPlugin(final String pluginName) throws NoSuchFieldException, IllegalAccessException {
      PluginManager manager = getServer().getPluginManager();
      SimplePluginManager spm = (SimplePluginManager) manager;
      SimpleCommandMap commandMap = null;
      List<Plugin> plugins = null;
      Map<String, Plugin> lookupNames = null;
      Map<String, Command> knownCommands = null;
      Map<Event, SortedSet<RegisteredListener>> listeners = null;
      boolean reloadlisteners = true;
      if(spm != null) {
        Field pluginsField = spm.getClass().getDeclaredField("plugins");
        pluginsField.setAccessible(true);
        plugins = (List<Plugin>) pluginsField.get(spm);
        Field lookupNamesField = spm.getClass().getDeclaredField("lookupNames");
        lookupNamesField.setAccessible(true);
        lookupNames = (Map<String, Plugin>) lookupNamesField.get(spm);
        try {
          Field listenersField = spm.getClass().getDeclaredField("listeners");
          listenersField.setAccessible(true);
          listeners = (Map<Event, SortedSet<RegisteredListener>>) listenersField.get(spm);
        }
        catch (Exception e) {
          reloadlisteners = false;
        }
        Field commandMapField = spm.getClass().getDeclaredField("commandMap");
        commandMapField.setAccessible(true);
        commandMap = (SimpleCommandMap) commandMapField.get(spm);
        Field knownCommandsField = commandMap.getClass().getDeclaredField("knownCommands");
        knownCommandsField.setAccessible(true);
        knownCommands = (Map<String, Command>) knownCommandsField.get(commandMap);
      }
      for(Plugin pl : getServer().getPluginManager().getPlugins()) {
        if(pl.getDescription().getName().equalsIgnoreCase(pluginName)) {
          manager.disablePlugin(pl);
          if(plugins != null && plugins.contains(pl)) {
            plugins.remove(pl);
          }
          if(lookupNames != null && lookupNames.containsKey(pluginName)) {
            lookupNames.remove(pluginName);
          }
          if(listeners != null && reloadlisteners) {
            for(SortedSet<RegisteredListener> set : listeners.values()) {
              for(Iterator<RegisteredListener> it = set.iterator(); it.hasNext();) {
                RegisteredListener value = it.next();
                if(value.getPlugin() == pl) {
                  it.remove();
                }
              }
            }
          }
          if(commandMap != null) {
            for(Iterator<Map.Entry<String, Command>> it = knownCommands.entrySet().iterator(); it.hasNext();) {
              Map.Entry<String, Command> entry = it.next();
              if(entry.getValue() instanceof PluginCommand) {
                PluginCommand c = (PluginCommand) entry.getValue();
                if(c.getPlugin() == pl) {
                  c.unregister(commandMap);
                  it.remove();
                }
              }
            }
          }
        }
      }
    }
    public void loadPlugin(final String pluginName) throws InvalidPluginException, InvalidDescriptionException {
      PluginManager manager = getServer().getPluginManager();
      Plugin plugin = manager.loadPlugin(new File("plugins", pluginName + ".jar"));
      if(plugin == null) {
        return;
      }
      manager.enablePlugin(plugin);
    }
    
    To run it you would just need to use this one line -
    Code:
    checkUpdate(true); //if set to false the update will not be downloaded
     
  4. Offline

    Jnorr44

    Great! Thank you I will be adding these!
     
Thread Status:
Not open for further replies.

Share This Page