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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  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<>();
  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. @Deprecated
  118. public static boolean isOnePointThreeVMOrGreater() {
  119. return 1.3 <= vmVersion;
  120. }
  121. @Deprecated
  122. public static boolean is1dot4VMOrGreater() {
  123. return 1.4 <= vmVersion;
  124. }
  125. @Deprecated
  126. public static boolean is15VMOrGreater() {
  127. return 1.5 <= vmVersion;
  128. }
  129. @Deprecated
  130. public static boolean is16VMOrGreater() {
  131. return 1.6 <= vmVersion;
  132. }
  133. @Deprecated
  134. public static boolean is17VMOrGreater() {
  135. return 1.7 <= vmVersion;
  136. }
  137. public static boolean is18VMOrGreater() {
  138. return 1.8 <= vmVersion;
  139. }
  140. public static boolean is19VMOrGreater() {
  141. return 9 <= vmVersion;
  142. }
  143. public static boolean is10VMOrGreater() {
  144. return 10 <= vmVersion;
  145. }
  146. public static boolean is11VMOrGreater() {
  147. return 11 <= vmVersion;
  148. }
  149. public static boolean is12VMOrGreater() {
  150. return 12 <= vmVersion;
  151. }
  152. public static boolean is13VMOrGreater() {
  153. return 13 <= vmVersion;
  154. }
  155. public static boolean is14VMOrGreater() {
  156. return 14 <= 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.valueOf(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. StringBuffer result = new StringBuffer();
  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. StringBuffer sb = new StringBuffer();
  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(StringBuffer 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. }