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

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