2
0

Util.java 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /*
  2. * Copyright (C) 2004-2015 L2J Server
  3. *
  4. * This file is part of L2J Server.
  5. *
  6. * L2J Server is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * L2J Server is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.l2jserver.util;
  20. import java.io.File;
  21. import java.io.IOException;
  22. import java.io.PrintWriter;
  23. import java.io.StringWriter;
  24. import java.net.InetAddress;
  25. import java.net.UnknownHostException;
  26. import java.nio.ByteBuffer;
  27. import java.time.DayOfWeek;
  28. import java.time.LocalDateTime;
  29. import java.time.temporal.TemporalAdjusters;
  30. import java.util.Arrays;
  31. import java.util.Comparator;
  32. import java.util.List;
  33. import java.util.Map;
  34. import java.util.function.Function;
  35. import java.util.logging.Logger;
  36. /**
  37. * Useful utilities common to L2J Server.
  38. */
  39. public final class Util
  40. {
  41. private static final Logger _log = Logger.getLogger(Util.class.getName());
  42. private static final char[] ILLEGAL_CHARACTERS =
  43. {
  44. '/',
  45. '\n',
  46. '\r',
  47. '\t',
  48. '\0',
  49. '\f',
  50. '`',
  51. '?',
  52. '*',
  53. '\\',
  54. '<',
  55. '>',
  56. '|',
  57. '\"',
  58. ':'
  59. };
  60. /**
  61. * Checks if a host name is internal
  62. * @param host the host name to check
  63. * @return true: host name is internal<br>
  64. * false: host name is external
  65. */
  66. public static boolean isInternalHostname(String host)
  67. {
  68. try
  69. {
  70. InetAddress addr = InetAddress.getByName(host);
  71. return addr.isSiteLocalAddress() || addr.isLoopbackAddress();
  72. }
  73. catch (UnknownHostException e)
  74. {
  75. _log.warning("Util: " + e.getMessage());
  76. }
  77. return false;
  78. }
  79. /**
  80. * Method to generate the hexadecimal representation of a byte array.<br>
  81. * 16 bytes per row, while ascii chars or "." is shown at the end of the line.
  82. * @param data the byte array to be represented in hexadecimal representation
  83. * @param len the number of bytes to represent in hexadecimal representation
  84. * @return byte array represented in hexadecimal format
  85. */
  86. public static String printData(byte[] data, int len)
  87. {
  88. return new String(HexUtils.bArr2HexEdChars(data, len));
  89. }
  90. /**
  91. * This call is equivalent to Util.printData(data, data.length)
  92. * @see Util#printData(byte[],int)
  93. * @param data data to represent in hexadecimal
  94. * @return byte array represented in hexadecimal format
  95. */
  96. public static String printData(byte[] data)
  97. {
  98. return printData(data, data.length);
  99. }
  100. /**
  101. * Method to represent the remaining bytes of a ByteBuffer as hexadecimal
  102. * @param buf ByteBuffer to represent the remaining bytes of as hexadecimal
  103. * @return hexadecimal representation of remaining bytes of the ByteBuffer
  104. */
  105. public static String printData(ByteBuffer buf)
  106. {
  107. byte[] data = new byte[buf.remaining()];
  108. buf.get(data);
  109. String hex = Util.printData(data, data.length);
  110. buf.position(buf.position() - data.length);
  111. return hex;
  112. }
  113. /**
  114. * Method to generate a random sequence of bytes returned as byte array
  115. * @param size number of random bytes to generate
  116. * @return byte array with sequence of random bytes
  117. */
  118. public static byte[] generateHex(int size)
  119. {
  120. byte[] array = new byte[size];
  121. Rnd.nextBytes(array);
  122. return array;
  123. }
  124. /**
  125. * Method to get the stack trace of a Throwable into a String
  126. * @param t Throwable to get the stacktrace from
  127. * @return stack trace from Throwable as String
  128. */
  129. public static String getStackTrace(Throwable t)
  130. {
  131. StringWriter sw = new StringWriter();
  132. t.printStackTrace(new PrintWriter(sw));
  133. return sw.toString();
  134. }
  135. /**
  136. * Replaces most invalid characters for the given string with an underscore.
  137. * @param str the string that may contain invalid characters
  138. * @return the string with invalid character replaced by underscores
  139. */
  140. public static String replaceIllegalCharacters(String str)
  141. {
  142. String valid = str;
  143. for (char c : ILLEGAL_CHARACTERS)
  144. {
  145. valid = valid.replace(c, '_');
  146. }
  147. return valid;
  148. }
  149. /**
  150. * Verify if a file name is valid.
  151. * @param name the name of the file
  152. * @return {@code true} if the file name is valid, {@code false} otherwise
  153. */
  154. public static boolean isValidFileName(String name)
  155. {
  156. final File f = new File(name);
  157. try
  158. {
  159. f.getCanonicalPath();
  160. return true;
  161. }
  162. catch (IOException e)
  163. {
  164. return false;
  165. }
  166. }
  167. /**
  168. * Split words with a space.
  169. * @param input the string to split
  170. * @return the split string
  171. */
  172. public static String splitWords(String input)
  173. {
  174. return input.replaceAll("(\\p{Ll})(\\p{Lu})", "$1 $2");
  175. }
  176. /**
  177. * Gets the next or same closest date from the specified days in {@code daysOfWeek Array} at specified {@code hour} and {@code min}.
  178. * @param daysOfWeek the days of week
  179. * @param hour the hour
  180. * @param min the min
  181. * @return the next or same date from the days of week at specified time
  182. * @throws IllegalArgumentException if the {@code daysOfWeek Array} is empty.
  183. */
  184. public static LocalDateTime getNextClosestDateTime(DayOfWeek[] daysOfWeek, int hour, int min) throws IllegalArgumentException
  185. {
  186. return getNextClosestDateTime(Arrays.asList(daysOfWeek), hour, min);
  187. }
  188. /**
  189. * Gets the next or same closest date from the specified days in {@code daysOfWeek List} at specified {@code hour} and {@code min}.
  190. * @param daysOfWeek the days of week
  191. * @param hour the hour
  192. * @param min the min
  193. * @return the next or same date from the days of week at specified time
  194. * @throws IllegalArgumentException if the {@code daysOfWeek List} is empty.
  195. */
  196. public static LocalDateTime getNextClosestDateTime(List<DayOfWeek> daysOfWeek, int hour, int min) throws IllegalArgumentException
  197. {
  198. if (daysOfWeek.isEmpty())
  199. {
  200. throw new IllegalArgumentException("daysOfWeek should not be empty.");
  201. }
  202. final LocalDateTime dateNow = LocalDateTime.now();
  203. final LocalDateTime dateNowWithDifferentTime = dateNow.withHour(hour).withMinute(min).withSecond(0);
  204. // @formatter:off
  205. return daysOfWeek.stream()
  206. .map(d -> dateNowWithDifferentTime.with(TemporalAdjusters.nextOrSame(d)))
  207. .filter(d -> d.isAfter(dateNow))
  208. .min(Comparator.naturalOrder())
  209. .orElse(dateNowWithDifferentTime.with(TemporalAdjusters.next(daysOfWeek.get(0))));
  210. // @formatter:on
  211. }
  212. /**
  213. * This method translates map to function
  214. * @param <K> key type of the map and argument of the function
  215. * @param <V> value type of the map and return type of the function
  216. * @param map the input map
  217. * @return a function which returns map.get(arg)
  218. */
  219. public static <K, V> Function<K, V> mapToFunction(Map<K, V> map)
  220. {
  221. return key -> map.get(key);
  222. }
  223. }