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

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