You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ResourceUtils.java 37 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package org.apache.tools.ant.util;
  19. import java.io.BufferedInputStream;
  20. import java.io.BufferedReader;
  21. import java.io.BufferedWriter;
  22. import java.io.File;
  23. import java.io.FileInputStream;
  24. import java.io.FileOutputStream;
  25. import java.io.IOException;
  26. import java.io.InputStream;
  27. import java.io.InputStreamReader;
  28. import java.io.OutputStream;
  29. import java.io.OutputStreamWriter;
  30. import java.io.Reader;
  31. import java.nio.channels.FileChannel;
  32. import java.util.Arrays;
  33. import java.util.Vector;
  34. import org.apache.tools.ant.Project;
  35. import org.apache.tools.ant.ProjectComponent;
  36. import org.apache.tools.ant.filters.util.ChainReaderHelper;
  37. import org.apache.tools.ant.types.FilterSetCollection;
  38. import org.apache.tools.ant.types.Resource;
  39. import org.apache.tools.ant.types.ResourceCollection;
  40. import org.apache.tools.ant.types.ResourceFactory;
  41. import org.apache.tools.ant.types.TimeComparison;
  42. import org.apache.tools.ant.types.resources.Appendable;
  43. import org.apache.tools.ant.types.resources.FileProvider;
  44. import org.apache.tools.ant.types.resources.FileResource;
  45. import org.apache.tools.ant.types.resources.Resources;
  46. import org.apache.tools.ant.types.resources.Restrict;
  47. import org.apache.tools.ant.types.resources.StringResource;
  48. import org.apache.tools.ant.types.resources.Touchable;
  49. import org.apache.tools.ant.types.resources.Union;
  50. import org.apache.tools.ant.types.resources.selectors.Date;
  51. import org.apache.tools.ant.types.resources.selectors.ResourceSelector;
  52. import org.apache.tools.ant.types.selectors.SelectorUtils;
  53. // CheckStyle:HideUtilityClassConstructorCheck OFF - bc
  54. /**
  55. * This class provides utility methods to process Resources.
  56. *
  57. * @since Ant 1.5.2
  58. */
  59. public class ResourceUtils {
  60. /** Utilities used for file operations */
  61. private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
  62. /**
  63. * Name of charset "ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1".
  64. *
  65. * @since Ant 1.8.1
  66. */
  67. public static final String ISO_8859_1 = "ISO-8859-1";
  68. private static final long MAX_IO_CHUNK_SIZE = 16*1024*1024l; // 16 MB
  69. /**
  70. * Tells which source files should be reprocessed based on the
  71. * last modification date of target files.
  72. * @param logTo where to send (more or less) interesting output.
  73. * @param source array of resources bearing relative path and last
  74. * modification date.
  75. * @param mapper filename mapper indicating how to find the target
  76. * files.
  77. * @param targets object able to map as a resource a relative path
  78. * at <b>destination</b>.
  79. * @return array containing the source files which need to be
  80. * copied or processed, because the targets are out of date or do
  81. * not exist.
  82. */
  83. public static Resource[] selectOutOfDateSources(final ProjectComponent logTo,
  84. final Resource[] source,
  85. final FileNameMapper mapper,
  86. final ResourceFactory targets) {
  87. return selectOutOfDateSources(logTo, source, mapper, targets,
  88. FILE_UTILS.getFileTimestampGranularity());
  89. }
  90. /**
  91. * Tells which source files should be reprocessed based on the
  92. * last modification date of target files.
  93. * @param logTo where to send (more or less) interesting output.
  94. * @param source array of resources bearing relative path and last
  95. * modification date.
  96. * @param mapper filename mapper indicating how to find the target
  97. * files.
  98. * @param targets object able to map as a resource a relative path
  99. * at <b>destination</b>.
  100. * @param granularity The number of milliseconds leeway to give
  101. * before deciding a target is out of date.
  102. * @return array containing the source files which need to be
  103. * copied or processed, because the targets are out of date or do
  104. * not exist.
  105. * @since Ant 1.6.2
  106. */
  107. public static Resource[] selectOutOfDateSources(final ProjectComponent logTo,
  108. final Resource[] source,
  109. final FileNameMapper mapper,
  110. final ResourceFactory targets,
  111. final long granularity) {
  112. final Union u = new Union();
  113. u.addAll(Arrays.asList(source));
  114. final ResourceCollection rc
  115. = selectOutOfDateSources(logTo, u, mapper, targets, granularity);
  116. return rc.size() == 0 ? new Resource[0] : ((Union) rc).listResources();
  117. }
  118. /**
  119. * Tells which sources should be reprocessed based on the
  120. * last modification date of targets.
  121. * @param logTo where to send (more or less) interesting output.
  122. * @param source ResourceCollection.
  123. * @param mapper filename mapper indicating how to find the target Resources.
  124. * @param targets object able to map a relative path as a Resource.
  125. * @param granularity The number of milliseconds leeway to give
  126. * before deciding a target is out of date.
  127. * @return ResourceCollection.
  128. * @since Ant 1.7
  129. */
  130. public static ResourceCollection selectOutOfDateSources(final ProjectComponent logTo,
  131. final ResourceCollection source,
  132. final FileNameMapper mapper,
  133. final ResourceFactory targets,
  134. final long granularity) {
  135. logFuture(logTo, source, granularity);
  136. final ResourceSelectorProvider p =
  137. new ResourceSelectorProvider() {
  138. public ResourceSelector
  139. getTargetSelectorForSource(final Resource sr) {
  140. return new ResourceSelector() {
  141. public boolean isSelected(final Resource target) {
  142. /* Extra I/O, probably wasted:
  143. if (target.isDirectory()) {
  144. return false;
  145. }
  146. */
  147. return SelectorUtils.isOutOfDate(sr, target,
  148. granularity);
  149. }
  150. };
  151. }
  152. };
  153. return selectSources(logTo, source, mapper, targets, p);
  154. }
  155. /**
  156. * Tells which sources should be reprocessed because the given
  157. * selector selects at least one target.
  158. *
  159. * @param logTo where to send (more or less) interesting output.
  160. * @param source ResourceCollection.
  161. * @param mapper filename mapper indicating how to find the target Resources.
  162. * @param targets object able to map a relative path as a Resource.
  163. * @param selector returns a selector that is applied to target
  164. * files. If it selects at least one target the source will be
  165. * added to the returned collection.
  166. * @return ResourceCollection.
  167. * @since Ant 1.8.0
  168. */
  169. public static ResourceCollection selectSources(final ProjectComponent logTo,
  170. ResourceCollection source,
  171. final FileNameMapper mapper,
  172. final ResourceFactory targets,
  173. final ResourceSelectorProvider selector) {
  174. if (source.size() == 0) {
  175. logTo.log("No sources found.", Project.MSG_VERBOSE);
  176. return Resources.NONE;
  177. }
  178. source = Union.getInstance(source);
  179. final Union result = new Union();
  180. for (final Resource sr : source) {
  181. String srName = sr.getName();
  182. srName = srName == null
  183. ? srName : srName.replace('/', File.separatorChar);
  184. String[] targetnames = null;
  185. try {
  186. targetnames = mapper.mapFileName(srName);
  187. } catch (final Exception e) {
  188. logTo.log("Caught " + e + " mapping resource " + sr,
  189. Project.MSG_VERBOSE);
  190. }
  191. if (targetnames == null || targetnames.length == 0) {
  192. logTo.log(sr + " skipped - don\'t know how to handle it",
  193. Project.MSG_VERBOSE);
  194. continue;
  195. }
  196. for (int i = 0; i < targetnames.length; i++) {
  197. if (targetnames[i] == null) {
  198. targetnames[i] = "(no name)";
  199. }
  200. }
  201. final Union targetColl = new Union();
  202. for (int i = 0; i < targetnames.length; i++) {
  203. targetColl.add(targets.getResource(
  204. targetnames[i].replace(File.separatorChar, '/')));
  205. }
  206. //find the out-of-date targets:
  207. final Restrict r = new Restrict();
  208. r.add(selector.getTargetSelectorForSource(sr));
  209. r.add(targetColl);
  210. if (r.size() > 0) {
  211. result.add(sr);
  212. final Resource t = r.iterator().next();
  213. logTo.log(sr.getName() + " added as " + t.getName()
  214. + (t.isExists() ? " is outdated." : " doesn\'t exist."),
  215. Project.MSG_VERBOSE);
  216. continue;
  217. }
  218. //log uptodateness of all targets:
  219. logTo.log(sr.getName()
  220. + " omitted as " + targetColl.toString()
  221. + (targetColl.size() == 1 ? " is" : " are ")
  222. + " up to date.", Project.MSG_VERBOSE);
  223. }
  224. return result;
  225. }
  226. /**
  227. * Convenience method to copy content from one Resource to another.
  228. * No filtering is performed.
  229. *
  230. * @param source the Resource to copy from.
  231. * Must not be <code>null</code>.
  232. * @param dest the Resource to copy to.
  233. * Must not be <code>null</code>.
  234. *
  235. * @throws IOException if the copying fails.
  236. *
  237. * @since Ant 1.7
  238. */
  239. public static void copyResource(final Resource source, final Resource dest) throws IOException {
  240. copyResource(source, dest, null);
  241. }
  242. /**
  243. * Convenience method to copy content from one Resource to another.
  244. * No filtering is performed.
  245. *
  246. * @param source the Resource to copy from.
  247. * Must not be <code>null</code>.
  248. * @param dest the Resource to copy to.
  249. * Must not be <code>null</code>.
  250. * @param project the project instance.
  251. *
  252. * @throws IOException if the copying fails.
  253. *
  254. * @since Ant 1.7
  255. */
  256. public static void copyResource(final Resource source, final Resource dest, final Project project)
  257. throws IOException {
  258. copyResource(source, dest, null, null, false,
  259. false, null, null, project);
  260. }
  261. // CheckStyle:ParameterNumberCheck OFF - bc
  262. /**
  263. * Convenience method to copy content from one Resource to another
  264. * specifying whether token filtering must be used, whether filter chains
  265. * must be used, whether newer destination files may be overwritten and
  266. * whether the last modified time of <code>dest</code> file should be made
  267. * equal to the last modified time of <code>source</code>.
  268. *
  269. * @param source the Resource to copy from.
  270. * Must not be <code>null</code>.
  271. * @param dest the Resource to copy to.
  272. * Must not be <code>null</code>.
  273. * @param filters the collection of filters to apply to this copy.
  274. * @param filterChains filterChains to apply during the copy.
  275. * @param overwrite Whether or not the destination Resource should be
  276. * overwritten if it already exists.
  277. * @param preserveLastModified Whether or not the last modified time of
  278. * the destination Resource should be set to that
  279. * of the source.
  280. * @param inputEncoding the encoding used to read the files.
  281. * @param outputEncoding the encoding used to write the files.
  282. * @param project the project instance.
  283. *
  284. * @throws IOException if the copying fails.
  285. *
  286. * @since Ant 1.7
  287. */
  288. public static void copyResource(final Resource source, final Resource dest,
  289. final FilterSetCollection filters, final Vector filterChains,
  290. final boolean overwrite, final boolean preserveLastModified,
  291. final String inputEncoding, final String outputEncoding,
  292. final Project project)
  293. throws IOException {
  294. copyResource(source, dest, filters, filterChains, overwrite, preserveLastModified, false, inputEncoding, outputEncoding, project);
  295. }
  296. // CheckStyle:ParameterNumberCheck OFF - bc
  297. /**
  298. * Convenience method to copy content from one Resource to another
  299. * specifying whether token filtering must be used, whether filter chains
  300. * must be used, whether newer destination files may be overwritten and
  301. * whether the last modified time of <code>dest</code> file should be made
  302. * equal to the last modified time of <code>source</code>.
  303. *
  304. * @param source the Resource to copy from.
  305. * Must not be <code>null</code>.
  306. * @param dest the Resource to copy to.
  307. * Must not be <code>null</code>.
  308. * @param filters the collection of filters to apply to this copy.
  309. * @param filterChains filterChains to apply during the copy.
  310. * @param overwrite Whether or not the destination Resource should be
  311. * overwritten if it already exists.
  312. * @param preserveLastModified Whether or not the last modified time of
  313. * the destination Resource should be set to that
  314. * of the source.
  315. * @param append Whether to append to an Appendable Resource.
  316. * @param inputEncoding the encoding used to read the files.
  317. * @param outputEncoding the encoding used to write the files.
  318. * @param project the project instance.
  319. *
  320. * @throws IOException if the copying fails.
  321. *
  322. * @since Ant 1.8
  323. */
  324. public static void copyResource(final Resource source, final Resource dest,
  325. final FilterSetCollection filters, final Vector filterChains,
  326. final boolean overwrite, final boolean preserveLastModified,
  327. final boolean append,
  328. final String inputEncoding, final String outputEncoding,
  329. final Project project)
  330. throws IOException {
  331. copyResource(source, dest, filters, filterChains, overwrite,
  332. preserveLastModified, append, inputEncoding,
  333. outputEncoding, project, /* force: */ false);
  334. }
  335. /**
  336. * Convenience method to copy content from one Resource to another
  337. * specifying whether token filtering must be used, whether filter chains
  338. * must be used, whether newer destination files may be overwritten and
  339. * whether the last modified time of <code>dest</code> file should be made
  340. * equal to the last modified time of <code>source</code>.
  341. *
  342. * @param source the Resource to copy from.
  343. * Must not be <code>null</code>.
  344. * @param dest the Resource to copy to.
  345. * Must not be <code>null</code>.
  346. * @param filters the collection of filters to apply to this copy.
  347. * @param filterChains filterChains to apply during the copy.
  348. * @param overwrite Whether or not the destination Resource should be
  349. * overwritten if it already exists.
  350. * @param preserveLastModified Whether or not the last modified time of
  351. * the destination Resource should be set to that
  352. * of the source.
  353. * @param append Whether to append to an Appendable Resource.
  354. * @param inputEncoding the encoding used to read the files.
  355. * @param outputEncoding the encoding used to write the files.
  356. * @param project the project instance.
  357. * @param force whether read-only target files will be overwritten
  358. *
  359. * @throws IOException if the copying fails.
  360. *
  361. * @since Ant 1.8.2
  362. */
  363. public static void copyResource(final Resource source, final Resource dest,
  364. final FilterSetCollection filters, final Vector filterChains,
  365. final boolean overwrite, final boolean preserveLastModified,
  366. final boolean append,
  367. final String inputEncoding, final String outputEncoding,
  368. final Project project, final boolean force)
  369. throws IOException {
  370. if (!(overwrite || SelectorUtils.isOutOfDate(source, dest, FileUtils.getFileUtils()
  371. .getFileTimestampGranularity()))) {
  372. return;
  373. }
  374. final boolean filterSetsAvailable = (filters != null
  375. && filters.hasFilters());
  376. final boolean filterChainsAvailable = (filterChains != null
  377. && filterChains.size() > 0);
  378. String effectiveInputEncoding = null;
  379. if (source instanceof StringResource) {
  380. effectiveInputEncoding = ((StringResource) source).getEncoding();
  381. } else {
  382. effectiveInputEncoding = inputEncoding;
  383. }
  384. File destFile = null;
  385. if (dest.as(FileProvider.class) != null) {
  386. destFile = dest.as(FileProvider.class).getFile();
  387. }
  388. if (destFile != null && destFile.isFile() && !destFile.canWrite()) {
  389. if (!force) {
  390. throw new ReadOnlyTargetFileException(destFile);
  391. } else if (!FILE_UTILS.tryHardToDelete(destFile)) {
  392. throw new IOException("failed to delete read-only "
  393. + "destination file " + destFile);
  394. }
  395. }
  396. if (filterSetsAvailable) {
  397. copyWithFilterSets(source, dest, filters, filterChains,
  398. filterChainsAvailable, append,
  399. effectiveInputEncoding, outputEncoding,
  400. project);
  401. } else if (filterChainsAvailable
  402. || (effectiveInputEncoding != null
  403. && !effectiveInputEncoding.equals(outputEncoding))
  404. || (effectiveInputEncoding == null && outputEncoding != null)) {
  405. copyWithFilterChainsOrTranscoding(source, dest, filterChains,
  406. filterChainsAvailable, append,
  407. effectiveInputEncoding,
  408. outputEncoding, project);
  409. } else {
  410. boolean copied = false;
  411. if (source.as(FileProvider.class) != null
  412. && destFile != null && !append) {
  413. final File sourceFile =
  414. source.as(FileProvider.class).getFile();
  415. try {
  416. copyUsingFileChannels(sourceFile, destFile);
  417. copied = true;
  418. } catch (final IOException ex) {
  419. String msg = "Attempt to copy " + sourceFile
  420. + " to " + destFile + " using NIO Channels"
  421. + " failed due to '" + ex.getMessage()
  422. + "'. Falling back to streams.";
  423. if (project != null) {
  424. project.log(msg, Project.MSG_WARN);
  425. } else {
  426. System.err.println(msg);
  427. }
  428. }
  429. }
  430. if (!copied) {
  431. copyUsingStreams(source, dest, append, project);
  432. }
  433. }
  434. if (preserveLastModified) {
  435. final Touchable t = dest.as(Touchable.class);
  436. if (t != null) {
  437. setLastModified(t, source.getLastModified());
  438. }
  439. }
  440. }
  441. // CheckStyle:ParameterNumberCheck ON
  442. /**
  443. * Set the last modified time of an object implementing
  444. * org.apache.tools.ant.types.resources.Touchable .
  445. *
  446. * @param t the Touchable whose modified time is to be set.
  447. * @param time the time to which the last modified time is to be set.
  448. * if this is -1, the current time is used.
  449. * @since Ant 1.7
  450. */
  451. public static void setLastModified(final Touchable t, final long time) {
  452. t.touch((time < 0) ? System.currentTimeMillis() : time);
  453. }
  454. /**
  455. * Compares the contents of two Resources.
  456. *
  457. * @param r1 the Resource whose content is to be compared.
  458. * @param r2 the other Resource whose content is to be compared.
  459. * @param text true if the content is to be treated as text and
  460. * differences in kind of line break are to be ignored.
  461. *
  462. * @return true if the content of the Resources is the same.
  463. *
  464. * @throws IOException if the Resources cannot be read.
  465. * @since Ant 1.7
  466. */
  467. public static boolean contentEquals(final Resource r1, final Resource r2, final boolean text) throws IOException {
  468. if (r1.isExists() != r2.isExists()) {
  469. return false;
  470. }
  471. if (!r1.isExists()) {
  472. // two not existing files are equal
  473. return true;
  474. }
  475. // should the following two be switched? If r1 and r2 refer to the same file,
  476. // isn't their content equal regardless of whether that file is a directory?
  477. if (r1.isDirectory() || r2.isDirectory()) {
  478. // don't want to compare directory contents for now
  479. return false;
  480. }
  481. if (r1.equals(r2)) {
  482. return true;
  483. }
  484. if (!text) {
  485. final long s1 = r1.getSize();
  486. final long s2 = r2.getSize();
  487. if (s1 != Resource.UNKNOWN_SIZE && s2 != Resource.UNKNOWN_SIZE
  488. && s1 != s2) {
  489. return false;
  490. }
  491. }
  492. return compareContent(r1, r2, text) == 0;
  493. }
  494. /**
  495. * Compare the content of two Resources. A nonexistent Resource's
  496. * content is "less than" that of an existing Resource; a directory-type
  497. * Resource's content is "less than" that of a file-type Resource.
  498. * @param r1 the Resource whose content is to be compared.
  499. * @param r2 the other Resource whose content is to be compared.
  500. * @param text true if the content is to be treated as text and
  501. * differences in kind of line break are to be ignored.
  502. * @return a negative integer, zero, or a positive integer as the first
  503. * argument is less than, equal to, or greater than the second.
  504. * @throws IOException if the Resources cannot be read.
  505. * @since Ant 1.7
  506. */
  507. public static int compareContent(final Resource r1, final Resource r2, final boolean text) throws IOException {
  508. if (r1.equals(r2)) {
  509. return 0;
  510. }
  511. final boolean e1 = r1.isExists();
  512. final boolean e2 = r2.isExists();
  513. if (!(e1 || e2)) {
  514. return 0;
  515. }
  516. if (e1 != e2) {
  517. return e1 ? 1 : -1;
  518. }
  519. final boolean d1 = r1.isDirectory();
  520. final boolean d2 = r2.isDirectory();
  521. if (d1 && d2) {
  522. return 0;
  523. }
  524. if (d1 || d2) {
  525. return d1 ? -1 : 1;
  526. }
  527. return text ? textCompare(r1, r2) : binaryCompare(r1, r2);
  528. }
  529. /**
  530. * Convenience method to turn any fileProvider into a basic
  531. * FileResource with the file's immediate parent as the basedir,
  532. * for tasks that need one.
  533. * @param fileProvider input
  534. * @return fileProvider if it is a FileResource instance, or a new
  535. * FileResource with fileProvider's file.
  536. * @since Ant 1.8
  537. */
  538. public static FileResource asFileResource(final FileProvider fileProvider) {
  539. if (fileProvider instanceof FileResource || fileProvider == null) {
  540. return (FileResource) fileProvider;
  541. }
  542. final FileResource result = new FileResource(fileProvider.getFile());
  543. result.setProject(Project.getProject(fileProvider));
  544. return result;
  545. }
  546. /**
  547. * Binary compares the contents of two Resources.
  548. * <p>
  549. * simple but sub-optimal comparison algorithm. written for working
  550. * rather than fast. Better would be a block read into buffers followed
  551. * by long comparisons apart from the final 1-7 bytes.
  552. * </p>
  553. *
  554. * @param r1 the Resource whose content is to be compared.
  555. * @param r2 the other Resource whose content is to be compared.
  556. * @return a negative integer, zero, or a positive integer as the first
  557. * argument is less than, equal to, or greater than the second.
  558. * @throws IOException if the Resources cannot be read.
  559. * @since Ant 1.7
  560. */
  561. private static int binaryCompare(final Resource r1, final Resource r2) throws IOException {
  562. InputStream in1 = null;
  563. InputStream in2 = null;
  564. try {
  565. in1 = new BufferedInputStream(r1.getInputStream());
  566. in2 = new BufferedInputStream(r2.getInputStream());
  567. for (int b1 = in1.read(); b1 != -1; b1 = in1.read()) {
  568. final int b2 = in2.read();
  569. if (b1 != b2) {
  570. return b1 > b2 ? 1 : -1;
  571. }
  572. }
  573. return in2.read() == -1 ? 0 : -1;
  574. } finally {
  575. FileUtils.close(in1);
  576. FileUtils.close(in2);
  577. }
  578. }
  579. /**
  580. * Text compares the contents of two Resources.
  581. * Ignores different kinds of line endings.
  582. * @param r1 the Resource whose content is to be compared.
  583. * @param r2 the other Resource whose content is to be compared.
  584. * @return a negative integer, zero, or a positive integer as the first
  585. * argument is less than, equal to, or greater than the second.
  586. * @throws IOException if the Resources cannot be read.
  587. * @since Ant 1.7
  588. */
  589. private static int textCompare(final Resource r1, final Resource r2) throws IOException {
  590. BufferedReader in1 = null;
  591. BufferedReader in2 = null;
  592. try {
  593. in1 = new BufferedReader(new InputStreamReader(r1.getInputStream()));
  594. in2 = new BufferedReader(new InputStreamReader(r2.getInputStream()));
  595. String expected = in1.readLine();
  596. while (expected != null) {
  597. final String actual = in2.readLine();
  598. if (!expected.equals(actual)) {
  599. if (actual == null) {
  600. return 1;
  601. }
  602. return expected.compareTo(actual);
  603. }
  604. expected = in1.readLine();
  605. }
  606. return in2.readLine() == null ? 0 : -1; //NOSONAR
  607. } finally {
  608. FileUtils.close(in1);
  609. FileUtils.close(in2);
  610. }
  611. }
  612. /**
  613. * Log which Resources (if any) have been modified in the future.
  614. * @param logTo the ProjectComponent to do the logging.
  615. * @param rc the collection of Resources to check.
  616. * @param granularity the timestamp granularity to use.
  617. * @since Ant 1.7
  618. */
  619. private static void logFuture(final ProjectComponent logTo,
  620. final ResourceCollection rc, final long granularity) {
  621. final long now = System.currentTimeMillis() + granularity;
  622. final Date sel = new Date();
  623. sel.setMillis(now);
  624. sel.setWhen(TimeComparison.AFTER);
  625. final Restrict future = new Restrict();
  626. future.add(sel);
  627. future.add(rc);
  628. for (final Resource r : future) {
  629. logTo.log("Warning: " + r.getName() + " modified in the future.", Project.MSG_WARN);
  630. }
  631. }
  632. private static void copyWithFilterSets(final Resource source, final Resource dest,
  633. final FilterSetCollection filters,
  634. final Vector filterChains,
  635. final boolean filterChainsAvailable,
  636. final boolean append, final String inputEncoding,
  637. final String outputEncoding,
  638. final Project project)
  639. throws IOException {
  640. BufferedReader in = null;
  641. BufferedWriter out = null;
  642. try {
  643. InputStreamReader isr = null;
  644. if (inputEncoding == null) {
  645. isr = new InputStreamReader(source.getInputStream());
  646. } else {
  647. isr = new InputStreamReader(source.getInputStream(),
  648. inputEncoding);
  649. }
  650. in = new BufferedReader(isr);
  651. final OutputStream os = getOutputStream(dest, append, project);
  652. OutputStreamWriter osw;
  653. if (outputEncoding == null) {
  654. osw = new OutputStreamWriter(os);
  655. } else {
  656. osw = new OutputStreamWriter(os, outputEncoding);
  657. }
  658. out = new BufferedWriter(osw);
  659. if (filterChainsAvailable) {
  660. final ChainReaderHelper crh = new ChainReaderHelper();
  661. crh.setBufferSize(FileUtils.BUF_SIZE);
  662. crh.setPrimaryReader(in);
  663. crh.setFilterChains(filterChains);
  664. crh.setProject(project);
  665. final Reader rdr = crh.getAssembledReader();
  666. in = new BufferedReader(rdr);
  667. }
  668. final LineTokenizer lineTokenizer = new LineTokenizer();
  669. lineTokenizer.setIncludeDelims(true);
  670. String newline = null;
  671. String line = lineTokenizer.getToken(in);
  672. while (line != null) {
  673. if (line.length() == 0) {
  674. // this should not happen, because the lines are
  675. // returned with the end of line delimiter
  676. out.newLine();
  677. } else {
  678. newline = filters.replaceTokens(line);
  679. out.write(newline);
  680. }
  681. line = lineTokenizer.getToken(in);
  682. }
  683. } finally {
  684. FileUtils.close(out);
  685. FileUtils.close(in);
  686. }
  687. }
  688. private static void copyWithFilterChainsOrTranscoding(final Resource source,
  689. final Resource dest,
  690. final Vector filterChains,
  691. final boolean filterChainsAvailable,
  692. final boolean append,
  693. final String inputEncoding,
  694. final String outputEncoding,
  695. final Project project)
  696. throws IOException {
  697. BufferedReader in = null;
  698. BufferedWriter out = null;
  699. try {
  700. InputStreamReader isr = null;
  701. if (inputEncoding == null) {
  702. isr = new InputStreamReader(source.getInputStream());
  703. } else {
  704. isr = new InputStreamReader(source.getInputStream(),
  705. inputEncoding);
  706. }
  707. in = new BufferedReader(isr);
  708. final OutputStream os = getOutputStream(dest, append, project);
  709. OutputStreamWriter osw;
  710. if (outputEncoding == null) {
  711. osw = new OutputStreamWriter(os);
  712. } else {
  713. osw = new OutputStreamWriter(os, outputEncoding);
  714. }
  715. out = new BufferedWriter(osw);
  716. if (filterChainsAvailable) {
  717. final ChainReaderHelper crh = new ChainReaderHelper();
  718. crh.setBufferSize(FileUtils.BUF_SIZE);
  719. crh.setPrimaryReader(in);
  720. crh.setFilterChains(filterChains);
  721. crh.setProject(project);
  722. final Reader rdr = crh.getAssembledReader();
  723. in = new BufferedReader(rdr);
  724. }
  725. final char[] buffer = new char[FileUtils.BUF_SIZE];
  726. while (true) {
  727. final int nRead = in.read(buffer, 0, buffer.length);
  728. if (nRead == -1) {
  729. break;
  730. }
  731. out.write(buffer, 0, nRead);
  732. }
  733. } finally {
  734. FileUtils.close(out);
  735. FileUtils.close(in);
  736. }
  737. }
  738. private static void copyUsingFileChannels(final File sourceFile,
  739. final File destFile)
  740. throws IOException {
  741. final File parent = destFile.getParentFile();
  742. if (parent != null && !parent.isDirectory()
  743. && !(parent.mkdirs() || parent.isDirectory())) {
  744. throw new IOException("failed to create the parent directory"
  745. + " for " + destFile);
  746. }
  747. FileInputStream in = null;
  748. FileOutputStream out = null;
  749. FileChannel srcChannel = null;
  750. FileChannel destChannel = null;
  751. try {
  752. in = new FileInputStream(sourceFile);
  753. out = new FileOutputStream(destFile);
  754. srcChannel = in.getChannel();
  755. destChannel = out.getChannel();
  756. long position = 0;
  757. final long count = srcChannel.size();
  758. while (position < count) {
  759. final long chunk = Math.min(MAX_IO_CHUNK_SIZE, count - position);
  760. position +=
  761. destChannel.transferFrom(srcChannel, position, chunk);
  762. }
  763. } finally {
  764. FileUtils.close(srcChannel);
  765. FileUtils.close(destChannel);
  766. FileUtils.close(out);
  767. FileUtils.close(in);
  768. }
  769. }
  770. private static void copyUsingStreams(final Resource source, final Resource dest,
  771. final boolean append, final Project project)
  772. throws IOException {
  773. InputStream in = null;
  774. OutputStream out = null;
  775. try {
  776. in = source.getInputStream();
  777. out = getOutputStream(dest, append, project);
  778. final byte[] buffer = new byte[FileUtils.BUF_SIZE];
  779. int count = 0;
  780. do {
  781. out.write(buffer, 0, count);
  782. count = in.read(buffer, 0, buffer.length);
  783. } while (count != -1);
  784. } finally {
  785. FileUtils.close(out);
  786. FileUtils.close(in);
  787. }
  788. }
  789. private static OutputStream getOutputStream(final Resource resource, final boolean append, final Project project)
  790. throws IOException {
  791. if (append) {
  792. final Appendable a = resource.as(Appendable.class);
  793. if (a != null) {
  794. return a.getAppendOutputStream();
  795. }
  796. String msg = "Appendable OutputStream not available for non-appendable resource "
  797. + resource + "; using plain OutputStream";
  798. if (project != null) {
  799. project.log(msg, Project.MSG_VERBOSE);
  800. } else {
  801. System.out.println(msg);
  802. }
  803. }
  804. return resource.getOutputStream();
  805. }
  806. public interface ResourceSelectorProvider {
  807. ResourceSelector getTargetSelectorForSource(Resource source);
  808. }
  809. /**
  810. * @since Ant 1.9.4
  811. */
  812. public static class ReadOnlyTargetFileException extends IOException {
  813. private static final long serialVersionUID = 1L;
  814. public ReadOnlyTargetFileException(final File destFile) {
  815. super("can't write to read-only destination file " + destFile);
  816. }
  817. }
  818. }