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

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