Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  1. /*
  2. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.util;
  44. import java.io.BufferedReader;
  45. import java.io.ByteArrayInputStream;
  46. import java.io.File;
  47. import java.io.IOException;
  48. import java.io.InputStream;
  49. import java.io.InputStreamReader;
  50. import java.io.OutputStream;
  51. import java.io.PrintStream;
  52. import java.nio.charset.Charset;
  53. import java.nio.file.attribute.BasicFileAttributes;
  54. import java.security.AccessController;
  55. import java.security.PrivilegedAction;
  56. import java.text.MessageFormat;
  57. import java.util.Arrays;
  58. import java.util.HashMap;
  59. import java.util.Map;
  60. import java.util.Objects;
  61. import java.util.concurrent.Callable;
  62. import java.util.concurrent.ExecutorService;
  63. import java.util.concurrent.Executors;
  64. import java.util.concurrent.TimeUnit;
  65. import java.util.concurrent.atomic.AtomicBoolean;
  66. import java.util.concurrent.atomic.AtomicReference;
  67. import org.eclipse.jgit.annotations.Nullable;
  68. import org.eclipse.jgit.api.errors.JGitInternalException;
  69. import org.eclipse.jgit.errors.CommandFailedException;
  70. import org.eclipse.jgit.internal.JGitText;
  71. import org.eclipse.jgit.lib.Constants;
  72. import org.eclipse.jgit.lib.Repository;
  73. import org.eclipse.jgit.util.ProcessResult.Status;
  74. import org.slf4j.Logger;
  75. import org.slf4j.LoggerFactory;
  76. /** Abstraction to support various file system operations not in Java. */
  77. public abstract class FS {
  78. /**
  79. * This class creates FS instances. It will be overridden by a Java7 variant
  80. * if such can be detected in {@link #detect(Boolean)}.
  81. *
  82. * @since 3.0
  83. */
  84. public static class FSFactory {
  85. /**
  86. * Constructor
  87. */
  88. protected FSFactory() {
  89. // empty
  90. }
  91. /**
  92. * Detect the file system
  93. *
  94. * @param cygwinUsed
  95. * @return FS instance
  96. */
  97. public FS detect(Boolean cygwinUsed) {
  98. if (SystemReader.getInstance().isWindows()) {
  99. if (cygwinUsed == null)
  100. cygwinUsed = Boolean.valueOf(FS_Win32_Cygwin.isCygwin());
  101. if (cygwinUsed.booleanValue())
  102. return new FS_Win32_Cygwin();
  103. else
  104. return new FS_Win32();
  105. } else {
  106. return new FS_POSIX();
  107. }
  108. }
  109. }
  110. /**
  111. * Result of an executed process. The caller is responsible to close the
  112. * contained {@link TemporaryBuffer}s
  113. *
  114. * @since 4.2
  115. */
  116. public static class ExecutionResult {
  117. private TemporaryBuffer stdout;
  118. private TemporaryBuffer stderr;
  119. private int rc;
  120. /**
  121. * @param stdout
  122. * @param stderr
  123. * @param rc
  124. */
  125. public ExecutionResult(TemporaryBuffer stdout, TemporaryBuffer stderr,
  126. int rc) {
  127. this.stdout = stdout;
  128. this.stderr = stderr;
  129. this.rc = rc;
  130. }
  131. /**
  132. * @return buffered standard output stream
  133. */
  134. public TemporaryBuffer getStdout() {
  135. return stdout;
  136. }
  137. /**
  138. * @return buffered standard error stream
  139. */
  140. public TemporaryBuffer getStderr() {
  141. return stderr;
  142. }
  143. /**
  144. * @return the return code of the process
  145. */
  146. public int getRc() {
  147. return rc;
  148. }
  149. }
  150. private final static Logger LOG = LoggerFactory.getLogger(FS.class);
  151. /** The auto-detected implementation selected for this operating system and JRE. */
  152. public static final FS DETECTED = detect();
  153. private static FSFactory factory;
  154. /**
  155. * Auto-detect the appropriate file system abstraction.
  156. *
  157. * @return detected file system abstraction
  158. */
  159. public static FS detect() {
  160. return detect(null);
  161. }
  162. /**
  163. * Auto-detect the appropriate file system abstraction, taking into account
  164. * the presence of a Cygwin installation on the system. Using jgit in
  165. * combination with Cygwin requires a more elaborate (and possibly slower)
  166. * resolution of file system paths.
  167. *
  168. * @param cygwinUsed
  169. * <ul>
  170. * <li><code>Boolean.TRUE</code> to assume that Cygwin is used in
  171. * combination with jgit</li>
  172. * <li><code>Boolean.FALSE</code> to assume that Cygwin is
  173. * <b>not</b> used with jgit</li>
  174. * <li><code>null</code> to auto-detect whether a Cygwin
  175. * installation is present on the system and in this case assume
  176. * that Cygwin is used</li>
  177. * </ul>
  178. *
  179. * Note: this parameter is only relevant on Windows.
  180. *
  181. * @return detected file system abstraction
  182. */
  183. public static FS detect(Boolean cygwinUsed) {
  184. if (factory == null) {
  185. factory = new FS.FSFactory();
  186. }
  187. return factory.detect(cygwinUsed);
  188. }
  189. private volatile Holder<File> userHome;
  190. private volatile Holder<File> gitSystemConfig;
  191. /**
  192. * Constructs a file system abstraction.
  193. */
  194. protected FS() {
  195. // Do nothing by default.
  196. }
  197. /**
  198. * Initialize this FS using another's current settings.
  199. *
  200. * @param src
  201. * the source FS to copy from.
  202. */
  203. protected FS(FS src) {
  204. userHome = src.userHome;
  205. gitSystemConfig = src.gitSystemConfig;
  206. }
  207. /** @return a new instance of the same type of FS. */
  208. public abstract FS newInstance();
  209. /**
  210. * Does this operating system and JRE support the execute flag on files?
  211. *
  212. * @return true if this implementation can provide reasonably accurate
  213. * executable bit information; false otherwise.
  214. */
  215. public abstract boolean supportsExecute();
  216. /**
  217. * Does this file system support atomic file creation via
  218. * java.io.File#createNewFile()? In certain environments (e.g. on NFS) it is
  219. * not guaranteed that when two file system clients run createNewFile() in
  220. * parallel only one will succeed. In such cases both clients may think they
  221. * created a new file.
  222. *
  223. * @return true if this implementation support atomic creation of new
  224. * Files by {@link File#createNewFile()}
  225. * @since 4.5
  226. */
  227. public boolean supportsAtomicCreateNewFile() {
  228. return true;
  229. }
  230. /**
  231. * Does this operating system and JRE supports symbolic links. The
  232. * capability to handle symbolic links is detected at runtime.
  233. *
  234. * @return true if symbolic links may be used
  235. * @since 3.0
  236. */
  237. public boolean supportsSymlinks() {
  238. return false;
  239. }
  240. /**
  241. * Is this file system case sensitive
  242. *
  243. * @return true if this implementation is case sensitive
  244. */
  245. public abstract boolean isCaseSensitive();
  246. /**
  247. * Determine if the file is executable (or not).
  248. * <p>
  249. * Not all platforms and JREs support executable flags on files. If the
  250. * feature is unsupported this method will always return false.
  251. * <p>
  252. * <em>If the platform supports symbolic links and <code>f</code> is a symbolic link
  253. * this method returns false, rather than the state of the executable flags
  254. * on the target file.</em>
  255. *
  256. * @param f
  257. * abstract path to test.
  258. * @return true if the file is believed to be executable by the user.
  259. */
  260. public abstract boolean canExecute(File f);
  261. /**
  262. * Set a file to be executable by the user.
  263. * <p>
  264. * Not all platforms and JREs support executable flags on files. If the
  265. * feature is unsupported this method will always return false and no
  266. * changes will be made to the file specified.
  267. *
  268. * @param f
  269. * path to modify the executable status of.
  270. * @param canExec
  271. * true to enable execution; false to disable it.
  272. * @return true if the change succeeded; false otherwise.
  273. */
  274. public abstract boolean setExecute(File f, boolean canExec);
  275. /**
  276. * Get the last modified time of a file system object. If the OS/JRE support
  277. * symbolic links, the modification time of the link is returned, rather
  278. * than that of the link target.
  279. *
  280. * @param f
  281. * @return last modified time of f
  282. * @throws IOException
  283. * @since 3.0
  284. */
  285. public long lastModified(File f) throws IOException {
  286. return FileUtils.lastModified(f);
  287. }
  288. /**
  289. * Set the last modified time of a file system object. If the OS/JRE support
  290. * symbolic links, the link is modified, not the target,
  291. *
  292. * @param f
  293. * @param time
  294. * @throws IOException
  295. * @since 3.0
  296. */
  297. public void setLastModified(File f, long time) throws IOException {
  298. FileUtils.setLastModified(f, time);
  299. }
  300. /**
  301. * Get the length of a file or link, If the OS/JRE supports symbolic links
  302. * it's the length of the link, else the length of the target.
  303. *
  304. * @param path
  305. * @return length of a file
  306. * @throws IOException
  307. * @since 3.0
  308. */
  309. public long length(File path) throws IOException {
  310. return FileUtils.getLength(path);
  311. }
  312. /**
  313. * Delete a file. Throws an exception if delete fails.
  314. *
  315. * @param f
  316. * @throws IOException
  317. * this may be a Java7 subclass with detailed information
  318. * @since 3.3
  319. */
  320. public void delete(File f) throws IOException {
  321. FileUtils.delete(f);
  322. }
  323. /**
  324. * Resolve this file to its actual path name that the JRE can use.
  325. * <p>
  326. * This method can be relatively expensive. Computing a translation may
  327. * require forking an external process per path name translated. Callers
  328. * should try to minimize the number of translations necessary by caching
  329. * the results.
  330. * <p>
  331. * Not all platforms and JREs require path name translation. Currently only
  332. * Cygwin on Win32 require translation for Cygwin based paths.
  333. *
  334. * @param dir
  335. * directory relative to which the path name is.
  336. * @param name
  337. * path name to translate.
  338. * @return the translated path. <code>new File(dir,name)</code> if this
  339. * platform does not require path name translation.
  340. */
  341. public File resolve(final File dir, final String name) {
  342. final File abspn = new File(name);
  343. if (abspn.isAbsolute())
  344. return abspn;
  345. return new File(dir, name);
  346. }
  347. /**
  348. * Determine the user's home directory (location where preferences are).
  349. * <p>
  350. * This method can be expensive on the first invocation if path name
  351. * translation is required. Subsequent invocations return a cached result.
  352. * <p>
  353. * Not all platforms and JREs require path name translation. Currently only
  354. * Cygwin on Win32 requires translation of the Cygwin HOME directory.
  355. *
  356. * @return the user's home directory; null if the user does not have one.
  357. */
  358. public File userHome() {
  359. Holder<File> p = userHome;
  360. if (p == null) {
  361. p = new Holder<File>(userHomeImpl());
  362. userHome = p;
  363. }
  364. return p.value;
  365. }
  366. /**
  367. * Set the user's home directory location.
  368. *
  369. * @param path
  370. * the location of the user's preferences; null if there is no
  371. * home directory for the current user.
  372. * @return {@code this}.
  373. */
  374. public FS setUserHome(File path) {
  375. userHome = new Holder<File>(path);
  376. return this;
  377. }
  378. /**
  379. * Does this file system have problems with atomic renames?
  380. *
  381. * @return true if the caller should retry a failed rename of a lock file.
  382. */
  383. public abstract boolean retryFailedLockFileCommit();
  384. /**
  385. * Return all the attributes of a file, without following symbolic links.
  386. *
  387. * @param file
  388. * @return {@link BasicFileAttributes} of the file
  389. * @throws IOException in case of any I/O errors accessing the file
  390. *
  391. * @since 4.5.6
  392. */
  393. public BasicFileAttributes fileAttributes(File file) throws IOException {
  394. return FileUtils.fileAttributes(file);
  395. }
  396. /**
  397. * Determine the user's home directory (location where preferences are).
  398. *
  399. * @return the user's home directory; null if the user does not have one.
  400. */
  401. protected File userHomeImpl() {
  402. final String home = AccessController
  403. .doPrivileged(new PrivilegedAction<String>() {
  404. public String run() {
  405. return System.getProperty("user.home"); //$NON-NLS-1$
  406. }
  407. });
  408. if (home == null || home.length() == 0)
  409. return null;
  410. return new File(home).getAbsoluteFile();
  411. }
  412. /**
  413. * Searches the given path to see if it contains one of the given files.
  414. * Returns the first it finds. Returns null if not found or if path is null.
  415. *
  416. * @param path
  417. * List of paths to search separated by File.pathSeparator
  418. * @param lookFor
  419. * Files to search for in the given path
  420. * @return the first match found, or null
  421. * @since 3.0
  422. **/
  423. protected static File searchPath(final String path, final String... lookFor) {
  424. if (path == null)
  425. return null;
  426. for (final String p : path.split(File.pathSeparator)) {
  427. for (String command : lookFor) {
  428. final File e = new File(p, command);
  429. if (e.isFile())
  430. return e.getAbsoluteFile();
  431. }
  432. }
  433. return null;
  434. }
  435. /**
  436. * Execute a command and return a single line of output as a String
  437. *
  438. * @param dir
  439. * Working directory for the command
  440. * @param command
  441. * as component array
  442. * @param encoding
  443. * to be used to parse the command's output
  444. * @return the one-line output of the command or {@code null} if there is
  445. * none
  446. * @throws CommandFailedException
  447. * thrown when the command failed (return code was non-zero)
  448. */
  449. @Nullable
  450. protected static String readPipe(File dir, String[] command,
  451. String encoding) throws CommandFailedException {
  452. return readPipe(dir, command, encoding, null);
  453. }
  454. /**
  455. * Execute a command and return a single line of output as a String
  456. *
  457. * @param dir
  458. * Working directory for the command
  459. * @param command
  460. * as component array
  461. * @param encoding
  462. * to be used to parse the command's output
  463. * @param env
  464. * Map of environment variables to be merged with those of the
  465. * current process
  466. * @return the one-line output of the command or {@code null} if there is
  467. * none
  468. * @throws CommandFailedException
  469. * thrown when the command failed (return code was non-zero)
  470. * @since 4.0
  471. */
  472. @Nullable
  473. protected static String readPipe(File dir, String[] command,
  474. String encoding, Map<String, String> env)
  475. throws CommandFailedException {
  476. final boolean debug = LOG.isDebugEnabled();
  477. try {
  478. if (debug) {
  479. LOG.debug("readpipe " + Arrays.asList(command) + "," //$NON-NLS-1$ //$NON-NLS-2$
  480. + dir);
  481. }
  482. ProcessBuilder pb = new ProcessBuilder(command);
  483. pb.directory(dir);
  484. if (env != null) {
  485. pb.environment().putAll(env);
  486. }
  487. Process p = pb.start();
  488. p.getOutputStream().close();
  489. GobblerThread gobbler = new GobblerThread(p, command, dir);
  490. gobbler.start();
  491. String r = null;
  492. try (BufferedReader lineRead = new BufferedReader(
  493. new InputStreamReader(p.getInputStream(), encoding))) {
  494. r = lineRead.readLine();
  495. if (debug) {
  496. LOG.debug("readpipe may return '" + r + "'"); //$NON-NLS-1$ //$NON-NLS-2$
  497. LOG.debug("remaining output:\n"); //$NON-NLS-1$
  498. String l;
  499. while ((l = lineRead.readLine()) != null) {
  500. LOG.debug(l);
  501. }
  502. }
  503. }
  504. for (;;) {
  505. try {
  506. int rc = p.waitFor();
  507. gobbler.join();
  508. if (rc == 0 && !gobbler.fail.get()) {
  509. return r;
  510. } else {
  511. if (debug) {
  512. LOG.debug("readpipe rc=" + rc); //$NON-NLS-1$
  513. }
  514. throw new CommandFailedException(rc,
  515. gobbler.errorMessage.get(),
  516. gobbler.exception.get());
  517. }
  518. } catch (InterruptedException ie) {
  519. // Stop bothering me, I have a zombie to reap.
  520. }
  521. }
  522. } catch (IOException e) {
  523. LOG.error("Caught exception in FS.readPipe()", e); //$NON-NLS-1$
  524. }
  525. if (debug) {
  526. LOG.debug("readpipe returns null"); //$NON-NLS-1$
  527. }
  528. return null;
  529. }
  530. private static class GobblerThread extends Thread {
  531. private final Process p;
  532. private final String desc;
  533. private final String dir;
  534. final AtomicBoolean fail = new AtomicBoolean();
  535. final AtomicReference<String> errorMessage = new AtomicReference<>();
  536. final AtomicReference<Throwable> exception = new AtomicReference<>();
  537. GobblerThread(Process p, String[] command, File dir) {
  538. this.p = p;
  539. this.desc = Arrays.toString(command);
  540. this.dir = Objects.toString(dir);
  541. }
  542. @Override
  543. public void run() {
  544. StringBuilder err = new StringBuilder();
  545. try (InputStream is = p.getErrorStream()) {
  546. int ch;
  547. while ((ch = is.read()) != -1) {
  548. err.append((char) ch);
  549. }
  550. } catch (IOException e) {
  551. if (p.exitValue() != 0) {
  552. setError(e, e.getMessage());
  553. fail.set(true);
  554. } else {
  555. // ignore. command terminated faster and stream was just closed
  556. }
  557. } finally {
  558. if (err.length() > 0) {
  559. setError(null, err.toString());
  560. if (p.exitValue() != 0) {
  561. fail.set(true);
  562. }
  563. }
  564. }
  565. }
  566. private void setError(IOException e, String message) {
  567. exception.set(e);
  568. errorMessage.set(MessageFormat.format(
  569. JGitText.get().exceptionCaughtDuringExcecutionOfCommand,
  570. desc, dir, Integer.valueOf(p.exitValue()), message));
  571. }
  572. }
  573. /**
  574. * @return the path to the Git executable or {@code null} if it cannot be
  575. * determined.
  576. * @since 4.0
  577. */
  578. protected abstract File discoverGitExe();
  579. /**
  580. * @return the path to the system-wide Git configuration file or
  581. * {@code null} if it cannot be determined.
  582. * @since 4.0
  583. */
  584. protected File discoverGitSystemConfig() {
  585. File gitExe = discoverGitExe();
  586. if (gitExe == null) {
  587. return null;
  588. }
  589. // Bug 480782: Check if the discovered git executable is JGit CLI
  590. String v;
  591. try {
  592. v = readPipe(gitExe.getParentFile(),
  593. new String[] { "git", "--version" }, //$NON-NLS-1$ //$NON-NLS-2$
  594. Charset.defaultCharset().name());
  595. } catch (CommandFailedException e) {
  596. LOG.warn(e.getMessage());
  597. return null;
  598. }
  599. if (StringUtils.isEmptyOrNull(v)
  600. || (v != null && v.startsWith("jgit"))) { //$NON-NLS-1$
  601. return null;
  602. }
  603. // Trick Git into printing the path to the config file by using "echo"
  604. // as the editor.
  605. Map<String, String> env = new HashMap<>();
  606. env.put("GIT_EDITOR", "echo"); //$NON-NLS-1$ //$NON-NLS-2$
  607. String w;
  608. try {
  609. w = readPipe(gitExe.getParentFile(),
  610. new String[] { "git", "config", "--system", "--edit" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  611. Charset.defaultCharset().name(), env);
  612. } catch (CommandFailedException e) {
  613. LOG.warn(e.getMessage());
  614. return null;
  615. }
  616. if (StringUtils.isEmptyOrNull(w)) {
  617. return null;
  618. }
  619. return new File(w);
  620. }
  621. /**
  622. * @return the currently used path to the system-wide Git configuration
  623. * file or {@code null} if none has been set.
  624. * @since 4.0
  625. */
  626. public File getGitSystemConfig() {
  627. if (gitSystemConfig == null) {
  628. gitSystemConfig = new Holder<File>(discoverGitSystemConfig());
  629. }
  630. return gitSystemConfig.value;
  631. }
  632. /**
  633. * Set the path to the system-wide Git configuration file to use.
  634. *
  635. * @param configFile
  636. * the path to the config file.
  637. * @return {@code this}
  638. * @since 4.0
  639. */
  640. public FS setGitSystemConfig(File configFile) {
  641. gitSystemConfig = new Holder<File>(configFile);
  642. return this;
  643. }
  644. /**
  645. * @param grandchild
  646. * @return the parent directory of this file's parent directory or
  647. * {@code null} in case there's no grandparent directory
  648. * @since 4.0
  649. */
  650. protected static File resolveGrandparentFile(File grandchild) {
  651. if (grandchild != null) {
  652. File parent = grandchild.getParentFile();
  653. if (parent != null)
  654. return parent.getParentFile();
  655. }
  656. return null;
  657. }
  658. /**
  659. * Check if a file is a symbolic link and read it
  660. *
  661. * @param path
  662. * @return target of link or null
  663. * @throws IOException
  664. * @since 3.0
  665. */
  666. public String readSymLink(File path) throws IOException {
  667. return FileUtils.readSymLink(path);
  668. }
  669. /**
  670. * @param path
  671. * @return true if the path is a symbolic link (and we support these)
  672. * @throws IOException
  673. * @since 3.0
  674. */
  675. public boolean isSymLink(File path) throws IOException {
  676. return FileUtils.isSymlink(path);
  677. }
  678. /**
  679. * Tests if the path exists, in case of a symbolic link, true even if the
  680. * target does not exist
  681. *
  682. * @param path
  683. * @return true if path exists
  684. * @since 3.0
  685. */
  686. public boolean exists(File path) {
  687. return FileUtils.exists(path);
  688. }
  689. /**
  690. * Check if path is a directory. If the OS/JRE supports symbolic links and
  691. * path is a symbolic link to a directory, this method returns false.
  692. *
  693. * @param path
  694. * @return true if file is a directory,
  695. * @since 3.0
  696. */
  697. public boolean isDirectory(File path) {
  698. return FileUtils.isDirectory(path);
  699. }
  700. /**
  701. * Examine if path represents a regular file. If the OS/JRE supports
  702. * symbolic links the test returns false if path represents a symbolic link.
  703. *
  704. * @param path
  705. * @return true if path represents a regular file
  706. * @since 3.0
  707. */
  708. public boolean isFile(File path) {
  709. return FileUtils.isFile(path);
  710. }
  711. /**
  712. * @param path
  713. * @return true if path is hidden, either starts with . on unix or has the
  714. * hidden attribute in windows
  715. * @throws IOException
  716. * @since 3.0
  717. */
  718. public boolean isHidden(File path) throws IOException {
  719. return FileUtils.isHidden(path);
  720. }
  721. /**
  722. * Set the hidden attribute for file whose name starts with a period.
  723. *
  724. * @param path
  725. * @param hidden
  726. * @throws IOException
  727. * @since 3.0
  728. */
  729. public void setHidden(File path, boolean hidden) throws IOException {
  730. FileUtils.setHidden(path, hidden);
  731. }
  732. /**
  733. * Create a symbolic link
  734. *
  735. * @param path
  736. * @param target
  737. * @throws IOException
  738. * @since 3.0
  739. */
  740. public void createSymLink(File path, String target) throws IOException {
  741. FileUtils.createSymLink(path, target);
  742. }
  743. /**
  744. * Create a new file. See {@link File#createNewFile()}. Subclasses of this
  745. * class may take care to provide a safe implementation for this even if
  746. * {@link #supportsAtomicCreateNewFile()} is <code>false</code>
  747. *
  748. * @param path
  749. * the file to be created
  750. * @return <code>true</code> if the file was created, <code>false</code> if
  751. * the file already existed
  752. * @throws IOException
  753. * @since 4.5
  754. */
  755. public boolean createNewFile(File path) throws IOException {
  756. return path.createNewFile();
  757. }
  758. /**
  759. * See {@link FileUtils#relativize(String, String)}.
  760. *
  761. * @param base
  762. * The path against which <code>other</code> should be
  763. * relativized.
  764. * @param other
  765. * The path that will be made relative to <code>base</code>.
  766. * @return A relative path that, when resolved against <code>base</code>,
  767. * will yield the original <code>other</code>.
  768. * @see FileUtils#relativize(String, String)
  769. * @since 3.7
  770. */
  771. public String relativize(String base, String other) {
  772. return FileUtils.relativize(base, other);
  773. }
  774. /**
  775. * Checks whether the given hook is defined for the given repository, then
  776. * runs it with the given arguments.
  777. * <p>
  778. * The hook's standard output and error streams will be redirected to
  779. * <code>System.out</code> and <code>System.err</code> respectively. The
  780. * hook will have no stdin.
  781. * </p>
  782. *
  783. * @param repository
  784. * The repository for which a hook should be run.
  785. * @param hookName
  786. * The name of the hook to be executed.
  787. * @param args
  788. * Arguments to pass to this hook. Cannot be <code>null</code>,
  789. * but can be an empty array.
  790. * @return The ProcessResult describing this hook's execution.
  791. * @throws JGitInternalException
  792. * if we fail to run the hook somehow. Causes may include an
  793. * interrupted process or I/O errors.
  794. * @since 4.0
  795. */
  796. public ProcessResult runHookIfPresent(Repository repository,
  797. final String hookName,
  798. String[] args) throws JGitInternalException {
  799. return runHookIfPresent(repository, hookName, args, System.out, System.err,
  800. null);
  801. }
  802. /**
  803. * Checks whether the given hook is defined for the given repository, then
  804. * runs it with the given arguments.
  805. *
  806. * @param repository
  807. * The repository for which a hook should be run.
  808. * @param hookName
  809. * The name of the hook to be executed.
  810. * @param args
  811. * Arguments to pass to this hook. Cannot be <code>null</code>,
  812. * but can be an empty array.
  813. * @param outRedirect
  814. * A print stream on which to redirect the hook's stdout. Can be
  815. * <code>null</code>, in which case the hook's standard output
  816. * will be lost.
  817. * @param errRedirect
  818. * A print stream on which to redirect the hook's stderr. Can be
  819. * <code>null</code>, in which case the hook's standard error
  820. * will be lost.
  821. * @param stdinArgs
  822. * A string to pass on to the standard input of the hook. May be
  823. * <code>null</code>.
  824. * @return The ProcessResult describing this hook's execution.
  825. * @throws JGitInternalException
  826. * if we fail to run the hook somehow. Causes may include an
  827. * interrupted process or I/O errors.
  828. * @since 4.0
  829. */
  830. public ProcessResult runHookIfPresent(Repository repository,
  831. final String hookName,
  832. String[] args, PrintStream outRedirect, PrintStream errRedirect,
  833. String stdinArgs) throws JGitInternalException {
  834. return new ProcessResult(Status.NOT_SUPPORTED);
  835. }
  836. /**
  837. * See
  838. * {@link #runHookIfPresent(Repository, String, String[], PrintStream, PrintStream, String)}
  839. * . Should only be called by FS supporting shell scripts execution.
  840. *
  841. * @param repository
  842. * The repository for which a hook should be run.
  843. * @param hookName
  844. * The name of the hook to be executed.
  845. * @param args
  846. * Arguments to pass to this hook. Cannot be <code>null</code>,
  847. * but can be an empty array.
  848. * @param outRedirect
  849. * A print stream on which to redirect the hook's stdout. Can be
  850. * <code>null</code>, in which case the hook's standard output
  851. * will be lost.
  852. * @param errRedirect
  853. * A print stream on which to redirect the hook's stderr. Can be
  854. * <code>null</code>, in which case the hook's standard error
  855. * will be lost.
  856. * @param stdinArgs
  857. * A string to pass on to the standard input of the hook. May be
  858. * <code>null</code>.
  859. * @return The ProcessResult describing this hook's execution.
  860. * @throws JGitInternalException
  861. * if we fail to run the hook somehow. Causes may include an
  862. * interrupted process or I/O errors.
  863. * @since 4.0
  864. */
  865. protected ProcessResult internalRunHookIfPresent(Repository repository,
  866. final String hookName, String[] args, PrintStream outRedirect,
  867. PrintStream errRedirect, String stdinArgs)
  868. throws JGitInternalException {
  869. final File hookFile = findHook(repository, hookName);
  870. if (hookFile == null)
  871. return new ProcessResult(Status.NOT_PRESENT);
  872. final String hookPath = hookFile.getAbsolutePath();
  873. final File runDirectory;
  874. if (repository.isBare())
  875. runDirectory = repository.getDirectory();
  876. else
  877. runDirectory = repository.getWorkTree();
  878. final String cmd = relativize(runDirectory.getAbsolutePath(),
  879. hookPath);
  880. ProcessBuilder hookProcess = runInShell(cmd, args);
  881. hookProcess.directory(runDirectory);
  882. try {
  883. return new ProcessResult(runProcess(hookProcess, outRedirect,
  884. errRedirect, stdinArgs), Status.OK);
  885. } catch (IOException e) {
  886. throw new JGitInternalException(MessageFormat.format(
  887. JGitText.get().exceptionCaughtDuringExecutionOfHook,
  888. hookName), e);
  889. } catch (InterruptedException e) {
  890. throw new JGitInternalException(MessageFormat.format(
  891. JGitText.get().exceptionHookExecutionInterrupted,
  892. hookName), e);
  893. }
  894. }
  895. /**
  896. * Tries to find a hook matching the given one in the given repository.
  897. *
  898. * @param repository
  899. * The repository within which to find a hook.
  900. * @param hookName
  901. * The name of the hook we're trying to find.
  902. * @return The {@link File} containing this particular hook if it exists in
  903. * the given repository, <code>null</code> otherwise.
  904. * @since 4.0
  905. */
  906. public File findHook(Repository repository, final String hookName) {
  907. File gitDir = repository.getDirectory();
  908. if (gitDir == null)
  909. return null;
  910. final File hookFile = new File(new File(gitDir,
  911. Constants.HOOKS), hookName);
  912. return hookFile.isFile() ? hookFile : null;
  913. }
  914. /**
  915. * Runs the given process until termination, clearing its stdout and stderr
  916. * streams on-the-fly.
  917. *
  918. * @param processBuilder
  919. * The process builder configured for this process.
  920. * @param outRedirect
  921. * A OutputStream on which to redirect the processes stdout. Can
  922. * be <code>null</code>, in which case the processes standard
  923. * output will be lost.
  924. * @param errRedirect
  925. * A OutputStream on which to redirect the processes stderr. Can
  926. * be <code>null</code>, in which case the processes standard
  927. * error will be lost.
  928. * @param stdinArgs
  929. * A string to pass on to the standard input of the hook. Can be
  930. * <code>null</code>.
  931. * @return the exit value of this process.
  932. * @throws IOException
  933. * if an I/O error occurs while executing this process.
  934. * @throws InterruptedException
  935. * if the current thread is interrupted while waiting for the
  936. * process to end.
  937. * @since 4.2
  938. */
  939. public int runProcess(ProcessBuilder processBuilder,
  940. OutputStream outRedirect, OutputStream errRedirect, String stdinArgs)
  941. throws IOException, InterruptedException {
  942. InputStream in = (stdinArgs == null) ? null : new ByteArrayInputStream(
  943. stdinArgs.getBytes(Constants.CHARACTER_ENCODING));
  944. return runProcess(processBuilder, outRedirect, errRedirect, in);
  945. }
  946. /**
  947. * Runs the given process until termination, clearing its stdout and stderr
  948. * streams on-the-fly.
  949. *
  950. * @param processBuilder
  951. * The process builder configured for this process.
  952. * @param outRedirect
  953. * An OutputStream on which to redirect the processes stdout. Can
  954. * be <code>null</code>, in which case the processes standard
  955. * output will be lost.
  956. * @param errRedirect
  957. * An OutputStream on which to redirect the processes stderr. Can
  958. * be <code>null</code>, in which case the processes standard
  959. * error will be lost.
  960. * @param inRedirect
  961. * An InputStream from which to redirect the processes stdin. Can
  962. * be <code>null</code>, in which case the process doesn't get
  963. * any data over stdin. It is assumed that the whole InputStream
  964. * will be consumed by the process. The method will close the
  965. * inputstream after all bytes are read.
  966. * @return the return code of this process.
  967. * @throws IOException
  968. * if an I/O error occurs while executing this process.
  969. * @throws InterruptedException
  970. * if the current thread is interrupted while waiting for the
  971. * process to end.
  972. * @since 4.2
  973. */
  974. public int runProcess(ProcessBuilder processBuilder,
  975. OutputStream outRedirect, OutputStream errRedirect,
  976. InputStream inRedirect) throws IOException,
  977. InterruptedException {
  978. final ExecutorService executor = Executors.newFixedThreadPool(2);
  979. Process process = null;
  980. // We'll record the first I/O exception that occurs, but keep on trying
  981. // to dispose of our open streams and file handles
  982. IOException ioException = null;
  983. try {
  984. process = processBuilder.start();
  985. final Callable<Void> errorGobbler = new StreamGobbler(
  986. process.getErrorStream(), errRedirect);
  987. final Callable<Void> outputGobbler = new StreamGobbler(
  988. process.getInputStream(), outRedirect);
  989. executor.submit(errorGobbler);
  990. executor.submit(outputGobbler);
  991. OutputStream outputStream = process.getOutputStream();
  992. if (inRedirect != null) {
  993. new StreamGobbler(inRedirect, outputStream)
  994. .call();
  995. }
  996. try {
  997. outputStream.close();
  998. } catch (IOException e) {
  999. // When the process exits before consuming the input, the OutputStream
  1000. // is replaced with the null output stream. This null output stream
  1001. // throws IOException for all write calls. When StreamGobbler fails to
  1002. // flush the buffer because of this, this close call tries to flush it
  1003. // again. This causes another IOException. Since we ignore the
  1004. // IOException in StreamGobbler, we also ignore the exception here.
  1005. }
  1006. return process.waitFor();
  1007. } catch (IOException e) {
  1008. ioException = e;
  1009. } finally {
  1010. shutdownAndAwaitTermination(executor);
  1011. if (process != null) {
  1012. try {
  1013. process.waitFor();
  1014. } catch (InterruptedException e) {
  1015. // Thrown by the outer try.
  1016. // Swallow this one to carry on our cleanup, and clear the
  1017. // interrupted flag (processes throw the exception without
  1018. // clearing the flag).
  1019. Thread.interrupted();
  1020. }
  1021. // A process doesn't clean its own resources even when destroyed
  1022. // Explicitly try and close all three streams, preserving the
  1023. // outer I/O exception if any.
  1024. if (inRedirect != null) {
  1025. inRedirect.close();
  1026. }
  1027. try {
  1028. process.getErrorStream().close();
  1029. } catch (IOException e) {
  1030. ioException = ioException != null ? ioException : e;
  1031. }
  1032. try {
  1033. process.getInputStream().close();
  1034. } catch (IOException e) {
  1035. ioException = ioException != null ? ioException : e;
  1036. }
  1037. try {
  1038. process.getOutputStream().close();
  1039. } catch (IOException e) {
  1040. ioException = ioException != null ? ioException : e;
  1041. }
  1042. process.destroy();
  1043. }
  1044. }
  1045. // We can only be here if the outer try threw an IOException.
  1046. throw ioException;
  1047. }
  1048. /**
  1049. * Shuts down an {@link ExecutorService} in two phases, first by calling
  1050. * {@link ExecutorService#shutdown() shutdown} to reject incoming tasks, and
  1051. * then calling {@link ExecutorService#shutdownNow() shutdownNow}, if
  1052. * necessary, to cancel any lingering tasks. Returns true if the pool has
  1053. * been properly shutdown, false otherwise.
  1054. * <p>
  1055. *
  1056. * @param pool
  1057. * the pool to shutdown
  1058. * @return <code>true</code> if the pool has been properly shutdown,
  1059. * <code>false</code> otherwise.
  1060. */
  1061. private static boolean shutdownAndAwaitTermination(ExecutorService pool) {
  1062. boolean hasShutdown = true;
  1063. pool.shutdown(); // Disable new tasks from being submitted
  1064. try {
  1065. // Wait a while for existing tasks to terminate
  1066. if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
  1067. pool.shutdownNow(); // Cancel currently executing tasks
  1068. // Wait a while for tasks to respond to being canceled
  1069. if (!pool.awaitTermination(60, TimeUnit.SECONDS))
  1070. hasShutdown = false;
  1071. }
  1072. } catch (InterruptedException ie) {
  1073. // (Re-)Cancel if current thread also interrupted
  1074. pool.shutdownNow();
  1075. // Preserve interrupt status
  1076. Thread.currentThread().interrupt();
  1077. hasShutdown = false;
  1078. }
  1079. return hasShutdown;
  1080. }
  1081. /**
  1082. * Initialize a ProcessBuilder to run a command using the system shell.
  1083. *
  1084. * @param cmd
  1085. * command to execute. This string should originate from the
  1086. * end-user, and thus is platform specific.
  1087. * @param args
  1088. * arguments to pass to command. These should be protected from
  1089. * shell evaluation.
  1090. * @return a partially completed process builder. Caller should finish
  1091. * populating directory, environment, and then start the process.
  1092. */
  1093. public abstract ProcessBuilder runInShell(String cmd, String[] args);
  1094. /**
  1095. * Execute a command defined by a {@link ProcessBuilder}.
  1096. *
  1097. * @param pb
  1098. * The command to be executed
  1099. * @param in
  1100. * The standard input stream passed to the process
  1101. * @return The result of the executed command
  1102. * @throws InterruptedException
  1103. * @throws IOException
  1104. * @since 4.2
  1105. */
  1106. public ExecutionResult execute(ProcessBuilder pb, InputStream in)
  1107. throws IOException, InterruptedException {
  1108. TemporaryBuffer stdout = new TemporaryBuffer.LocalFile(null);
  1109. TemporaryBuffer stderr = new TemporaryBuffer.Heap(1024, 1024 * 1024);
  1110. try {
  1111. int rc = runProcess(pb, stdout, stderr, in);
  1112. return new ExecutionResult(stdout, stderr, rc);
  1113. } finally {
  1114. stdout.close();
  1115. stderr.close();
  1116. }
  1117. }
  1118. private static class Holder<V> {
  1119. final V value;
  1120. Holder(V value) {
  1121. this.value = value;
  1122. }
  1123. }
  1124. /**
  1125. * File attributes we typically care for.
  1126. *
  1127. * @since 3.3
  1128. */
  1129. public static class Attributes {
  1130. /**
  1131. * @return true if this are the attributes of a directory
  1132. */
  1133. public boolean isDirectory() {
  1134. return isDirectory;
  1135. }
  1136. /**
  1137. * @return true if this are the attributes of an executable file
  1138. */
  1139. public boolean isExecutable() {
  1140. return isExecutable;
  1141. }
  1142. /**
  1143. * @return true if this are the attributes of a symbolic link
  1144. */
  1145. public boolean isSymbolicLink() {
  1146. return isSymbolicLink;
  1147. }
  1148. /**
  1149. * @return true if this are the attributes of a regular file
  1150. */
  1151. public boolean isRegularFile() {
  1152. return isRegularFile;
  1153. }
  1154. /**
  1155. * @return the time when the file was created
  1156. */
  1157. public long getCreationTime() {
  1158. return creationTime;
  1159. }
  1160. /**
  1161. * @return the time (milliseconds since 1970-01-01) when this object was
  1162. * last modified
  1163. */
  1164. public long getLastModifiedTime() {
  1165. return lastModifiedTime;
  1166. }
  1167. private final boolean isDirectory;
  1168. private final boolean isSymbolicLink;
  1169. private final boolean isRegularFile;
  1170. private final long creationTime;
  1171. private final long lastModifiedTime;
  1172. private final boolean isExecutable;
  1173. private final File file;
  1174. private final boolean exists;
  1175. /**
  1176. * file length
  1177. */
  1178. protected long length = -1;
  1179. final FS fs;
  1180. Attributes(FS fs, File file, boolean exists, boolean isDirectory,
  1181. boolean isExecutable, boolean isSymbolicLink,
  1182. boolean isRegularFile, long creationTime,
  1183. long lastModifiedTime, long length) {
  1184. this.fs = fs;
  1185. this.file = file;
  1186. this.exists = exists;
  1187. this.isDirectory = isDirectory;
  1188. this.isExecutable = isExecutable;
  1189. this.isSymbolicLink = isSymbolicLink;
  1190. this.isRegularFile = isRegularFile;
  1191. this.creationTime = creationTime;
  1192. this.lastModifiedTime = lastModifiedTime;
  1193. this.length = length;
  1194. }
  1195. /**
  1196. * Constructor when there are issues with reading. All attributes except
  1197. * given will be set to the default values.
  1198. *
  1199. * @param fs
  1200. * @param path
  1201. */
  1202. public Attributes(File path, FS fs) {
  1203. this(fs, path, false, false, false, false, false, 0L, 0L, 0L);
  1204. }
  1205. /**
  1206. * @return length of this file object
  1207. */
  1208. public long getLength() {
  1209. if (length == -1)
  1210. return length = file.length();
  1211. return length;
  1212. }
  1213. /**
  1214. * @return the filename
  1215. */
  1216. public String getName() {
  1217. return file.getName();
  1218. }
  1219. /**
  1220. * @return the file the attributes apply to
  1221. */
  1222. public File getFile() {
  1223. return file;
  1224. }
  1225. boolean exists() {
  1226. return exists;
  1227. }
  1228. }
  1229. /**
  1230. * @param path
  1231. * @return the file attributes we care for
  1232. * @since 3.3
  1233. */
  1234. public Attributes getAttributes(File path) {
  1235. boolean isDirectory = isDirectory(path);
  1236. boolean isFile = !isDirectory && path.isFile();
  1237. assert path.exists() == isDirectory || isFile;
  1238. boolean exists = isDirectory || isFile;
  1239. boolean canExecute = exists && !isDirectory && canExecute(path);
  1240. boolean isSymlink = false;
  1241. long lastModified = exists ? path.lastModified() : 0L;
  1242. long createTime = 0L;
  1243. return new Attributes(this, path, exists, isDirectory, canExecute,
  1244. isSymlink, isFile, createTime, lastModified, -1);
  1245. }
  1246. /**
  1247. * Normalize the unicode path to composed form.
  1248. *
  1249. * @param file
  1250. * @return NFC-format File
  1251. * @since 3.3
  1252. */
  1253. public File normalize(File file) {
  1254. return file;
  1255. }
  1256. /**
  1257. * Normalize the unicode path to composed form.
  1258. *
  1259. * @param name
  1260. * @return NFC-format string
  1261. * @since 3.3
  1262. */
  1263. public String normalize(String name) {
  1264. return name;
  1265. }
  1266. /**
  1267. * This runnable will consume an input stream's content into an output
  1268. * stream as soon as it gets available.
  1269. * <p>
  1270. * Typically used to empty processes' standard output and error, preventing
  1271. * them to choke.
  1272. * </p>
  1273. * <p>
  1274. * <b>Note</b> that a {@link StreamGobbler} will never close either of its
  1275. * streams.
  1276. * </p>
  1277. */
  1278. private static class StreamGobbler implements Callable<Void> {
  1279. private InputStream in;
  1280. private OutputStream out;
  1281. public StreamGobbler(InputStream stream, OutputStream output) {
  1282. this.in = stream;
  1283. this.out = output;
  1284. }
  1285. public Void call() throws IOException {
  1286. boolean writeFailure = false;
  1287. byte buffer[] = new byte[4096];
  1288. int readBytes;
  1289. while ((readBytes = in.read(buffer)) != -1) {
  1290. // Do not try to write again after a failure, but keep
  1291. // reading as long as possible to prevent the input stream
  1292. // from choking.
  1293. if (!writeFailure && out != null) {
  1294. try {
  1295. out.write(buffer, 0, readBytes);
  1296. out.flush();
  1297. } catch (IOException e) {
  1298. writeFailure = true;
  1299. }
  1300. }
  1301. }
  1302. return null;
  1303. }
  1304. }
  1305. }