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

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