PageRenderTime 89ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/src/uk/co/oliwali/HawkEye/util/Util.java

https://github.com/Lithixium/HawkEye
Java | 329 lines | 205 code | 29 blank | 95 comment | 53 complexity | be51842346e7b9f86fb2b97838ccebb9 MD5 | raw file
  1. package uk.co.oliwali.HawkEye.util;
  2. import java.io.BufferedOutputStream;
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.net.URL;
  9. import java.util.Collection;
  10. import java.util.Iterator;
  11. import java.util.logging.Logger;
  12. import org.bukkit.Location;
  13. import org.bukkit.command.CommandSender;
  14. import org.bukkit.entity.Chicken;
  15. import org.bukkit.entity.Cow;
  16. import org.bukkit.entity.Creeper;
  17. import org.bukkit.entity.Entity;
  18. import org.bukkit.entity.Ghast;
  19. import org.bukkit.entity.Giant;
  20. import org.bukkit.entity.Pig;
  21. import org.bukkit.entity.PigZombie;
  22. import org.bukkit.entity.Player;
  23. import org.bukkit.entity.Sheep;
  24. import org.bukkit.entity.Skeleton;
  25. import org.bukkit.entity.Slime;
  26. import org.bukkit.entity.Spider;
  27. import org.bukkit.entity.Squid;
  28. import org.bukkit.entity.Wolf;
  29. import org.bukkit.entity.Zombie;
  30. /**
  31. * Utility class for HawkEye.
  32. * All logging and messages should go through this class.
  33. * Contains methods for parsing strings, colours etc.
  34. * @author oliverw92
  35. */
  36. public class Util {
  37. private static final Logger log = Logger.getLogger("Minecraft");
  38. private static int maxLength = 105;
  39. /**
  40. * Send an info level log message to console
  41. * @param msg message to send
  42. */
  43. public static void info(String msg) {
  44. log.info("[HawkEye] " + msg);
  45. }
  46. /**
  47. * Send a warn level log message to console
  48. * @param msg message to send
  49. */
  50. public static void warning(String msg) {
  51. log.warning("[HawkEye] " + msg);
  52. }
  53. /**
  54. * Send a severe level log message to console
  55. * @param msg message to send
  56. */
  57. public static void severe(String msg) {
  58. log.severe("[HawkEye] " + msg);
  59. }
  60. /**
  61. * Send an debug message to console if debug is enabled
  62. * @param msg message to send
  63. */
  64. public static void debug(String msg) {
  65. if (Config.Debug)
  66. Util.info("DEBUG: " + msg);
  67. }
  68. /**
  69. * Deletes a file or directory
  70. * @param dir File to delete
  71. * @return true on success
  72. */
  73. public static boolean deleteFile(File file) {
  74. if (file.isDirectory()) {
  75. String[] children = file.list();
  76. for (int i=0; i<children.length; i++)
  77. if (!deleteFile(new File(file, children[i]))) return false;
  78. }
  79. return file.delete();
  80. }
  81. /**
  82. * Downloads a file from the internet
  83. * @param url URL of the file to download
  84. * @param file location where the file should be downloaded to
  85. * @throws IOException
  86. */
  87. public static void download(URL url, File file) throws IOException {
  88. if (!file.getParentFile().exists())
  89. file.getParentFile().mkdir();
  90. if (file.exists())
  91. file.delete();
  92. file.createNewFile();
  93. int size = url.openConnection().getContentLength();
  94. Util.info("Downloading " + file.getName() + " (" + size / 1024 + "kb) ...");
  95. InputStream in = url.openStream();
  96. OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
  97. byte[] buffer = new byte[1024];
  98. int len, downloaded = 0, msgs = 0;
  99. final long start = System.currentTimeMillis();
  100. while ((len = in.read(buffer)) >= 0) {
  101. out.write(buffer, 0, len);
  102. downloaded += len;
  103. if ((int)((System.currentTimeMillis() - start) / 500) > msgs) {
  104. Util.info((int)((double)downloaded / (double)size * 100d) + "%");
  105. msgs++;
  106. }
  107. }
  108. in.close();
  109. out.close();
  110. Util.info("Download finished");
  111. }
  112. /**
  113. * Send a message to a CommandSender (can be a player or console).
  114. * Has parsing built in for &a colours, as well as `n for new line
  115. * @param player sender to send to
  116. * @param msg message to send
  117. */
  118. public static void sendMessage(CommandSender player, String msg) {
  119. int i;
  120. String part;
  121. CustomColor lastColor = CustomColor.WHITE;
  122. for (String line : msg.split("`n")) {
  123. i = 0;
  124. while (i < line.length()) {
  125. part = getMaxString(line.substring(i));
  126. if (i+part.length() < line.length() && part.contains(" "))
  127. part = part.substring(0, part.lastIndexOf(" "));
  128. part = lastColor.getCustom() + part;
  129. player.sendMessage(replaceColors(part));
  130. lastColor = getLastColor(part);
  131. i = i + part.length() -1;
  132. }
  133. }
  134. }
  135. /**
  136. * Turns supplied location into a simplified (1 decimal point) version
  137. * @param location location to simplify
  138. * @return Location
  139. */
  140. public static Location getSimpleLocation(Location location) {
  141. location.setX((double)Math.round(location.getX() * 10) / 10);
  142. location.setY((double)Math.round(location.getY() * 10) / 10);
  143. location.setZ((double)Math.round(location.getZ() * 10) / 10);
  144. return location;
  145. }
  146. /**
  147. * Checks if inputted string is an integer
  148. * @param str string to check
  149. * @return true if an integer, false if not
  150. */
  151. public static boolean isInteger(String str) {
  152. try {
  153. Integer.parseInt(str);
  154. } catch (NumberFormatException e) {
  155. return false;
  156. }
  157. return true;
  158. }
  159. /**
  160. * Java version of PHP's join(array, delimiter)
  161. * Takes any kind of collection (List, HashMap etc)
  162. * @param s collection to be joined
  163. * @param delimiter string delimiter
  164. * @return String
  165. */
  166. public static String join(Collection<?> s, String delimiter) {
  167. StringBuffer buffer = new StringBuffer();
  168. Iterator<?> iter = s.iterator();
  169. while (iter.hasNext()) {
  170. buffer.append(iter.next());
  171. if (iter.hasNext())
  172. buffer.append(delimiter);
  173. }
  174. return buffer.toString();
  175. }
  176. /**
  177. * Returns the distance between two {Location}s
  178. * @param from
  179. * @param to
  180. * @return double
  181. **/
  182. public static double distance(Location from, Location to) {
  183. return Math.sqrt(Math.pow(from.getX() - to.getX(), 2) + Math.pow(from.getY() - to.getY(), 2) + Math.pow(from.getZ() - to.getZ(), 2));
  184. }
  185. /**
  186. * Strips colours from inputted string
  187. * @param str
  188. * @return string without colours
  189. */
  190. public static String stripColors(String str) {
  191. str = str.replaceAll("(?i)\u00A7[0-F]", "");
  192. str = str.replaceAll("(?i)&[0-F]", "");
  193. return str;
  194. }
  195. /**
  196. * Finds the last colour in the string
  197. * @param str
  198. * @return {@link CustomColor}
  199. */
  200. public static CustomColor getLastColor(String str) {
  201. int i = 0;
  202. CustomColor lastColor = CustomColor.WHITE;
  203. while (i < str.length()-2) {
  204. for (CustomColor color: CustomColor.values()) {
  205. if (str.substring(i, i+2).equalsIgnoreCase(color.getCustom()))
  206. lastColor = color;
  207. }
  208. i = i+1;
  209. }
  210. return lastColor;
  211. }
  212. /**
  213. * Replaces custom colours with actual colour values
  214. * @param str input
  215. * @return inputted string with proper colour values
  216. */
  217. public static String replaceColors(String str) {
  218. for (CustomColor color : CustomColor.values())
  219. str = str.replace(color.getCustom(), color.getString());
  220. return str;
  221. }
  222. /**
  223. * Finds the max length of the inputted string for outputting
  224. * @param str
  225. * @return the string in its longest possible form
  226. */
  227. private static String getMaxString(String str) {
  228. for (int i = 0; i < str.length(); i++) {
  229. if (stripColors(str.substring(0, i)).length() == maxLength) {
  230. if (stripColors(str.substring(i, i+1)) == "")
  231. return str.substring(0, i-1);
  232. else
  233. return str.substring(0, i);
  234. }
  235. }
  236. return str;
  237. }
  238. /**
  239. * Returns the name of the supplied entity
  240. * @param entity to get name of
  241. * @return String name
  242. */
  243. public static String getEntityName(Entity entity) {
  244. //Player
  245. if (entity instanceof Player) return ((Player) entity).getName();
  246. //Creature
  247. else if (entity instanceof Pig) return "Pig";
  248. else if (entity instanceof Cow) return "Cow";
  249. else if (entity instanceof Squid) return "Squid";
  250. else if (entity instanceof Sheep) return "Sheep";
  251. else if (entity instanceof Chicken) return "Chicken";
  252. else if (entity instanceof PigZombie) return "PigZombie";
  253. else if (entity instanceof Giant) return "Giant";
  254. else if (entity instanceof Zombie) return "Zombie";
  255. else if (entity instanceof Skeleton) return "Skeleton";
  256. else if (entity instanceof Spider) return "Spider";
  257. else if (entity instanceof Creeper) return "Creeper";
  258. else if (entity instanceof Ghast) return "Ghast";
  259. else if (entity instanceof Slime) return "Slime";
  260. else if (entity instanceof Wolf) return "Wolf";
  261. //Unknown
  262. else return "Unknown";
  263. }
  264. /**
  265. * Custom colour class.
  266. * Created to allow for easier colouring of text
  267. * @author oliverw92
  268. */
  269. public enum CustomColor {
  270. RED("c", 0xC),
  271. DARK_RED("4", 0x4),
  272. YELLOW("e", 0xE),
  273. GOLD("6", 0x6),
  274. GREEN("a", 0xA),
  275. DARK_GREEN("2", 0x2),
  276. TURQOISE("3", 0x3),
  277. AQUA("b", 0xB),
  278. DARK_AQUA("8", 0x8),
  279. BLUE("9", 0x9),
  280. DARK_BLUE("1", 0x1),
  281. LIGHT_PURPLE("d", 0xD),
  282. DARK_PURPLE("5", 0x5),
  283. BLACK("0", 0x0),
  284. DARK_GRAY("8", 0x8),
  285. GRAY("7", 0x7),
  286. WHITE("f", 0xf);
  287. private String custom;
  288. private int code;
  289. private CustomColor(String custom, int code) {
  290. this.custom = custom;
  291. this.code = code;
  292. }
  293. public String getCustom() {
  294. return "&" + custom;
  295. }
  296. public String getString() {
  297. return String.format("\u00A7%x", code);
  298. }
  299. }
  300. }