Utils.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package de.Linus122.TimeIsMoney.tools;
  2. import org.bukkit.Bukkit;
  3. import org.bukkit.ChatColor;
  4. import org.bukkit.entity.Player;
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7. /**
  8. * Utility class.
  9. *
  10. * @author Linus122
  11. * @since 1.9.6.1
  12. */
  13. public class Utils {
  14. /**
  15. * @throws RuntimeException utils class should not be instantiated.
  16. */
  17. public Utils() {
  18. throw new RuntimeException("Utils class should not be instantiated!");
  19. }
  20. /**
  21. * Converts &color to {@link org.bukkit.ChatColor}.
  22. *
  23. * @param s The string to convert to {@link org.bukkit.ChatColor}.
  24. * @return The converted string with {@link org.bukkit.ChatColor}.
  25. */
  26. public static String CC(String s) {
  27. // return an empty string if given string is null
  28. if(s == null) {
  29. return "";
  30. }
  31. return ChatColor.translateAlternateColorCodes('&', parseRGB(s));
  32. }
  33. public static String applyPlaceholders(Player player, String s) {
  34. if(Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
  35. s = me.clip.placeholderapi.PlaceholderAPI.setPlaceholders(player, s);
  36. }
  37. return s;
  38. }
  39. private static final Pattern rgbColor = Pattern.compile("(?<!\\\\)(&#[a-fA-F0-9]{6})");
  40. public static String parseRGB(String msg) {
  41. Matcher matcher = rgbColor.matcher(msg);
  42. while (matcher.find()) {
  43. String color = msg.substring(matcher.start(), matcher.end());
  44. String hex = color.replace("&", "");
  45. try {
  46. msg = msg.replace(color, String.valueOf(net.md_5.bungee.api.ChatColor.of(hex)));
  47. } catch(NoSuchMethodError e) {
  48. // older spigot versions
  49. msg = msg.replace(color, "");
  50. }
  51. matcher = rgbColor.matcher(msg);
  52. }
  53. return msg;
  54. }
  55. /**
  56. * Return the seconds of a time format, valid suffixes are s (seconds), m (minutes) and h (hours)
  57. * @param format the formatted time, examples: 10m, 8h, 30s.
  58. * @return converted seconds, invalid return -1
  59. */
  60. public static int parseTimeFormat(String format) {
  61. Pattern pattern = Pattern.compile("^(?:(\\d+)s|(\\d+)m|(\\d+)h)$");
  62. Matcher matcher = pattern.matcher(format);
  63. if (matcher.matches()) {
  64. String seconds = matcher.group(1);
  65. String minutes = matcher.group(2);
  66. String hours = matcher.group(3);
  67. if (seconds != null) {
  68. return Integer.parseInt(seconds);
  69. }
  70. if (minutes != null) {
  71. return Integer.parseInt(minutes) * 60;
  72. }
  73. if (hours != null) {
  74. return Integer.parseInt(hours) * 60 * 60;
  75. }
  76. }
  77. return -1;
  78. }
  79. }