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

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