You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507
  1. /* *******************************************************************
  2. * Copyright (c) 1999-2001 Xerox Corporation,
  3. * 2002 Palo Alto Research Center, Incorporated (PARC).
  4. * 2018 Contributors
  5. * All rights reserved.
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Public License v1.0
  8. * which accompanies this distribution and is available at
  9. * http://www.eclipse.org/legal/epl-v10.html
  10. *
  11. * Contributors:
  12. * Xerox/PARC initial implementation
  13. * ******************************************************************/
  14. package org.aspectj.util;
  15. import java.io.ByteArrayOutputStream;
  16. import java.io.File;
  17. import java.io.IOException;
  18. import java.io.PrintWriter;
  19. import java.io.StringWriter;
  20. import java.lang.reflect.Array;
  21. import java.lang.reflect.InvocationTargetException;
  22. import java.security.PrivilegedActionException;
  23. import java.sql.SQLException;
  24. import java.util.ArrayList;
  25. import java.util.Arrays;
  26. import java.util.BitSet;
  27. import java.util.Collection;
  28. import java.util.Collections;
  29. import java.util.LinkedList;
  30. import java.util.List;
  31. import java.util.Map;
  32. import java.util.StringTokenizer;
  33. /**
  34. *
  35. */
  36. public class LangUtil {
  37. public static final String EOL;
  38. public static final String JRT_FS = "jrt-fs.jar";
  39. private static double vmVersion;
  40. /**
  41. * @return the vm version (1.1, 1.2, 1.3, 1.4, etc)
  42. */
  43. public static String getVmVersionString() {
  44. return Double.toString(vmVersion);
  45. }
  46. public static double getVmVersion() {
  47. return vmVersion;
  48. }
  49. static {
  50. StringWriter buf = new StringWriter();
  51. PrintWriter writer = new PrintWriter(buf);
  52. writer.println("");
  53. String eol = "\n";
  54. try {
  55. buf.close();
  56. StringBuffer sb = buf.getBuffer();
  57. if (sb != null) {
  58. eol = buf.toString();
  59. }
  60. } catch (Throwable t) {
  61. }
  62. EOL = eol;
  63. }
  64. static {
  65. // http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html
  66. // http://openjdk.java.net/jeps/223 "New Version-String Scheme"
  67. try {
  68. String vm = System.getProperty("java.version"); // JLS 20.18.7
  69. if (vm == null) {
  70. vm = System.getProperty("java.runtime.version");
  71. }
  72. if (vm == null) {
  73. vm = System.getProperty("java.vm.version");
  74. }
  75. if (vm == null) {
  76. new RuntimeException(
  77. "System properties appear damaged, cannot find: java.version/java.runtime.version/java.vm.version")
  78. .printStackTrace(System.err);
  79. vmVersion = 1.5;
  80. } else {
  81. // Version: [1-9][0-9]*((\.0)*\.[1-9][0-9]*)*
  82. // Care about the first set of digits and second set if first digit is 1
  83. try {
  84. List<Integer> numbers = getFirstNumbers(vm);
  85. if (numbers.get(0) == 1) {
  86. // Old school for 1.0 > 1.8
  87. vmVersion = numbers.get(0)+(numbers.get(1)/10d);
  88. } else {
  89. // numbers.get(0) is the major version (9 and above)
  90. // Note here the number will be 9 (or 10), *not* 1.9 or 1.10
  91. vmVersion = numbers.get(0);
  92. }
  93. } catch (Throwable t) {
  94. // Give up
  95. vmVersion = 1.5;
  96. }
  97. }
  98. } catch (Throwable t) {
  99. new RuntimeException(
  100. "System properties appear damaged, cannot find: java.version/java.runtime.version/java.vm.version", t)
  101. .printStackTrace(System.err);
  102. vmVersion = 1.5;
  103. }
  104. }
  105. private static List<Integer> getFirstNumbers(String vm) {
  106. List<Integer> result = new ArrayList<Integer>();
  107. StringTokenizer st = new StringTokenizer(vm,".-_");
  108. try {
  109. result.add(Integer.parseInt(st.nextToken()));
  110. result.add(Integer.parseInt(st.nextToken()));
  111. } catch (Exception e) {
  112. // NoSuchElementException if no more tokens
  113. // NumberFormatException if not a number
  114. }
  115. return result;
  116. }
  117. public static boolean is13VMOrGreater() {
  118. return 1.3 <= vmVersion;
  119. }
  120. public static boolean is14VMOrGreater() {
  121. return 1.4 <= vmVersion;
  122. }
  123. public static boolean is15VMOrGreater() {
  124. return 1.5 <= vmVersion;
  125. }
  126. public static boolean is16VMOrGreater() {
  127. return 1.6 <= vmVersion;
  128. }
  129. public static boolean is17VMOrGreater() {
  130. return 1.7 <= vmVersion;
  131. }
  132. public static boolean is18VMOrGreater() {
  133. return 1.8 <= vmVersion;
  134. }
  135. public static boolean is19VMOrGreater() {
  136. return 9 <= vmVersion;
  137. }
  138. public static boolean is10VMOrGreater() {
  139. return 10 <= vmVersion;
  140. }
  141. /**
  142. * Shorthand for "if null, throw IllegalArgumentException"
  143. *
  144. * @throws IllegalArgumentException "null {name}" if o is null
  145. */
  146. public static final void throwIaxIfNull(final Object o, final String name) {
  147. if (null == o) {
  148. String message = "null " + (null == name ? "input" : name);
  149. throw new IllegalArgumentException(message);
  150. }
  151. }
  152. /**
  153. * Shorthand for "if not null or not assignable, throw IllegalArgumentException"
  154. *
  155. * @param c the Class to check - use null to ignore type check
  156. * @throws IllegalArgumentException "null {name}" if o is null
  157. */
  158. public static final void throwIaxIfNotAssignable(final Object ra[], final Class<?> c, final String name) {
  159. throwIaxIfNull(ra, name);
  160. String label = (null == name ? "input" : name);
  161. for (int i = 0; i < ra.length; i++) {
  162. if (null == ra[i]) {
  163. String m = " null " + label + "[" + i + "]";
  164. throw new IllegalArgumentException(m);
  165. } else if (null != c) {
  166. Class<?> actualClass = ra[i].getClass();
  167. if (!c.isAssignableFrom(actualClass)) {
  168. String message = label + " not assignable to " + c.getName();
  169. throw new IllegalArgumentException(message);
  170. }
  171. }
  172. }
  173. }
  174. /**
  175. * Shorthand for "if not null or not assignable, throw IllegalArgumentException"
  176. *
  177. * @throws IllegalArgumentException "null {name}" if o is null
  178. */
  179. public static final void throwIaxIfNotAssignable(final Object o, final Class<?> c, final String name) {
  180. throwIaxIfNull(o, name);
  181. if (null != c) {
  182. Class<?> actualClass = o.getClass();
  183. if (!c.isAssignableFrom(actualClass)) {
  184. String message = name + " not assignable to " + c.getName();
  185. throw new IllegalArgumentException(message);
  186. }
  187. }
  188. }
  189. // /**
  190. // * Shorthand for
  191. // "if any not null or not assignable, throw IllegalArgumentException"
  192. // * @throws IllegalArgumentException "{name} is not assignable to {c}"
  193. // */
  194. // public static final void throwIaxIfNotAllAssignable(final Collection
  195. // collection,
  196. // final Class c, final String name) {
  197. // throwIaxIfNull(collection, name);
  198. // if (null != c) {
  199. // for (Iterator iter = collection.iterator(); iter.hasNext();) {
  200. // throwIaxIfNotAssignable(iter.next(), c, name);
  201. //
  202. // }
  203. // }
  204. // }
  205. /**
  206. * Shorthand for "if false, throw IllegalArgumentException"
  207. *
  208. * @throws IllegalArgumentException "{message}" if test is false
  209. */
  210. public static final void throwIaxIfFalse(final boolean test, final String message) {
  211. if (!test) {
  212. throw new IllegalArgumentException(message);
  213. }
  214. }
  215. // /** @return ((null == s) || (0 == s.trim().length())); */
  216. // public static boolean isEmptyTrimmed(String s) {
  217. // return ((null == s) || (0 == s.length())
  218. // || (0 == s.trim().length()));
  219. // }
  220. /** @return ((null == s) || (0 == s.length())); */
  221. public static boolean isEmpty(String s) {
  222. return ((null == s) || (0 == s.length()));
  223. }
  224. /** @return ((null == ra) || (0 == ra.length)) */
  225. public static boolean isEmpty(Object[] ra) {
  226. return ((null == ra) || (0 == ra.length));
  227. }
  228. /** @return ((null == ra) || (0 == ra.length)) */
  229. public static boolean isEmpty(byte[] ra) {
  230. return ((null == ra) || (0 == ra.length));
  231. }
  232. /** @return ((null == collection) || (0 == collection.size())) */
  233. public static boolean isEmpty(Collection<?> collection) {
  234. return ((null == collection) || (0 == collection.size()));
  235. }
  236. /** @return ((null == map) || (0 == map.size())) */
  237. public static boolean isEmpty(Map<?,?> map) {
  238. return ((null == map) || (0 == map.size()));
  239. }
  240. /**
  241. * Splits <code>text</code> at whitespace.
  242. *
  243. * @param text <code>String</code> to split.
  244. */
  245. public static String[] split(String text) {
  246. return strings(text).toArray(new String[0]);
  247. }
  248. /**
  249. * Splits <code>input</code> at commas, trimming any white space.
  250. *
  251. * @param input <code>String</code> to split.
  252. * @return List of String of elements.
  253. */
  254. public static List<String> commaSplit(String input) {
  255. return anySplit(input, ",");
  256. }
  257. /**
  258. * Split string as classpath, delimited at File.pathSeparator. Entries are not trimmed, but empty entries are ignored.
  259. *
  260. * @param classpath the String to split - may be null or empty
  261. * @return String[] of classpath entries
  262. */
  263. public static String[] splitClasspath(String classpath) {
  264. if (LangUtil.isEmpty(classpath)) {
  265. return new String[0];
  266. }
  267. StringTokenizer st = new StringTokenizer(classpath, File.pathSeparator);
  268. ArrayList<String> result = new ArrayList<String>(st.countTokens());
  269. while (st.hasMoreTokens()) {
  270. String entry = st.nextToken();
  271. if (!LangUtil.isEmpty(entry)) {
  272. result.add(entry);
  273. }
  274. }
  275. return result.toArray(new String[0]);
  276. }
  277. /**
  278. * Get System property as boolean, but use default value where the system property is not set.
  279. *
  280. * @return true if value is set to true, false otherwise
  281. */
  282. public static boolean getBoolean(String propertyName, boolean defaultValue) {
  283. if (null != propertyName) {
  284. try {
  285. String value = System.getProperty(propertyName);
  286. if (null != value) {
  287. return Boolean.valueOf(value).booleanValue();
  288. }
  289. } catch (Throwable t) {
  290. // default below
  291. }
  292. }
  293. return defaultValue;
  294. }
  295. /**
  296. * Splits <code>input</code>, removing delimiter and trimming any white space. Returns an empty collection if the input is null.
  297. * If delimiter is null or empty or if the input contains no delimiters, the input itself is returned after trimming white
  298. * space.
  299. *
  300. * @param input <code>String</code> to split.
  301. * @param delim <code>String</code> separators for input.
  302. * @return List of String of elements.
  303. */
  304. public static List<String> anySplit(String input, String delim) {
  305. if (null == input) {
  306. return Collections.emptyList();
  307. }
  308. ArrayList<String> result = new ArrayList<String>();
  309. if (LangUtil.isEmpty(delim) || (-1 == input.indexOf(delim))) {
  310. result.add(input.trim());
  311. } else {
  312. StringTokenizer st = new StringTokenizer(input, delim);
  313. while (st.hasMoreTokens()) {
  314. result.add(st.nextToken().trim());
  315. }
  316. }
  317. return result;
  318. }
  319. /**
  320. * Splits strings into a <code>List</code> using a <code>StringTokenizer</code>.
  321. *
  322. * @param text <code>String</code> to split.
  323. */
  324. public static List<String> strings(String text) {
  325. if (LangUtil.isEmpty(text)) {
  326. return Collections.emptyList();
  327. }
  328. List<String> strings = new ArrayList<String>();
  329. StringTokenizer tok = new StringTokenizer(text);
  330. while (tok.hasMoreTokens()) {
  331. strings.add(tok.nextToken());
  332. }
  333. return strings;
  334. }
  335. /** @return a non-null unmodifiable List */
  336. public static <T> List<T> safeList(List<T> list) {
  337. return (null == list ? Collections.<T>emptyList() : Collections.unmodifiableList(list));
  338. }
  339. // /**
  340. // * Select from input String[] based on suffix-matching
  341. // * @param inputs String[] of input - null ignored
  342. // * @param suffixes String[] of suffix selectors - null ignored
  343. // * @param ignoreCase if true, ignore case
  344. // * @return String[] of input that end with any input
  345. // */
  346. // public static String[] endsWith(String[] inputs, String[] suffixes,
  347. // boolean ignoreCase) {
  348. // if (LangUtil.isEmpty(inputs) || LangUtil.isEmpty(suffixes)) {
  349. // return new String[0];
  350. // }
  351. // if (ignoreCase) {
  352. // String[] temp = new String[suffixes.length];
  353. // for (int i = 0; i < temp.length; i++) {
  354. // String suff = suffixes[i];
  355. // temp[i] = (null == suff ? null : suff.toLowerCase());
  356. // }
  357. // suffixes = temp;
  358. // }
  359. // ArrayList result = new ArrayList();
  360. // for (int i = 0; i < inputs.length; i++) {
  361. // String input = inputs[i];
  362. // if (null == input) {
  363. // continue;
  364. // }
  365. // if (!ignoreCase) {
  366. // input = input.toLowerCase();
  367. // }
  368. // for (int j = 0; j < suffixes.length; j++) {
  369. // String suffix = suffixes[j];
  370. // if (null == suffix) {
  371. // continue;
  372. // }
  373. // if (input.endsWith(suffix)) {
  374. // result.add(input);
  375. // break;
  376. // }
  377. // }
  378. // }
  379. // return (String[]) result.toArray(new String[0]);
  380. // }
  381. //
  382. // /**
  383. // * Select from input String[] if readable directories
  384. // * @param inputs String[] of input - null ignored
  385. // * @param baseDir the base directory of the input
  386. // * @return String[] of input that end with any input
  387. // */
  388. // public static String[] selectDirectories(String[] inputs, File baseDir) {
  389. // if (LangUtil.isEmpty(inputs)) {
  390. // return new String[0];
  391. // }
  392. // ArrayList result = new ArrayList();
  393. // for (int i = 0; i < inputs.length; i++) {
  394. // String input = inputs[i];
  395. // if (null == input) {
  396. // continue;
  397. // }
  398. // File inputFile = new File(baseDir, input);
  399. // if (inputFile.canRead() && inputFile.isDirectory()) {
  400. // result.add(input);
  401. // }
  402. // }
  403. // return (String[]) result.toArray(new String[0]);
  404. // }
  405. /**
  406. * copy non-null two-dimensional String[][]
  407. *
  408. * @see extractOptions(String[], String[][])
  409. */
  410. public static String[][] copyStrings(String[][] in) {
  411. String[][] out = new String[in.length][];
  412. for (int i = 0; i < out.length; i++) {
  413. out[i] = new String[in[i].length];
  414. System.arraycopy(in[i], 0, out[i], 0, out[i].length);
  415. }
  416. return out;
  417. }
  418. /**
  419. * Extract options and arguments to input option list, returning remainder. The input options will be nullified if not found.
  420. * e.g.,
  421. *
  422. * <pre>
  423. * String[] options = new String[][] { new String[] { &quot;-verbose&quot; }, new String[] { &quot;-classpath&quot;, null } };
  424. * String[] args = extractOptions(args, options);
  425. * boolean verbose = null != options[0][0];
  426. * boolean classpath = options[1][1];
  427. * </pre>
  428. *
  429. * @param args the String[] input options
  430. * @param options the String[][]options to find in the input args - not null for each String[] component the first subcomponent
  431. * is the option itself, and there is one String subcomponent for each additional argument.
  432. * @return String[] of args remaining after extracting options to extracted
  433. */
  434. public static String[] extractOptions(String[] args, String[][] options) {
  435. if (LangUtil.isEmpty(args) || LangUtil.isEmpty(options)) {
  436. return args;
  437. }
  438. BitSet foundSet = new BitSet();
  439. String[] result = new String[args.length];
  440. int resultIndex = 0;
  441. for (int j = 0; j < args.length; j++) {
  442. boolean found = false;
  443. for (int i = 0; !found && (i < options.length); i++) {
  444. String[] option = options[i];
  445. LangUtil.throwIaxIfFalse(!LangUtil.isEmpty(option), "options");
  446. String sought = option[0];
  447. found = sought.equals(args[j]);
  448. if (found) {
  449. foundSet.set(i);
  450. int doMore = option.length - 1;
  451. if (0 < doMore) {
  452. final int MAX = j + doMore;
  453. if (MAX >= args.length) {
  454. String s = "expecting " + doMore + " args after ";
  455. throw new IllegalArgumentException(s + args[j]);
  456. }
  457. for (int k = 1; k < option.length; k++) {
  458. option[k] = args[++j];
  459. }
  460. }
  461. }
  462. }
  463. if (!found) {
  464. result[resultIndex++] = args[j];
  465. }
  466. }
  467. // unset any not found
  468. for (int i = 0; i < options.length; i++) {
  469. if (!foundSet.get(i)) {
  470. options[i][0] = null;
  471. }
  472. }
  473. // fixup remainder
  474. if (resultIndex < args.length) {
  475. String[] temp = new String[resultIndex];
  476. System.arraycopy(result, 0, temp, 0, resultIndex);
  477. args = temp;
  478. }
  479. return args;
  480. }
  481. //
  482. // /**
  483. // * Extract options and arguments to input parameter list, returning
  484. // remainder.
  485. // * @param args the String[] input options
  486. // * @param validOptions the String[] options to find in the input args -
  487. // not null
  488. // * @param optionArgs the int[] number of arguments for each option in
  489. // validOptions
  490. // * (if null, then no arguments for any option)
  491. // * @param extracted the List for the matched options
  492. // * @return String[] of args remaining after extracting options to
  493. // extracted
  494. // */
  495. // public static String[] extractOptions(String[] args, String[]
  496. // validOptions,
  497. // int[] optionArgs, List extracted) {
  498. // if (LangUtil.isEmpty(args)
  499. // || LangUtil.isEmpty(validOptions) ) {
  500. // return args;
  501. // }
  502. // if (null != optionArgs) {
  503. // if (optionArgs.length != validOptions.length) {
  504. // throw new IllegalArgumentException("args must match options");
  505. // }
  506. // }
  507. // String[] result = new String[args.length];
  508. // int resultIndex = 0;
  509. // for (int j = 0; j < args.length; j++) {
  510. // boolean found = false;
  511. // for (int i = 0; !found && (i < validOptions.length); i++) {
  512. // String sought = validOptions[i];
  513. // int doMore = (null == optionArgs ? 0 : optionArgs[i]);
  514. // if (LangUtil.isEmpty(sought)) {
  515. // continue;
  516. // }
  517. // found = sought.equals(args[j]);
  518. // if (found) {
  519. // if (null != extracted) {
  520. // extracted.add(sought);
  521. // }
  522. // if (0 < doMore) {
  523. // final int MAX = j + doMore;
  524. // if (MAX >= args.length) {
  525. // String s = "expecting " + doMore + " args after ";
  526. // throw new IllegalArgumentException(s + args[j]);
  527. // }
  528. // if (null != extracted) {
  529. // while (j < MAX) {
  530. // extracted.add(args[++j]);
  531. // }
  532. // } else {
  533. // j = MAX;
  534. // }
  535. // }
  536. // break;
  537. // }
  538. // }
  539. // if (!found) {
  540. // result[resultIndex++] = args[j];
  541. // }
  542. // }
  543. // if (resultIndex < args.length) {
  544. // String[] temp = new String[resultIndex];
  545. // System.arraycopy(result, 0, temp, 0, resultIndex);
  546. // args = temp;
  547. // }
  548. // return args;
  549. // }
  550. // /** @return String[] of entries in validOptions found in args */
  551. // public static String[] selectOptions(String[] args, String[]
  552. // validOptions) {
  553. // if (LangUtil.isEmpty(args) || LangUtil.isEmpty(validOptions)) {
  554. // return new String[0];
  555. // }
  556. // ArrayList result = new ArrayList();
  557. // for (int i = 0; i < validOptions.length; i++) {
  558. // String sought = validOptions[i];
  559. // if (LangUtil.isEmpty(sought)) {
  560. // continue;
  561. // }
  562. // for (int j = 0; j < args.length; j++) {
  563. // if (sought.equals(args[j])) {
  564. // result.add(sought);
  565. // break;
  566. // }
  567. // }
  568. // }
  569. // return (String[]) result.toArray(new String[0]);
  570. // }
  571. // /** @return String[] of entries in validOptions found in args */
  572. // public static String[] selectOptions(List args, String[] validOptions) {
  573. // if (LangUtil.isEmpty(args) || LangUtil.isEmpty(validOptions)) {
  574. // return new String[0];
  575. // }
  576. // ArrayList result = new ArrayList();
  577. // for (int i = 0; i < validOptions.length; i++) {
  578. // String sought = validOptions[i];
  579. // if (LangUtil.isEmpty(sought)) {
  580. // continue;
  581. // }
  582. // for (Iterator iter = args.iterator(); iter.hasNext();) {
  583. // String arg = (String) iter.next();
  584. // if (sought.equals(arg)) {
  585. // result.add(sought);
  586. // break;
  587. // }
  588. // }
  589. // }
  590. // return (String[]) result.toArray(new String[0]);
  591. // }
  592. // /**
  593. // * Generate variants of String[] options by creating an extra set for
  594. // * each option that ends with "-". If none end with "-", then an
  595. // * array equal to <code>new String[][] { options }</code> is returned;
  596. // * if one ends with "-", then two sets are returned,
  597. // * three causes eight sets, etc.
  598. // * @return String[][] with each option set.
  599. // * @throws IllegalArgumentException if any option is null or empty.
  600. // */
  601. // public static String[][] optionVariants(String[] options) {
  602. // if ((null == options) || (0 == options.length)) {
  603. // return new String[][] { new String[0]};
  604. // }
  605. // // be nice, don't stomp input
  606. // String[] temp = new String[options.length];
  607. // System.arraycopy(options, 0, temp, 0, temp.length);
  608. // options = temp;
  609. // boolean[] dup = new boolean[options.length];
  610. // int numDups = 0;
  611. //
  612. // for (int i = 0; i < options.length; i++) {
  613. // String option = options[i];
  614. // if (LangUtil.isEmpty(option)) {
  615. // throw new IllegalArgumentException("empty option at " + i);
  616. // }
  617. // if (option.endsWith("-")) {
  618. // options[i] = option.substring(0, option.length()-1);
  619. // dup[i] = true;
  620. // numDups++;
  621. // }
  622. // }
  623. // final String[] NONE = new String[0];
  624. // final int variants = exp(2, numDups);
  625. // final String[][] result = new String[variants][];
  626. // // variant is a bitmap wrt doing extra value when dup[k]=true
  627. // for (int variant = 0; variant < variants; variant++) {
  628. // ArrayList next = new ArrayList();
  629. // int nextOption = 0;
  630. // for (int k = 0; k < options.length; k++) {
  631. // if (!dup[k] || (0 != (variant & (1 << (nextOption++))))) {
  632. // next.add(options[k]);
  633. // }
  634. // }
  635. // result[variant] = (String[]) next.toArray(NONE);
  636. // }
  637. // return result;
  638. // }
  639. //
  640. // private static int exp(int base, int power) { // not in Math?
  641. // if (0 > power) {
  642. // throw new IllegalArgumentException("negative power: " + power);
  643. // }
  644. // int result = 1;
  645. // while (0 < power--) {
  646. // result *= base;
  647. // }
  648. // return result;
  649. // }
  650. // /**
  651. // * Make a copy of the array.
  652. // * @return an array with the same component type as source
  653. // * containing same elements, even if null.
  654. // * @throws IllegalArgumentException if source is null
  655. // */
  656. // public static final Object[] copy(Object[] source) {
  657. // LangUtil.throwIaxIfNull(source, "source");
  658. // final Class c = source.getClass().getComponentType();
  659. // Object[] result = (Object[]) Array.newInstance(c, source.length);
  660. // System.arraycopy(source, 0, result, 0, result.length);
  661. // return result;
  662. // }
  663. /**
  664. * Convert arrays safely. The number of elements in the result will be 1 smaller for each element that is null or not
  665. * assignable. This will use sink if it has exactly the right size. The result will always have the same component type as sink.
  666. *
  667. * @return an array with the same component type as sink containing any assignable elements in source (in the same order).
  668. * @throws IllegalArgumentException if either is null
  669. */
  670. public static Object[] safeCopy(Object[] source, Object[] sink) {
  671. final Class<?> sinkType = (null == sink ? Object.class : sink.getClass().getComponentType());
  672. final int sourceLength = (null == source ? 0 : source.length);
  673. final int sinkLength = (null == sink ? 0 : sink.length);
  674. final int resultSize;
  675. ArrayList<Object> result = null;
  676. if (0 == sourceLength) {
  677. resultSize = 0;
  678. } else {
  679. result = new ArrayList<Object>(sourceLength);
  680. for (int i = 0; i < sourceLength; i++) {
  681. if ((null != source[i]) && (sinkType.isAssignableFrom(source[i].getClass()))) {
  682. result.add(source[i]);
  683. }
  684. }
  685. resultSize = result.size();
  686. }
  687. if (resultSize != sinkLength) {
  688. sink = (Object[]) Array.newInstance(sinkType, result.size());
  689. }
  690. if (0 < resultSize) {
  691. sink = result.toArray(sink);
  692. }
  693. return sink;
  694. }
  695. /**
  696. * @return a String with the unqualified class name of the class (or "null")
  697. */
  698. public static String unqualifiedClassName(Class<?> c) {
  699. if (null == c) {
  700. return "null";
  701. }
  702. String name = c.getName();
  703. int loc = name.lastIndexOf(".");
  704. if (-1 != loc) {
  705. name = name.substring(1 + loc);
  706. }
  707. return name;
  708. }
  709. /**
  710. * @return a String with the unqualified class name of the object (or "null")
  711. */
  712. public static String unqualifiedClassName(Object o) {
  713. return LangUtil.unqualifiedClassName(null == o ? null : o.getClass());
  714. }
  715. /** inefficient way to replace all instances of sought with replace */
  716. public static String replace(String in, String sought, String replace) {
  717. if (LangUtil.isEmpty(in) || LangUtil.isEmpty(sought)) {
  718. return in;
  719. }
  720. StringBuffer result = new StringBuffer();
  721. final int len = sought.length();
  722. int start = 0;
  723. int loc;
  724. while (-1 != (loc = in.indexOf(sought, start))) {
  725. result.append(in.substring(start, loc));
  726. if (!LangUtil.isEmpty(replace)) {
  727. result.append(replace);
  728. }
  729. start = loc + len;
  730. }
  731. result.append(in.substring(start));
  732. return result.toString();
  733. }
  734. /** render i right-justified with a given width less than about 40 */
  735. public static String toSizedString(long i, int width) {
  736. String result = "" + i;
  737. int size = result.length();
  738. if (width > size) {
  739. final String pad = " ";
  740. final int padLength = pad.length();
  741. if (width > padLength) {
  742. width = padLength;
  743. }
  744. int topad = width - size;
  745. result = pad.substring(0, topad) + result;
  746. }
  747. return result;
  748. }
  749. // /** clip StringBuffer to maximum number of lines */
  750. // static String clipBuffer(StringBuffer buffer, int maxLines) {
  751. // if ((null == buffer) || (1 > buffer.length())) return "";
  752. // StringBuffer result = new StringBuffer();
  753. // int j = 0;
  754. // final int MAX = maxLines;
  755. // final int N = buffer.length();
  756. // for (int i = 0, srcBegin = 0; i < MAX; srcBegin += j) {
  757. // // todo: replace with String variant if/since getting char?
  758. // char[] chars = new char[128];
  759. // int srcEnd = srcBegin+chars.length;
  760. // if (srcEnd >= N) {
  761. // srcEnd = N-1;
  762. // }
  763. // if (srcBegin == srcEnd) break;
  764. // //log("srcBegin:" + srcBegin + ":srcEnd:" + srcEnd);
  765. // buffer.getChars(srcBegin, srcEnd, chars, 0);
  766. // for (j = 0; j < srcEnd-srcBegin/*chars.length*/; j++) {
  767. // char c = chars[j];
  768. // if (c == '\n') {
  769. // i++;
  770. // j++;
  771. // break;
  772. // }
  773. // }
  774. // try { result.append(chars, 0, j); }
  775. // catch (Throwable t) { }
  776. // }
  777. // return result.toString();
  778. // }
  779. /**
  780. * @return "({UnqualifiedExceptionClass}) {message}"
  781. */
  782. public static String renderExceptionShort(Throwable e) {
  783. if (null == e) {
  784. return "(Throwable) null";
  785. }
  786. return "(" + LangUtil.unqualifiedClassName(e) + ") " + e.getMessage();
  787. }
  788. /**
  789. * Renders exception <code>t</code> after unwrapping and eliding any test packages.
  790. *
  791. * @param t <code>Throwable</code> to print.
  792. * @see #maxStackTrace
  793. */
  794. public static String renderException(Throwable t) {
  795. return renderException(t, true);
  796. }
  797. /**
  798. * Renders exception <code>t</code>, unwrapping, optionally eliding and limiting total number of lines.
  799. *
  800. * @param t <code>Throwable</code> to print.
  801. * @param elide true to limit to 100 lines and elide test packages
  802. * @see StringChecker#TEST_PACKAGES
  803. */
  804. public static String renderException(Throwable t, boolean elide) {
  805. if (null == t) {
  806. return "null throwable";
  807. }
  808. t = unwrapException(t);
  809. StringBuffer stack = stackToString(t, false);
  810. if (elide) {
  811. elideEndingLines(StringChecker.TEST_PACKAGES, stack, 100);
  812. }
  813. return stack.toString();
  814. }
  815. /**
  816. * Trim ending lines from a StringBuffer, clipping to maxLines and further removing any number of trailing lines accepted by
  817. * checker.
  818. *
  819. * @param checker returns true if trailing line should be elided.
  820. * @param stack StringBuffer with lines to elide
  821. * @param maxLines int for maximum number of resulting lines
  822. */
  823. static void elideEndingLines(StringChecker checker, StringBuffer stack, int maxLines) {
  824. if (null == checker || (null == stack) || (0 == stack.length())) {
  825. return;
  826. }
  827. final LinkedList<String> lines = new LinkedList<String>();
  828. StringTokenizer st = new StringTokenizer(stack.toString(), "\n\r");
  829. while (st.hasMoreTokens() && (0 < --maxLines)) {
  830. lines.add(st.nextToken());
  831. }
  832. st = null;
  833. String line;
  834. int elided = 0;
  835. while (!lines.isEmpty()) {
  836. line = lines.getLast();
  837. if (!checker.acceptString(line)) {
  838. break;
  839. } else {
  840. elided++;
  841. lines.removeLast();
  842. }
  843. }
  844. if ((elided > 0) || (maxLines < 1)) {
  845. final int EOL_LEN = EOL.length();
  846. int totalLength = 0;
  847. while (!lines.isEmpty()) {
  848. totalLength += EOL_LEN + lines.getFirst().length();
  849. lines.removeFirst();
  850. }
  851. if (stack.length() > totalLength) {
  852. stack.setLength(totalLength);
  853. if (elided > 0) {
  854. stack.append(" (... " + elided + " lines...)");
  855. }
  856. }
  857. }
  858. }
  859. /** Dump message and stack to StringBuffer. */
  860. public static StringBuffer stackToString(Throwable throwable, boolean skipMessage) {
  861. if (null == throwable) {
  862. return new StringBuffer();
  863. }
  864. StringWriter buf = new StringWriter();
  865. PrintWriter writer = new PrintWriter(buf);
  866. if (!skipMessage) {
  867. writer.println(throwable.getMessage());
  868. }
  869. throwable.printStackTrace(writer);
  870. try {
  871. buf.close();
  872. } catch (IOException ioe) {
  873. } // ignored
  874. return buf.getBuffer();
  875. }
  876. /** @return Throwable input or tail of any wrapped exception chain */
  877. public static Throwable unwrapException(Throwable t) {
  878. Throwable current = t;
  879. Throwable next = null;
  880. while (current != null) {
  881. // Java 1.2 exceptions that carry exceptions
  882. if (current instanceof InvocationTargetException) {
  883. next = ((InvocationTargetException) current).getTargetException();
  884. } else if (current instanceof ClassNotFoundException) {
  885. next = ((ClassNotFoundException) current).getException();
  886. } else if (current instanceof ExceptionInInitializerError) {
  887. next = ((ExceptionInInitializerError) current).getException();
  888. } else if (current instanceof PrivilegedActionException) {
  889. next = ((PrivilegedActionException) current).getException();
  890. } else if (current instanceof SQLException) {
  891. next = ((SQLException) current).getNextException();
  892. }
  893. // ...getException():
  894. // javax.naming.event.NamingExceptionEvent
  895. // javax.naming.ldap.UnsolicitedNotification
  896. // javax.xml.parsers.FactoryConfigurationError
  897. // javax.xml.transform.TransformerFactoryConfigurationError
  898. // javax.xml.transform.TransformerException
  899. // org.xml.sax.SAXException
  900. // 1.4: Throwable.getCause
  901. // java.util.logging.LogRecord.getThrown()
  902. if (null == next) {
  903. break;
  904. } else {
  905. current = next;
  906. next = null;
  907. }
  908. }
  909. return current;
  910. }
  911. /**
  912. * Replacement for Arrays.asList(..) which gacks on null and returns a List in which remove is an unsupported operation.
  913. *
  914. * @param array the Object[] to convert (may be null)
  915. * @return the List corresponding to array (never null)
  916. */
  917. public static <T> List<T> arrayAsList(T[] array) {
  918. if ((null == array) || (1 > array.length)) {
  919. return Collections.emptyList();
  920. }
  921. ArrayList<T> list = new ArrayList<T>();
  922. list.addAll(Arrays.asList(array));
  923. return list;
  924. }
  925. /** check if input contains any packages to elide. */
  926. public static class StringChecker {
  927. static StringChecker TEST_PACKAGES = new StringChecker(new String[] { "org.aspectj.testing",
  928. "org.eclipse.jdt.internal.junit", "junit.framework.",
  929. "org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner" });
  930. String[] infixes;
  931. /** @param infixes adopted */
  932. StringChecker(String[] infixes) {
  933. this.infixes = infixes;
  934. }
  935. /** @return true if input contains infixes */
  936. public boolean acceptString(String input) {
  937. boolean result = false;
  938. if (!LangUtil.isEmpty(input)) {
  939. for (int i = 0; !result && (i < infixes.length); i++) {
  940. result = (-1 != input.indexOf(infixes[i]));
  941. }
  942. }
  943. return result;
  944. }
  945. }
  946. /**
  947. * Gen classpath.
  948. *
  949. * @param bootclasspath
  950. * @param classpath
  951. * @param classesDir
  952. * @param outputJar
  953. * @return String combining classpath elements
  954. */
  955. public static String makeClasspath( // XXX dumb implementation
  956. String bootclasspath, String classpath, String classesDir, String outputJar) {
  957. StringBuffer sb = new StringBuffer();
  958. addIfNotEmpty(bootclasspath, sb, File.pathSeparator);
  959. addIfNotEmpty(classpath, sb, File.pathSeparator);
  960. if (!addIfNotEmpty(classesDir, sb, File.pathSeparator)) {
  961. addIfNotEmpty(outputJar, sb, File.pathSeparator);
  962. }
  963. return sb.toString();
  964. }
  965. /**
  966. * @param input ignored if null
  967. * @param sink the StringBuffer to add input to - return false if null
  968. * @param delimiter the String to append to input when added - ignored if empty
  969. * @return true if input + delimiter added to sink
  970. */
  971. private static boolean addIfNotEmpty(String input, StringBuffer sink, String delimiter) {
  972. if (LangUtil.isEmpty(input) || (null == sink)) {
  973. return false;
  974. }
  975. sink.append(input);
  976. if (!LangUtil.isEmpty(delimiter)) {
  977. sink.append(delimiter);
  978. }
  979. return true;
  980. }
  981. /**
  982. * Create or initialize a process controller to run a process in another VM asynchronously.
  983. *
  984. * @param controller the ProcessController to initialize, if not null
  985. * @param classpath
  986. * @param mainClass
  987. * @param args
  988. * @return initialized ProcessController
  989. */
  990. public static ProcessController makeProcess(ProcessController controller, String classpath, String mainClass, String[] args) {
  991. File java = LangUtil.getJavaExecutable();
  992. ArrayList<String> cmd = new ArrayList<String>();
  993. cmd.add(java.getAbsolutePath());
  994. cmd.add("-classpath");
  995. cmd.add(classpath);
  996. cmd.add(mainClass);
  997. if (!LangUtil.isEmpty(args)) {
  998. cmd.addAll(Arrays.asList(args));
  999. }
  1000. String[] command = cmd.toArray(new String[0]);
  1001. if (null == controller) {
  1002. controller = new ProcessController();
  1003. }
  1004. controller.init(command, mainClass);
  1005. return controller;
  1006. }
  1007. // /**
  1008. // * Create a process to run asynchronously.
  1009. // * @param controller if not null, initialize this one
  1010. // * @param command the String[] command to run
  1011. // * @param controller the ProcessControl for streams and results
  1012. // */
  1013. // public static ProcessController makeProcess( // not needed?
  1014. // ProcessController controller,
  1015. // String[] command,
  1016. // String label) {
  1017. // if (null == controller) {
  1018. // controller = new ProcessController();
  1019. // }
  1020. // controller.init(command, label);
  1021. // return controller;
  1022. // }
  1023. /**
  1024. * Find java executable File path from java.home system property.
  1025. *
  1026. * @return File associated with the java command, or null if not found.
  1027. */
  1028. public static File getJavaExecutable() {
  1029. String javaHome = null;
  1030. File result = null;
  1031. // java.home
  1032. // java.class.path
  1033. // java.ext.dirs
  1034. try {
  1035. javaHome = System.getProperty("java.home");
  1036. } catch (Throwable t) {
  1037. // ignore
  1038. }
  1039. if (null != javaHome) {
  1040. File binDir = new File(javaHome, "bin");
  1041. if (binDir.isDirectory() && binDir.canRead()) {
  1042. String[] execs = new String[] { "java", "java.exe" };
  1043. for (int i = 0; i < execs.length; i++) {
  1044. result = new File(binDir, execs[i]);
  1045. if (result.canRead()) {
  1046. break;
  1047. }
  1048. }
  1049. }
  1050. }
  1051. return result;
  1052. }
  1053. // /**
  1054. // * Sleep for a particular period (in milliseconds).
  1055. // *
  1056. // * @param time the long time in milliseconds to sleep
  1057. // * @return true if delay succeeded, false if interrupted 100 times
  1058. // */
  1059. // public static boolean sleep(long milliseconds) {
  1060. // if (milliseconds == 0) {
  1061. // return true;
  1062. // } else if (milliseconds < 0) {
  1063. // throw new IllegalArgumentException("negative: " + milliseconds);
  1064. // }
  1065. // return sleepUntil(milliseconds + System.currentTimeMillis());
  1066. // }
  1067. /**
  1068. * Sleep until a particular time.
  1069. *
  1070. * @param time the long time in milliseconds to sleep until
  1071. * @return true if delay succeeded, false if interrupted 100 times
  1072. */
  1073. public static boolean sleepUntil(long time) {
  1074. if (time == 0) {
  1075. return true;
  1076. } else if (time < 0) {
  1077. throw new IllegalArgumentException("negative: " + time);
  1078. }
  1079. // final Thread thread = Thread.currentThread();
  1080. long curTime = System.currentTimeMillis();
  1081. for (int i = 0; (i < 100) && (curTime < time); i++) {
  1082. try {
  1083. Thread.sleep(time - curTime);
  1084. } catch (InterruptedException e) {
  1085. // ignore
  1086. }
  1087. curTime = System.currentTimeMillis();
  1088. }
  1089. return (curTime >= time);
  1090. }
  1091. /**
  1092. * Handle an external process asynchrously. <code>start()</code> launches a main thread to wait for the process and pipes
  1093. * streams (in child threads) through to the corresponding streams (e.g., the process System.err to this System.err). This can
  1094. * complete normally, by exception, or on demand by a client. Clients can implement <code>doCompleting(..)</code> to get notice
  1095. * when the process completes.
  1096. * <p>
  1097. * The following sample code creates a process with a completion callback starts it, and some time later retries the process.
  1098. *
  1099. * <pre>
  1100. * LangUtil.ProcessController controller = new LangUtil.ProcessController() {
  1101. * protected void doCompleting(LangUtil.ProcessController.Thrown thrown, int result) {
  1102. * // signal result
  1103. * }
  1104. * };
  1105. * controller.init(new String[] { &quot;java&quot;, &quot;-version&quot; }, &quot;java version&quot;);
  1106. * controller.start();
  1107. * // some time later...
  1108. * // retry...
  1109. * if (!controller.completed()) {
  1110. * controller.stop();
  1111. * controller.reinit();
  1112. * controller.start();
  1113. * }
  1114. * </pre>
  1115. *
  1116. * <u>warning</u>: Currently this does not close the input or output streams, since doing so prevents their use later.
  1117. */
  1118. public static class ProcessController {
  1119. /*
  1120. * XXX not verified thread-safe, but should be. Known problems: - user stops (completed = true) then exception thrown from
  1121. * destroying process (stop() expects !completed) ...
  1122. */
  1123. private String[] command;
  1124. private String[] envp;
  1125. private String label;
  1126. private boolean init;
  1127. private boolean started;
  1128. private boolean completed;
  1129. /** if true, stopped by user when not completed */
  1130. private boolean userStopped;
  1131. private Process process;
  1132. private FileUtil.Pipe errStream;
  1133. private FileUtil.Pipe outStream;
  1134. private FileUtil.Pipe inStream;
  1135. private ByteArrayOutputStream errSnoop;
  1136. private ByteArrayOutputStream outSnoop;
  1137. private int result;
  1138. private Thrown thrown;
  1139. public ProcessController() {
  1140. }
  1141. /**
  1142. * Permit re-running using the same command if this is not started or if completed. Can also call this when done with
  1143. * results to release references associated with results (e.g., stack traces).
  1144. */
  1145. public final void reinit() {
  1146. if (!init) {
  1147. throw new IllegalStateException("must init(..) before reinit()");
  1148. }
  1149. if (started && !completed) {
  1150. throw new IllegalStateException("not completed - do stop()");
  1151. }
  1152. // init everything but command and label
  1153. started = false;
  1154. completed = false;
  1155. result = Integer.MIN_VALUE;
  1156. thrown = null;
  1157. process = null;
  1158. errStream = null;
  1159. outStream = null;
  1160. inStream = null;
  1161. }
  1162. public final void init(String classpath, String mainClass, String[] args) {
  1163. init(LangUtil.getJavaExecutable(), classpath, mainClass, args);
  1164. }
  1165. public final void init(File java, String classpath, String mainClass, String[] args) {
  1166. LangUtil.throwIaxIfNull(java, "java");
  1167. LangUtil.throwIaxIfNull(mainClass, "mainClass");
  1168. LangUtil.throwIaxIfNull(args, "args");
  1169. ArrayList<String> cmd = new ArrayList<String>();
  1170. cmd.add(java.getAbsolutePath());
  1171. cmd.add("-classpath");
  1172. cmd.add(classpath);
  1173. cmd.add(mainClass);
  1174. if (!LangUtil.isEmpty(args)) {
  1175. cmd.addAll(Arrays.asList(args));
  1176. }
  1177. init(cmd.toArray(new String[0]), mainClass);
  1178. }
  1179. public final void init(String[] command, String label) {
  1180. this.command = (String[]) LangUtil.safeCopy(command, new String[0]);
  1181. if (1 > this.command.length) {
  1182. throw new IllegalArgumentException("empty command");
  1183. }
  1184. this.label = LangUtil.isEmpty(label) ? command[0] : label;
  1185. init = true;
  1186. reinit();
  1187. }
  1188. public final void setEnvp(String[] envp) {
  1189. this.envp = (String[]) LangUtil.safeCopy(envp, new String[0]);
  1190. if (1 > this.envp.length) {
  1191. throw new IllegalArgumentException("empty envp");
  1192. }
  1193. }
  1194. public final void setErrSnoop(ByteArrayOutputStream snoop) {
  1195. errSnoop = snoop;
  1196. if (null != errStream) {
  1197. errStream.setSnoop(errSnoop);
  1198. }
  1199. }
  1200. public final void setOutSnoop(ByteArrayOutputStream snoop) {
  1201. outSnoop = snoop;
  1202. if (null != outStream) {
  1203. outStream.setSnoop(outSnoop);
  1204. }
  1205. }
  1206. /**
  1207. * Start running the process and pipes asynchronously.
  1208. *
  1209. * @return Thread started or null if unable to start thread (results available via <code>getThrown()</code>, etc.)
  1210. */
  1211. public final Thread start() {
  1212. if (!init) {
  1213. throw new IllegalStateException("not initialized");
  1214. }
  1215. synchronized (this) {
  1216. if (started) {
  1217. throw new IllegalStateException("already started");
  1218. }
  1219. started = true;
  1220. }
  1221. try {
  1222. process = Runtime.getRuntime().exec(command);
  1223. } catch (IOException e) {
  1224. stop(e, Integer.MIN_VALUE);
  1225. return null;
  1226. }
  1227. errStream = new FileUtil.Pipe(process.getErrorStream(), System.err);
  1228. if (null != errSnoop) {
  1229. errStream.setSnoop(errSnoop);
  1230. }
  1231. outStream = new FileUtil.Pipe(process.getInputStream(), System.out);
  1232. if (null != outSnoop) {
  1233. outStream.setSnoop(outSnoop);
  1234. }
  1235. inStream = new FileUtil.Pipe(System.in, process.getOutputStream());
  1236. // start 4 threads, process & pipes for in, err, out
  1237. Runnable processRunner = new Runnable() {
  1238. @Override
  1239. public void run() {
  1240. Throwable thrown = null;
  1241. int result = Integer.MIN_VALUE;
  1242. try {
  1243. // pipe threads are children
  1244. new Thread(errStream).start();
  1245. new Thread(outStream).start();
  1246. new Thread(inStream).start();
  1247. process.waitFor();
  1248. result = process.exitValue();
  1249. } catch (Throwable e) {
  1250. thrown = e;
  1251. } finally {
  1252. stop(thrown, result);
  1253. }
  1254. }
  1255. };
  1256. Thread result = new Thread(processRunner, label);
  1257. result.start();
  1258. return result;
  1259. }
  1260. /**
  1261. * Destroy any process, stop any pipes. This waits for the pipes to clear (reading until no more input is available), but
  1262. * does not wait for the input stream for the pipe to close (i.e., not waiting for end-of-file on input stream).
  1263. */
  1264. public final synchronized void stop() {
  1265. if (completed) {
  1266. return;
  1267. }
  1268. userStopped = true;
  1269. stop(null, Integer.MIN_VALUE);
  1270. }
  1271. public final String[] getCommand() {
  1272. String[] toCopy = command;
  1273. if (LangUtil.isEmpty(toCopy)) {
  1274. return new String[0];
  1275. }
  1276. String[] result = new String[toCopy.length];
  1277. System.arraycopy(toCopy, 0, result, 0, result.length);
  1278. return result;
  1279. }
  1280. public final boolean completed() {
  1281. return completed;
  1282. }
  1283. public final boolean started() {
  1284. return started;
  1285. }
  1286. public final boolean userStopped() {
  1287. return userStopped;
  1288. }
  1289. /**
  1290. * Get any Throwable thrown. Note that the process can complete normally (with a valid return value), at the same time the
  1291. * pipes throw exceptions, and that this may return some exceptions even if the process is not complete.
  1292. *
  1293. * @return null if not complete or Thrown containing exceptions thrown by the process and streams.
  1294. */
  1295. public final Thrown getThrown() { // cache this
  1296. return makeThrown(null);
  1297. }
  1298. public final int getResult() {
  1299. return result;
  1300. }
  1301. /**
  1302. * Subclasses implement this to get synchronous notice of completion. All pipes and processes should be complete at this
  1303. * time. To get the exceptions thrown for the pipes, use <code>getThrown()</code>. If there is an exception, the process
  1304. * completed abruptly (including side-effects of the user halting the process). If <code>userStopped()</code> is true, then
  1305. * some client asked that the process be destroyed using <code>stop()</code>. Otherwise, the result code should be the
  1306. * result value returned by the process.
  1307. *
  1308. * @param thrown same as <code>getThrown().fromProcess</code>.
  1309. * @param result same as <code>getResult()</code>
  1310. * @see getThrown()
  1311. * @see getResult()
  1312. * @see stop()
  1313. */
  1314. protected void doCompleting(Thrown thrown, int result) {
  1315. }
  1316. /**
  1317. * Handle termination (on-demand, abrupt, or normal) by destroying and/or halting process and pipes.
  1318. *
  1319. * @param thrown ignored if null
  1320. * @param result ignored if Integer.MIN_VALUE
  1321. */
  1322. private final synchronized void stop(Throwable thrown, int result) {
  1323. if (completed) {
  1324. throw new IllegalStateException("already completed");
  1325. } else if (null != this.thrown) {
  1326. throw new IllegalStateException("already set thrown: " + thrown);
  1327. }
  1328. // assert null == this.thrown
  1329. this.thrown = makeThrown(thrown);
  1330. if (null != process) {
  1331. process.destroy();
  1332. }
  1333. if (null != inStream) {
  1334. inStream.halt(false, true); // this will block if waiting
  1335. inStream = null;
  1336. }
  1337. if (null != outStream) {
  1338. outStream.halt(true, true);
  1339. outStream = null;
  1340. }
  1341. if (null != errStream) {
  1342. errStream.halt(true, true);
  1343. errStream = null;
  1344. }
  1345. if (Integer.MIN_VALUE != result) {
  1346. this.result = result;
  1347. }
  1348. completed = true;
  1349. doCompleting(this.thrown, result);
  1350. }
  1351. /**
  1352. * Create snapshot of Throwable's thrown.
  1353. *
  1354. * @param thrown ignored if null or if this.thrown is not null
  1355. */
  1356. private final synchronized Thrown makeThrown(Throwable processThrown) {
  1357. if (null != thrown) {
  1358. return thrown;
  1359. }
  1360. return new Thrown(processThrown, (null == outStream ? null : outStream.getThrown()), (null == errStream ? null
  1361. : errStream.getThrown()), (null == inStream ? null : inStream.getThrown()));
  1362. }
  1363. public static class Thrown {
  1364. public final Throwable fromProcess;
  1365. public final Throwable fromErrPipe;
  1366. public final Throwable fromOutPipe;
  1367. public final Throwable fromInPipe;
  1368. /** true only if some Throwable is not null */
  1369. public final boolean thrown;
  1370. private Thrown(Throwable fromProcess, Throwable fromOutPipe, Throwable fromErrPipe, Throwable fromInPipe) {
  1371. this.fromProcess = fromProcess;
  1372. this.fromErrPipe = fromErrPipe;
  1373. this.fromOutPipe = fromOutPipe;
  1374. this.fromInPipe = fromInPipe;
  1375. thrown = ((null != fromProcess) || (null != fromInPipe) || (null != fromOutPipe) || (null != fromErrPipe));
  1376. }
  1377. @Override
  1378. public String toString() {
  1379. StringBuffer sb = new StringBuffer();
  1380. append(sb, fromProcess, "process");
  1381. append(sb, fromOutPipe, " stdout");
  1382. append(sb, fromErrPipe, " stderr");
  1383. append(sb, fromInPipe, " stdin");
  1384. if (0 == sb.length()) {
  1385. return "Thrown (none)";
  1386. } else {
  1387. return sb.toString();
  1388. }
  1389. }
  1390. private void append(StringBuffer sb, Throwable thrown, String label) {
  1391. if (null != thrown) {
  1392. sb.append("from " + label + ": ");
  1393. sb.append(LangUtil.renderExceptionShort(thrown));
  1394. sb.append(LangUtil.EOL);
  1395. }
  1396. }
  1397. } // class Thrown
  1398. }
  1399. public static String getJrtFsFilePath() {
  1400. return getJavaHome() + File.separator + "lib" + File.separator + JRT_FS;
  1401. }
  1402. public static String getJavaHome() {
  1403. return System.getProperty("java.home");
  1404. }
  1405. }