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

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