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

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