Util.java 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. /*
  2. * Copyright (C) 2004-2014 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.logging.Logger;
  34. /**
  35. * Useful utilities common to L2J Server.
  36. */
  37. public final class Util
  38. {
  39. private static final Logger _log = Logger.getLogger(Util.class.getName());
  40. private static final char[] ILLEGAL_CHARACTERS =
  41. {
  42. '/',
  43. '\n',
  44. '\r',
  45. '\t',
  46. '\0',
  47. '\f',
  48. '`',
  49. '?',
  50. '*',
  51. '\\',
  52. '<',
  53. '>',
  54. '|',
  55. '\"',
  56. ':'
  57. };
  58. /**
  59. * Checks if a host name is internal
  60. * @param host the host name to check
  61. * @return true: host name is internal<br>
  62. * false: host name is external
  63. */
  64. public static boolean isInternalHostname(String host)
  65. {
  66. try
  67. {
  68. InetAddress addr = InetAddress.getByName(host);
  69. return addr.isSiteLocalAddress() || addr.isLoopbackAddress();
  70. }
  71. catch (UnknownHostException e)
  72. {
  73. _log.warning("Util: " + e.getMessage());
  74. }
  75. return false;
  76. }
  77. /**
  78. * Method to generate the hexadecimal representation of a byte array.<br>
  79. * 16 bytes per row, while ascii chars or "." is shown at the end of the line.
  80. * @param data the byte array to be represented in hexadecimal representation
  81. * @param len the number of bytes to represent in hexadecimal representation
  82. * @return byte array represented in hexadecimal format
  83. */
  84. public static String printData(byte[] data, int len)
  85. {
  86. return new String(HexUtils.bArr2HexEdChars(data, len));
  87. }
  88. /**
  89. * This call is equivalent to Util.printData(data, data.length)
  90. * @see Util#printData(byte[],int)
  91. * @param data data to represent in hexadecimal
  92. * @return byte array represented in hexadecimal format
  93. */
  94. public static String printData(byte[] data)
  95. {
  96. return printData(data, data.length);
  97. }
  98. /**
  99. * Method to represent the remaining bytes of a ByteBuffer as hexadecimal
  100. * @param buf ByteBuffer to represent the remaining bytes of as hexadecimal
  101. * @return hexadecimal representation of remaining bytes of the ByteBuffer
  102. */
  103. public static String printData(ByteBuffer buf)
  104. {
  105. byte[] data = new byte[buf.remaining()];
  106. buf.get(data);
  107. String hex = Util.printData(data, data.length);
  108. buf.position(buf.position() - data.length);
  109. return hex;
  110. }
  111. /**
  112. * Method to generate a random sequence of bytes returned as byte array
  113. * @param size number of random bytes to generate
  114. * @return byte array with sequence of random bytes
  115. */
  116. public static byte[] generateHex(int size)
  117. {
  118. byte[] array = new byte[size];
  119. Rnd.nextBytes(array);
  120. return array;
  121. }
  122. /**
  123. * Method to get the stack trace of a Throwable into a String
  124. * @param t Throwable to get the stacktrace from
  125. * @return stack trace from Throwable as String
  126. */
  127. public static String getStackTrace(Throwable t)
  128. {
  129. StringWriter sw = new StringWriter();
  130. t.printStackTrace(new PrintWriter(sw));
  131. return sw.toString();
  132. }
  133. /**
  134. * Replaces most invalid characters for the given string with an underscore.
  135. * @param str the string that may contain invalid characters
  136. * @return the string with invalid character replaced by underscores
  137. */
  138. public static String replaceIllegalCharacters(String str)
  139. {
  140. String valid = str;
  141. for (char c : ILLEGAL_CHARACTERS)
  142. {
  143. valid = valid.replace(c, '_');
  144. }
  145. return valid;
  146. }
  147. /**
  148. * Verify if a file name is valid.
  149. * @param name the name of the file
  150. * @return {@code true} if the file name is valid, {@code false} otherwise
  151. */
  152. public static boolean isValidFileName(String name)
  153. {
  154. final File f = new File(name);
  155. try
  156. {
  157. f.getCanonicalPath();
  158. return true;
  159. }
  160. catch (IOException e)
  161. {
  162. return false;
  163. }
  164. }
  165. /**
  166. * Split words with a space.
  167. * @param input the string to split
  168. * @return the split string
  169. */
  170. public static String splitWords(String input)
  171. {
  172. return input.replaceAll("(\\p{Ll})(\\p{Lu})", "$1 $2");
  173. }
  174. /**
  175. * Gets the next or same closest date from the specified days in {@code daysOfWeek Array} at specified {@code hour} and {@code min}.
  176. * @param daysOfWeek the days of week
  177. * @param hour the hour
  178. * @param min the min
  179. * @return the next or same date from the days of week at specified time
  180. * @throws IllegalArgumentException if the {@code daysOfWeek Array} is empty.
  181. */
  182. public static LocalDateTime getNextClosestDateTime(DayOfWeek[] daysOfWeek, int hour, int min) throws IllegalArgumentException
  183. {
  184. return getNextClosestDateTime(Arrays.asList(daysOfWeek), hour, min);
  185. }
  186. /**
  187. * Gets the next or same closest date from the specified days in {@code daysOfWeek List} at specified {@code hour} and {@code min}.
  188. * @param daysOfWeek the days of week
  189. * @param hour the hour
  190. * @param min the min
  191. * @return the next or same date from the days of week at specified time
  192. * @throws IllegalArgumentException if the {@code daysOfWeek List} is empty.
  193. */
  194. public static LocalDateTime getNextClosestDateTime(List<DayOfWeek> daysOfWeek, int hour, int min) throws IllegalArgumentException
  195. {
  196. if (daysOfWeek.isEmpty())
  197. {
  198. throw new IllegalArgumentException("daysOfWeek should not be empty.");
  199. }
  200. final LocalDateTime dateNow = LocalDateTime.now();
  201. final LocalDateTime dateNowWithDifferentTime = dateNow.withHour(hour).withMinute(min).withSecond(0);
  202. // @formatter:off
  203. return daysOfWeek.stream()
  204. .map(d -> dateNowWithDifferentTime.with(TemporalAdjusters.nextOrSame(d)))
  205. .filter(d -> d.isAfter(dateNow))
  206. .min(Comparator.naturalOrder())
  207. .orElse(dateNowWithDifferentTime.with(TemporalAdjusters.next(daysOfWeek.get(0))));
  208. // @formatter:on
  209. }
  210. }