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

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