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

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