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

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