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.

LangUtil.java 45KB

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