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 44KB

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