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 34 kB

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