Util.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. /* Util.java -- Miscellaneous utility methods.
  2. Copyright (C) 2006 Free Software Foundation, Inc.
  3. This file is a part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or (at
  7. your option) any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; if not, write to the Free Software
  14. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
  15. USA
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package gnu.javax.net.ssl.provider;
  32. import gnu.java.lang.CPStringBuilder;
  33. import java.io.PrintWriter;
  34. import java.io.StringWriter;
  35. import java.lang.reflect.Array;
  36. import java.lang.reflect.InvocationTargetException;
  37. import java.lang.reflect.Method;
  38. import java.math.BigInteger;
  39. import java.nio.ByteBuffer;
  40. import java.security.AccessController;
  41. import java.security.PrivilegedAction;
  42. import java.security.Security;
  43. /**
  44. * A collection of useful class methods.
  45. *
  46. * @author Casey Marshall (rsdio@metastatic.org)
  47. */
  48. public final class Util
  49. {
  50. // Constants.
  51. // -------------------------------------------------------------------------
  52. static final String HEX = "0123456789abcdef";
  53. // Static methods only.
  54. private Util() { }
  55. // Class methods.
  56. // -------------------------------------------------------------------------
  57. public static Object wrapBuffer(ByteBuffer buffer)
  58. {
  59. return wrapBuffer(buffer, "");
  60. }
  61. public static Object wrapBuffer(ByteBuffer buffer, String prefix)
  62. {
  63. return new WrappedBuffer(buffer, prefix);
  64. }
  65. private static class WrappedBuffer
  66. {
  67. private final ByteBuffer buffer;
  68. private final String prefix;
  69. WrappedBuffer(ByteBuffer buffer, String prefix)
  70. {
  71. this.buffer = buffer;
  72. this.prefix = prefix;
  73. }
  74. public String toString()
  75. {
  76. return hexDump(buffer, prefix);
  77. }
  78. }
  79. /**
  80. * Convert a hexadecimal string into its byte representation.
  81. *
  82. * @param hex The hexadecimal string.
  83. * @return The converted bytes.
  84. */
  85. public static byte[] toByteArray(String hex)
  86. {
  87. hex = hex.toLowerCase();
  88. byte[] buf = new byte[hex.length() / 2];
  89. int j = 0;
  90. for (int i = 0; i < buf.length; i++)
  91. {
  92. buf[i] = (byte) ((Character.digit(hex.charAt(j++), 16) << 4) |
  93. Character.digit(hex.charAt(j++), 16));
  94. }
  95. return buf;
  96. }
  97. /**
  98. * Convert a byte array to a hexadecimal string, as though it were a
  99. * big-endian arbitrarily-sized integer.
  100. *
  101. * @param buf The bytes to format.
  102. * @param off The offset to start at.
  103. * @param len The number of bytes to format.
  104. * @return A hexadecimal representation of the specified bytes.
  105. */
  106. public static String toHexString(byte[] buf, int off, int len)
  107. {
  108. CPStringBuilder str = new CPStringBuilder();
  109. for (int i = 0; i < len; i++)
  110. {
  111. str.append(HEX.charAt(buf[i+off] >>> 4 & 0x0F));
  112. str.append(HEX.charAt(buf[i+off] & 0x0F));
  113. }
  114. return str.toString();
  115. }
  116. /**
  117. * See {@link #toHexString(byte[],int,int)}.
  118. */
  119. public static String toHexString(byte[] buf)
  120. {
  121. return Util.toHexString(buf, 0, buf.length);
  122. }
  123. /**
  124. * Convert a byte array to a hexadecimal string, separating octets
  125. * with the given character.
  126. *
  127. * @param buf The bytes to format.
  128. * @param off The offset to start at.
  129. * @param len The number of bytes to format.
  130. * @param sep The character to insert between octets.
  131. * @return A hexadecimal representation of the specified bytes.
  132. */
  133. public static String toHexString(byte[] buf, int off, int len, char sep)
  134. {
  135. CPStringBuilder str = new CPStringBuilder();
  136. for (int i = 0; i < len; i++)
  137. {
  138. str.append(HEX.charAt(buf[i+off] >>> 4 & 0x0F));
  139. str.append(HEX.charAt(buf[i+off] & 0x0F));
  140. if (i < len - 1)
  141. str.append(sep);
  142. }
  143. return str.toString();
  144. }
  145. /**
  146. * See {@link #toHexString(byte[],int,int,char)}.
  147. */
  148. public static String toHexString(byte[] buf, char sep)
  149. {
  150. return Util.toHexString(buf, 0, buf.length, sep);
  151. }
  152. /**
  153. * Create a representation of the given byte array similar to the
  154. * output of <code>`hexdump -C'</code>, which is
  155. *
  156. * <p><pre>OFFSET SIXTEEN-BYTES-IN-HEX PRINTABLE-BYTES</pre>
  157. *
  158. * <p>The printable bytes show up as-is if they are printable and
  159. * not a newline character, otherwise showing as '.'.
  160. *
  161. * @param buf The bytes to format.
  162. * @param off The offset to start at.
  163. * @param len The number of bytes to encode.
  164. * @param prefix A string to prepend to every line.
  165. * @return The formatted string.
  166. */
  167. public static String hexDump(byte[] buf, int off, int len, String prefix)
  168. {
  169. String nl = getProperty("line.separator");
  170. CPStringBuilder str = new CPStringBuilder();
  171. int i = 0;
  172. while (i < len)
  173. {
  174. if (prefix != null)
  175. str.append(prefix);
  176. str.append(Util.formatInt(i+off, 16, 8));
  177. str.append(" ");
  178. String s = Util.toHexString(buf, i+off, Math.min(16, len-i), ' ');
  179. str.append(s);
  180. for (int j = s.length(); j < 49; j++)
  181. str.append(" ");
  182. for (int j = 0; j < Math.min(16, len - i); j++)
  183. {
  184. if ((buf[i+off+j] & 0xFF) < 0x20 || (buf[i+off+j] & 0xFF) > 0x7E)
  185. str.append('.');
  186. else
  187. str.append((char) (buf[i+off+j] & 0xFF));
  188. }
  189. str.append(nl);
  190. i += 16;
  191. }
  192. return str.toString();
  193. }
  194. public static String hexDump (ByteBuffer buf)
  195. {
  196. return hexDump (buf, null);
  197. }
  198. public static String hexDump (ByteBuffer buf, String prefix)
  199. {
  200. buf = buf.duplicate();
  201. StringWriter str = new StringWriter ();
  202. PrintWriter out = new PrintWriter (str);
  203. int i = 0;
  204. int len = buf.remaining();
  205. byte[] line = new byte[16];
  206. while (i < len)
  207. {
  208. if (prefix != null)
  209. out.print(prefix);
  210. out.print(Util.formatInt (i, 16, 8));
  211. out.print(" ");
  212. int l = Math.min(16, len - i);
  213. buf.get(line, 0, l);
  214. String s = Util.toHexString(line, 0, l, ' ');
  215. out.print(s);
  216. for (int j = s.length(); j < 49; j++)
  217. out.print(' ');
  218. for (int j = 0; j < l; j++)
  219. {
  220. int c = line[j] & 0xFF;
  221. if (c < 0x20 || c > 0x7E)
  222. out.print('.');
  223. else
  224. out.print((char) c);
  225. }
  226. out.println();
  227. i += 16;
  228. }
  229. return str.toString();
  230. }
  231. /**
  232. * See {@link #hexDump(byte[],int,int,String)}.
  233. */
  234. public static String hexDump(byte[] buf, int off, int len)
  235. {
  236. return hexDump(buf, off, len, "");
  237. }
  238. /**
  239. * See {@link #hexDump(byte[],int,int,String)}.
  240. */
  241. public static String hexDump(byte[] buf, String prefix)
  242. {
  243. return hexDump(buf, 0, buf.length, prefix);
  244. }
  245. /**
  246. * See {@link #hexDump(byte[],int,int,String)}.
  247. */
  248. public static String hexDump(byte[] buf)
  249. {
  250. return hexDump(buf, 0, buf.length);
  251. }
  252. /**
  253. * Format an integer into the specified radix, zero-filled.
  254. *
  255. * @param i The integer to format.
  256. * @param radix The radix to encode to.
  257. * @param len The target length of the string. The string is
  258. * zero-padded to this length, but may be longer.
  259. * @return The formatted integer.
  260. */
  261. public static String formatInt(int i, int radix, int len)
  262. {
  263. String s = Integer.toString(i, radix);
  264. CPStringBuilder buf = new CPStringBuilder();
  265. for (int j = 0; j < len - s.length(); j++)
  266. buf.append("0");
  267. buf.append(s);
  268. return buf.toString();
  269. }
  270. /**
  271. * Concatenate two byte arrays into one.
  272. *
  273. * @param b1 The first byte array.
  274. * @param b2 The second byte array.
  275. * @return The concatenation of b1 and b2.
  276. */
  277. public static byte[] concat(byte[] b1, byte[] b2)
  278. {
  279. byte[] b3 = new byte[b1.length+b2.length];
  280. System.arraycopy(b1, 0, b3, 0, b1.length);
  281. System.arraycopy(b2, 0, b3, b1.length, b2.length);
  282. return b3;
  283. }
  284. /**
  285. * See {@link #trim(byte[],int,int)}.
  286. */
  287. public static byte[] trim(byte[] buffer, int len)
  288. {
  289. return trim(buffer, 0, len);
  290. }
  291. /**
  292. * Returns a portion of a byte array, possibly zero-filled.
  293. *
  294. * @param buffer The byte array to trim.
  295. * @param off The offset to begin reading at.
  296. * @param len The number of bytes to return. This value can be larger
  297. * than <i>buffer.length - off</i>, in which case the rest of the
  298. * returned byte array will be filled with zeros.
  299. * @throws IndexOutOfBoundsException If <i>off</i> or <i>len</i> is
  300. * negative, or if <i>off</i> is larger than the byte array's
  301. * length.
  302. * @return The trimmed byte array.
  303. */
  304. public static byte[] trim(byte[] buffer, int off, int len)
  305. {
  306. if (off < 0 || len < 0 || off > buffer.length)
  307. throw new IndexOutOfBoundsException("max=" + buffer.length +
  308. " off=" + off + " len=" + len);
  309. if (off == 0 && len == buffer.length)
  310. return buffer;
  311. byte[] b = new byte[len];
  312. System.arraycopy(buffer, off, b, 0, Math.min(len, buffer.length - off));
  313. return b;
  314. }
  315. /**
  316. * Returns the byte array representation of the given big integer with
  317. * the leading zero byte (if any) trimmed off.
  318. *
  319. * @param bi The integer to trim.
  320. * @return The byte representation of the big integer, with any leading
  321. * zero removed.
  322. */
  323. public static byte[] trim(BigInteger bi)
  324. {
  325. byte[] buf = bi.toByteArray();
  326. if (buf[0] == 0x00 && !bi.equals(BigInteger.ZERO))
  327. {
  328. return trim(buf, 1, buf.length - 1);
  329. }
  330. else
  331. {
  332. return buf;
  333. }
  334. }
  335. /**
  336. * Returns the integer value of <code>{@link
  337. * java.lang.System#currentTimeMillis()} / 1000</code>.
  338. *
  339. * @return The current time, in seconds.
  340. */
  341. public static int unixTime()
  342. {
  343. return (int) (System.currentTimeMillis() / 1000L);
  344. }
  345. /**
  346. * Transform an Object array into another by calling the given method
  347. * on each object. The returned object array will have the runtime
  348. * type of <i>returnType</i>. For example, the following will transform
  349. * array of objects into their String representations, returning a String
  350. * array. For example:
  351. *
  352. * <blockquote><p><code>
  353. * String[] strings = (String[]) Util.transform(array, String.class,
  354. * "toString", null);
  355. * </code></p></blockquote>
  356. *
  357. * <p>If any element of the given array is <tt>null</tt>, then that
  358. * entry in the returned array will also be <tt>null</tt>.
  359. *
  360. * @param array The array to transform. It does not need to be of
  361. * uniform type.
  362. * @param returnType The desired return type of the returned array.
  363. * This must by the <i>component</i> type, not the array type.
  364. * @param method The name of the method to invoke from each object.
  365. * @param args The arguments to pass to the method, or <tt>null</tt>
  366. * if the method takes no arguments.
  367. * @throws InvocationTargetException If an exception occurs while
  368. * calling <i>method</i> of any object.
  369. * @throws NoSuchMethodException If <i>method</i> is not the name of
  370. * a valid method of any component of the array.
  371. * @throws ClassCastException If the returned object from the method
  372. * is not assignable to the return type.
  373. * @throws IllegalArgumentException If <i>args</i> is not appropriate
  374. * for <i>method</i>
  375. * @throws IllegalAccessException If <i>method</i> is not accessible.
  376. * @throws SecurityException If <i>method</i> is not accessible.
  377. * @return An array containing the output of <i>method</i> called on
  378. * each element of <i>array</i> with <i>args</i>. The return type
  379. * of the array will be an array of <i>returnType</i>.
  380. */
  381. static Object[] transform(Object[] array, Class returnType,
  382. String method, Object[] args)
  383. throws InvocationTargetException, NoSuchMethodException,
  384. IllegalAccessException
  385. {
  386. if (args == null)
  387. args = new Object[0];
  388. Object[] result = (Object[]) Array.newInstance(returnType, array.length);
  389. Class[] argsClasses = new Class[args.length];
  390. for (int i = 0; i < args.length; i++)
  391. {
  392. argsClasses[i] = args[i].getClass();
  393. }
  394. for (int i = 0; i < array.length; i++)
  395. {
  396. if (array[i] == null)
  397. {
  398. result[i] = null;
  399. continue;
  400. }
  401. Class objClass = array[i].getClass();
  402. Method objMethod = objClass.getMethod(method, argsClasses);
  403. Object o = objMethod.invoke(array[i], args);
  404. if (!returnType.isAssignableFrom(o.getClass()))
  405. throw new ClassCastException();
  406. result[i] = o;
  407. }
  408. return result;
  409. }
  410. /**
  411. * Get a system property as a privileged action.
  412. *
  413. * @param name The name of the property to get.
  414. * @return The property named <i>name</i>, or null if the property is
  415. * not set.
  416. * @throws SecurityException If the Jessie code still does not have
  417. * permission to read the property.
  418. */
  419. @Deprecated static String getProperty(final String name)
  420. {
  421. return (String) AccessController.doPrivileged(
  422. new PrivilegedAction()
  423. {
  424. public Object run()
  425. {
  426. return System.getProperty(name);
  427. }
  428. }
  429. );
  430. }
  431. /**
  432. * Get a security property as a privileged action.
  433. *
  434. * @param name The name of the property to get.
  435. * @return The property named <i>name</i>, or null if the property is
  436. * not set.
  437. * @throws SecurityException If the Jessie code still does not have
  438. * permission to read the property.
  439. */
  440. @Deprecated static String getSecurityProperty(final String name)
  441. {
  442. return (String) AccessController.doPrivileged(
  443. new PrivilegedAction()
  444. {
  445. public Object run()
  446. {
  447. return Security.getProperty(name);
  448. }
  449. }
  450. );
  451. }
  452. }