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