Useful/Awesome Code Snippets

Discussion in 'Resources' started by iKeirNez, Oct 7, 2012.

Thread Status:
Not open for further replies.
  1. I am creating a list of useful code snippets, I'll be able to post some more of my own once I get back from holiday but I'll start it off. If you would like to contribute then please post in the comments and I may add it here (I will give credit too). The code can be general Java or specific to Bukkit if you like.

    Get All Arguments (Customizable)
    Author: iKeirNez
    Description: Get's all arguments from a command, this is useful if you are coding a plugin for sending private messages to another user and want to get all arguments. This way can save you a lot of time and it is one of the most efficient and compact ways of doing this.
    Code:
    Code:
    // the argument to start at, this will usually be 0 or 1
    // this could be useful if your arguments might contain
    // a target, in that case you would start at 1
     
    int startAt = 0;
     
    // this will allow us to easily collect the arguments
     
    StringBuilder sb = new StringBuilder();
     
    for (int i = startAt; i < args.length; i++){
    sb.append(args[i]).append(" ");
    }
     
    // this is the final space seperated string with the arguments
     
    String allArgs = sb.toString().trim();
     
    // this next bit can be whatever you want it to be, this is where you would do something with your
    // string full of arguments, in this example we will simply print them to the console
     
    System.out.println(allArgs);
    
    V10lator posted a way to do this without using the trim function to remove the extra spaces.

    Code:
    public String joinArgs(String[] args, int start)
    {
    if(args.length <= start)
    return "";
    StringBuilder sb = new StringBuilder(args[start]);
    for(start++; start < args.length; start++)
    sb.append(' ').append(args[start]);
    return sb.toString();
    
    desht posted another way of doing the above, it uses the Google Commons lib which is included in Bukkit.

    Code:
    String allArgs = Joiner.on(" ").join(args);
    BlockTickSelector
    Author: Icyene
    Description:
    Generates lists of random blocks at immense speeds. MC 1.2.X & 1.3.X compatible.

    Code:
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Random;
     
    import org.bukkit.World;
    import org.bukkit.block.Block;
    import org.bukkit.craftbukkit.CraftWorld;
     
    import net.minecraft.server.ChunkCoordIntPair;
    import net.minecraft.server.EntityHuman;
    import net.minecraft.server.WorldServer;
    import net.minecraft.server.Chunk;
     
    /*
    * @author Icyene
    */
    public class BlockTickSelector {
     
    private WorldServer world;
    private Method recheckGaps;
    private int chan;
    private final Random rand = new Random();
     
    public BlockTickSelector(World world, int selChance)
    throws NoSuchMethodException,
    SecurityException, NoSuchFieldException,
    InstantiationException, IllegalAccessException {
     
    this.world = ((CraftWorld) world).getHandle();
    recheckGaps = Chunk.class.getDeclaredMethod(Storm.version == 1.3 ? "k" : "o"); //If 1.3.X, method is named "k", else "o".
    recheckGaps.setAccessible(true); //Is private by default
    }
     
    public ArrayList<ChunkCoordIntPair> getRandomTickedChunks() throws InvocationTargetException, IllegalAccessException {
     
    ArrayList<ChunkCoordIntPair> doTick = new ArrayList<ChunkCoordIntPair>();
     
    if (world.players.isEmpty()) {
    return doTick;
    }
     
    List<org.bukkit.Chunk> loadedChunks = Arrays.asList(world.getWorld().getLoadedChunks());
     
    for (Object ob : world.players) {
     
    EntityHuman entityhuman = (EntityHuman) ob;
    int eX = (int) Math.floor(entityhuman.locX / 16), eZ = (int) Math.floor(entityhuman.locZ / 16);
     
    for (int x = -7; x <= 7; x++) {
    for (int z = -7; z <= 7; z++) {
    if (loadedChunks.contains(world.getChunkAt(x + eX, z + eZ).bukkitChunk)) { //Check if the bukkit chunk exists
    doTick.add(new ChunkCoordIntPair(x + eX, z + eZ));
    }
    }
    }
    }
    return doTick; //Empty list = failure
    }
     
    public ArrayList<Block> getRandomTickedBlocks()
    throws IllegalArgumentException,
    IllegalAccessException, InvocationTargetException {
     
    ArrayList<Block> doTick = new ArrayList<Block>();
    ArrayList<ChunkCoordIntPair> ticked = getRandomTickedChunks();
     
    if (ticked.isEmpty()) {
    return doTick;
    }
     
    for (ChunkCoordIntPair pair : ticked) {
     
    int xOffset = pair.x << 4, zOffset = pair.z << 4; //Multiply by 4, obviously.
    Chunk chunk = world.getChunkAt(pair.x, pair.z);
     
    recheckGaps.invoke(chunk); //Recheck gaps
     
    for (int i = 0; i != 3; i++) {
    if (rand.nextInt(100) <= chan) {
    int x = rand.nextInt(15), z = rand.nextInt(15);
    doTick.add(world.getWorld().getBlockAt(x + xOffset, world.g(x + xOffset, z + zOffset), z + zOffset));
    }
    }
    }
    return doTick;
    }
    }
    
    ReplaceChatColors
    Author: @iKeirNez
    Description: Replaces all chat color codes in a String to Color Codes. E.g. &f would be replaced with ChatColor.WHITE
    Code:
    Code:
    public static String replaceChatColors(String s) {
        for (ChatColor c : ChatColor.values()) {
            s = s.replaceAll("&" + c.getChar(), ChatColor.getByChar(c.getChar()) + "");
        }
     
        return s;
    }
    @chaseos told me that Bukkit now has a built in way of doing this (which I didn't know about until now)
    Code:
    Code:
    ChatColor.translateAlternateColorCodes(char arg0, String arg1);
    User-friendly Names
    Author: @iKeirNez
    Description: This code can be used for Material names, EntityType names or similiar, it replaces all _ and replaces them with a space it also capitalizes each word too.
    Code:
    Code:
    public static String userFriendlyNames(String name){
        return WordUtils.capitalize(name.replaceAll("_", " ").toLowerCase());
    }
    Example: GLOWSTONE_DUST will be changed to Glowstone Dust

    CommaStringToList
    Author: @iKeirNez
    Description: Gets a comma seperated string list and returns it as a List<String>
    Code:
    Code:
    public static List<String> separateCommaList(String s){
        return Arrays.asList(s.split("\\s*,\\s*"));
    }
    CopyFile
    Author: iKeirNez
    Description: Copies a file to another location (strangely Java doesn't have this built in) without an external library (e.g. Apache Commons)
    This should only be used for small files, the below code will struggle with big files
    Code:
    Code:
        public static void copyFile(File sourceFile, File destFile) throws IOException {
            if(!destFile.exists()) {
                destFile.createNewFile();
            }
     
            FileChannel source = null;
            FileChannel destination = null;
     
            try {
                source = new FileInputStream(sourceFile).getChannel();
                destination = new FileOutputStream(destFile).getChannel();
                destination.transferFrom(source, 0, source.size());
            }
     
            finally {
                if(source != null) {
                    source.close();
                }
         
                if(destination != null) {
                    destination.close();
                }
            }
        }
    one4me notified me that you can use this if you are using the Google Commons API (Bukkit has this included)
    Code:
    Files.copy(File from, File to);
    Delete Folder
    Author: iKeirNez
    Description: Deletes a folder and all its contents
    Code:
    Code:
    public static void deleteFolder(File folder){
            File[] files = folder.listFiles();
            if (files != null){
                for (File f : files){
                    if (f.isDirectory()){
                        deleteFolder(f);
                    } else {
                        f.delete();
                    }
                }
            }
           
            folder.delete();
        }
     
    hawkfalcon likes this.
  2. Offline

    hawkfalcon

  3. Haha I just saw that before you posted, I didn't copy it though haha. Funny how when you want to post something someone else manages to do it just before you.
     
  4. Offline

    IcyRelic

    @iKeirNez
    i have a better way of getting the args

    lets say you type /kick <player> <reason>


    Code:java
    1. public static String getFinalArg(final String[] args, final int start)
    2. {
    3. final StringBuilder bldr = new StringBuilder();
    4. for (int i = start; i < args.length; i++)
    5. {
    6. if (i != start)
    7. {
    8. bldr.append(" ");
    9. }
    10. bldr.append(args[I]);[/I]
    11. [I] }[/I]
    12. [I] return bldr.toString();[/I]
    13. [I] }[/I]


    then in the kick command use this to get the remaining args
    Code:java
    1. getFinalArg(args, 1));
     
  5. It doesn't seem too different, all you are doing there is getting rid of the final space that is not needed and then doing a check to see if it is the start and if it is not then add a space.

    It seems easier to use the trim method which would fix the problem with the spaces anyway.
     
  6. Offline

    IcyRelic

    i got this method from the essentials broadcast command it extends EssentialsCommand and i traced it to find getfinalargs andi use that now.. its just my way im not saying ur way is bad

    https://github.com/essentials/Essen.../src/net/ess3/commands/EssentialsCommand.java
     
  7. Offline

    Icyene

    BlockTickSelector
    Author: Icyene
    Description:
    Generates lists of random blocks at immense speeds. MC 1.2.X & 1.3.X compatible.

    Code:Java
    1.  
    2.  
    3. import java.lang.reflect.InvocationTargetException;
    4. import java.lang.reflect.Method;
    5. import java.util.ArrayList;
    6. import java.util.Arrays;
    7. import java.util.List;
    8. import java.util.Random;
    9. import org.bukkit.World;
    10. import org.bukkit.block.Block;
    11. import org.bukkit.craftbukkit.CraftWorld;
    12. import net.minecraft.server.ChunkCoordIntPair;
    13. import net.minecraft.server.EntityHuman;
    14. import net.minecraft.server.WorldServer;
    15. import net.minecraft.server.Chunk;
    16. /*
    17.  * @author Icyene
    18.  */
    19. public class BlockTickSelector {
    20.  
    21. private WorldServer world;
    22. private Method recheckGaps;
    23. private int chan;
    24. private final Random rand = new Random();
    25. public static double version;
    26.  
    27. public BlockTickSelector(World world, int selChance)
    28.  
    29. String v = getServer().getVersion(); //Get MC version. Reflection varies between 1.2 & 1.3
    30.  
    31. if (v.contains("1.2.")) {
    32.  
    33. version = 1.2;
    34.  
    35. getLogger().log(Level.INFO, "Loading with MC 1.2.X compatibility.");
    36.  
    37. } else {
    38.  
    39. if (v.contains("1.3.")) {
    40.  
    41. version = 1.3;
    42.  
    43. getLogger().log(Level.INFO, "Loading with MC 1.3.X compatibility.");
    44.  
    45. } else {
    46.  
    47. getLogger().log(Level.SEVERE, "Unsupported MC version detected!");
    48.  
    49. }
    50.  
    51. }
    52.  
    53. }
    54. this.world = ((CraftWorld) world).getHandle();
    55. recheckGaps = Chunk.class.getDeclaredMethod(version == 1.3 ? "k" : "o"); //If 1.3.X, method is named "k", else "o".
    56.  
    57. recheckGaps.setAccessible (
    58.  
    59.  
    60. true); //Is private by default
    61.  
    62. public ArrayList<ChunkCoordIntPair> getRandomTickedChunks() throws InvocationTargetException, IllegalAccessException {
    63.  
    64. ArrayList<ChunkCoordIntPair> doTick = new ArrayList<ChunkCoordIntPair>();
    65.  
    66. if (world.players.isEmpty()) {
    67.  
    68. return doTick;
    69.  
    70. }
    71.  
    72. List<org.bukkit.Chunk> loadedChunks = Arrays.asList(world.getWorld().getLoadedChunks());
    73.  
    74. for (Object ob : world.players) {
    75.  
    76. EntityHuman entityhuman = (EntityHuman) ob;
    77.  
    78. int eX = (int) Math.floor(entityhuman.locX / 16), eZ = (int) Math.floor(entityhuman.locZ / 16);
    79.  
    80. for (int x = -7; x <= 7; x++) {
    81.  
    82. for (int z = -7; z <= 7; z++) {
    83.  
    84. if (loadedChunks.contains(world.getChunkAt(x + eX, z + eZ).bukkitChunk)) { //Check if the bukkit chunk exists
    85.  
    86. doTick.add(new ChunkCoordIntPair(x + eX, z + eZ));
    87.  
    88. }
    89. }
    90. }
    91. }
    92.  
    93. return doTick; //Empty list = failure
    94.  
    95. }
    96.  
    97. public ArrayList<Block> getRandomTickedBlocks()
    98.  
    99. ArrayList<Block> doTick = new ArrayList<Block>();
    100.  
    101. ArrayList<ChunkCoordIntPair> ticked = getRandomTickedChunks();
    102.  
    103. if (ticked.isEmpty()) {
    104.  
    105. return doTick;
    106.  
    107. }
    108.  
    109. for (ChunkCoordIntPair pair : ticked) {
    110.  
    111. int xOffset = pair.x << 4, zOffset = pair.z << 4; //Multiply by 4, obviously.
    112.  
    113. Chunk chunk = world.getChunkAt(pair.x, pair.z);
    114.  
    115. recheckGaps.invoke(chunk); //Recheck gaps
    116.  
    117. for (int i = 0; i != 3; i++) {
    118. if (rand.nextInt(100) <= chan) {
    119. int x = rand.nextInt(15), z = rand.nextInt(15);
    120.  
    121. doTick.add(world.getWorld().getBlockAt(x + xOffset, world.g(x + xOffset, z + zOffset), z + zOffset));
    122.  
    123. }
    124. }
    125. }
    126.  
    127. return doTick;
    128.  
    129. }
    130. }
    131.  
     
  8. iKeirNez You can get rid of the trim():
    Code:java
    1. public String joinArgs(String[] args, int start)
    2. {
    3. if(args.length <= start)
    4. return "";
    5. StringBuilder sb = new StringBuilder(args[start]);
    6. for(start++; start < args.length; start++)
    7. sb.append(' ').append(args[start]);
    8. return sb.toString();
    9. }

    ;)
     
  9. Offline

    desht

    iKeirNez V10lator you can even do this:

    PHP:
    String allArgs Joiner.on(" ").join(args);
    (Joiner is from Google commons lib, which is included with Bukkit)
     
  10. Haha, thats so simple! I'll add that to the post but will also keep my version, if anyone isn't using this for Bukkit and do not want to use the Google Commons lib.

    Very nice! Also nice sig haha!

    Added!

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

    xiaomao

    This code have an extra space in the beginning. You need to change
    Code:
    return sb.toString();
    to
    Code:
    return sb.toString().substring(1);
    .
     
  12. Edited! Thanks!
     
  13. No it has not, it starts here:
    StringBuilder sb = new StringBuilder(args[start]);
    and as args[start] doesn't have a space at the beginning...
    No! Then you cut off the first character of the first word!
    Edit it back... ;)
     
  14. Sorry should've looked at it more, edited back!
     
  15. Offline

    xiaomao

    Sorry didn't see that.
     
    hawkfalcon likes this.
  16. Added ReplaceChatColors code!

    Posted a bunch of my own code snippets, enjoy :)

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

    chaseoes

    Bukkit has the ChatColor.replaceAlternateColorCodes (or something like that) method for replacing colors in a string.
     
  18. Offline

    Icyene

    But Bukkit comes with Apache Commons, so I don't see the point of making a method yourself instead of using the Apache Commons one.
     
  19. :0 didn't know that, thanks! :D

    Thanks, will look into it!
     
  20. Offline

    one4me

    That copyFile method may struggle with really big files.
    Also, anyone using Bukkit could easily use this instead:
    Code:
    Files.copy(File from, File to);
    
    As chaseoes said, anyone using Bukkit can translate colors like this instead:
    Code:
    ChatColor.translateAlternateColorCodes(char arg0, String arg1);
    
     
  21. Thanks, edited!
     
  22. Posted another one

    Delete Folder
    Author: iKeirNez
    Description: Deletes a folder and all its contents
    Code:
    Code:
    public static void deleteFolder(File folder){
            File[] files = folder.listFiles();
            if (files != null){
                for (File f : files){
                    if (f.isDirectory()){
                        deleteFolder(f);
                    } else {
                        f.delete();
                    }
                }
            }
           
            folder.delete();
        }
     
Thread Status:
Not open for further replies.

Share This Page