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

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