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.

Copy.java 40 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  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.taskdefs;
  19. import java.io.File;
  20. import java.io.IOException;
  21. import java.util.ArrayList;
  22. import java.util.Enumeration;
  23. import java.util.HashMap;
  24. import java.util.HashSet;
  25. import java.util.Hashtable;
  26. import java.util.Iterator;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.Vector;
  30. import org.apache.tools.ant.Task;
  31. import org.apache.tools.ant.Project;
  32. import org.apache.tools.ant.BuildException;
  33. import org.apache.tools.ant.DirectoryScanner;
  34. import org.apache.tools.ant.types.Mapper;
  35. import org.apache.tools.ant.types.FileSet;
  36. import org.apache.tools.ant.types.FilterSet;
  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.resources.FileProvider;
  43. import org.apache.tools.ant.types.resources.FileResource;
  44. import org.apache.tools.ant.util.FileUtils;
  45. import org.apache.tools.ant.util.FileNameMapper;
  46. import org.apache.tools.ant.util.IdentityMapper;
  47. import org.apache.tools.ant.util.ResourceUtils;
  48. import org.apache.tools.ant.util.SourceFileScanner;
  49. import org.apache.tools.ant.util.FlatFileNameMapper;
  50. /**
  51. * Copies a file or directory to a new file
  52. * or directory. Files are only copied if the source file is newer
  53. * than the destination file, or when the destination file does not
  54. * exist. It is possible to explicitly overwrite existing files.</p>
  55. *
  56. * <p>This implementation is based on Arnout Kuiper's initial design
  57. * document, the following mailing list discussions, and the
  58. * copyfile/copydir tasks.</p>
  59. *
  60. *
  61. * @since Ant 1.2
  62. *
  63. * @ant.task category="filesystem"
  64. */
  65. public class Copy extends Task {
  66. private static final String MSG_WHEN_COPYING_EMPTY_RC_TO_FILE =
  67. "Cannot perform operation from directory to file.";
  68. static final File NULL_FILE_PLACEHOLDER = new File("/NULL_FILE");
  69. static final String LINE_SEPARATOR = System.getProperty("line.separator");
  70. // CheckStyle:VisibilityModifier OFF - bc
  71. protected File file = null; // the source file
  72. protected File destFile = null; // the destination file
  73. protected File destDir = null; // the destination directory
  74. protected Vector rcs = new Vector();
  75. // here to provide API backwards compatibility
  76. protected Vector filesets = rcs;
  77. private boolean enableMultipleMappings = false;
  78. protected boolean filtering = false;
  79. protected boolean preserveLastModified = false;
  80. protected boolean forceOverwrite = false;
  81. protected boolean flatten = false;
  82. protected int verbosity = Project.MSG_VERBOSE;
  83. protected boolean includeEmpty = true;
  84. protected boolean failonerror = true;
  85. protected Hashtable fileCopyMap = new Hashtable();
  86. protected Hashtable dirCopyMap = new Hashtable();
  87. protected Hashtable completeDirMap = new Hashtable();
  88. protected Mapper mapperElement = null;
  89. protected FileUtils fileUtils;
  90. //CheckStyle:VisibilityModifier ON
  91. private Vector filterChains = new Vector();
  92. private Vector filterSets = new Vector();
  93. private String inputEncoding = null;
  94. private String outputEncoding = null;
  95. private long granularity = 0;
  96. /**
  97. * Copy task constructor.
  98. */
  99. public Copy() {
  100. fileUtils = FileUtils.getFileUtils();
  101. granularity = fileUtils.getFileTimestampGranularity();
  102. }
  103. /**
  104. * Get the FileUtils for this task.
  105. * @return the fileutils object.
  106. */
  107. protected FileUtils getFileUtils() {
  108. return fileUtils;
  109. }
  110. /**
  111. * Set a single source file to copy.
  112. * @param file the file to copy.
  113. */
  114. public void setFile(File file) {
  115. this.file = file;
  116. }
  117. /**
  118. * Set the destination file.
  119. * @param destFile the file to copy to.
  120. */
  121. public void setTofile(File destFile) {
  122. this.destFile = destFile;
  123. }
  124. /**
  125. * Set the destination directory.
  126. * @param destDir the destination directory.
  127. */
  128. public void setTodir(File destDir) {
  129. this.destDir = destDir;
  130. }
  131. /**
  132. * Add a FilterChain.
  133. * @return a filter chain object.
  134. */
  135. public FilterChain createFilterChain() {
  136. FilterChain filterChain = new FilterChain();
  137. filterChains.addElement(filterChain);
  138. return filterChain;
  139. }
  140. /**
  141. * Add a filterset.
  142. * @return a filter set object.
  143. */
  144. public FilterSet createFilterSet() {
  145. FilterSet filterSet = new FilterSet();
  146. filterSets.addElement(filterSet);
  147. return filterSet;
  148. }
  149. /**
  150. * Give the copied files the same last modified time as the original files.
  151. * @param preserve a boolean string.
  152. * @deprecated since 1.5.x.
  153. * setPreserveLastModified(String) has been deprecated and
  154. * replaced with setPreserveLastModified(boolean) to
  155. * consistently let the Introspection mechanism work.
  156. */
  157. public void setPreserveLastModified(String preserve) {
  158. setPreserveLastModified(Project.toBoolean(preserve));
  159. }
  160. /**
  161. * Give the copied files the same last modified time as the original files.
  162. * @param preserve if true preserve the modified time; default is false.
  163. */
  164. public void setPreserveLastModified(boolean preserve) {
  165. preserveLastModified = preserve;
  166. }
  167. /**
  168. * Get whether to give the copied files the same last modified time as
  169. * the original files.
  170. * @return the whether destination files will inherit the modification
  171. * times of the corresponding source files.
  172. * @since 1.32, Ant 1.5
  173. */
  174. public boolean getPreserveLastModified() {
  175. return preserveLastModified;
  176. }
  177. /**
  178. * Get the filtersets being applied to this operation.
  179. *
  180. * @return a vector of FilterSet objects.
  181. */
  182. protected Vector getFilterSets() {
  183. return filterSets;
  184. }
  185. /**
  186. * Get the filterchains being applied to this operation.
  187. *
  188. * @return a vector of FilterChain objects.
  189. */
  190. protected Vector getFilterChains() {
  191. return filterChains;
  192. }
  193. /**
  194. * Set filtering mode.
  195. * @param filtering if true enable filtering; default is false.
  196. */
  197. public void setFiltering(boolean filtering) {
  198. this.filtering = filtering;
  199. }
  200. /**
  201. * Set overwrite mode regarding existing destination file(s).
  202. * @param overwrite if true force overwriting of destination file(s)
  203. * even if the destination file(s) are younger than
  204. * the corresponding source file. Default is false.
  205. */
  206. public void setOverwrite(boolean overwrite) {
  207. this.forceOverwrite = overwrite;
  208. }
  209. /**
  210. * Set whether files copied from directory trees will be "flattened"
  211. * into a single directory. If there are multiple files with
  212. * the same name in the source directory tree, only the first
  213. * file will be copied into the "flattened" directory, unless
  214. * the forceoverwrite attribute is true.
  215. * @param flatten if true flatten the destination directory. Default
  216. * is false.
  217. */
  218. public void setFlatten(boolean flatten) {
  219. this.flatten = flatten;
  220. }
  221. /**
  222. * Set verbose mode. Used to force listing of all names of copied files.
  223. * @param verbose whether to output the names of copied files.
  224. * Default is false.
  225. */
  226. public void setVerbose(boolean verbose) {
  227. this.verbosity = verbose ? Project.MSG_INFO : Project.MSG_VERBOSE;
  228. }
  229. /**
  230. * Set whether to copy empty directories.
  231. * @param includeEmpty if true copy empty directories. Default is true.
  232. */
  233. public void setIncludeEmptyDirs(boolean includeEmpty) {
  234. this.includeEmpty = includeEmpty;
  235. }
  236. /**
  237. * Set method of handling mappers that return multiple
  238. * mappings for a given source path.
  239. * @param enableMultipleMappings If true the task will
  240. * copy to all the mappings for a given source path, if
  241. * false, only the first file or directory is
  242. * processed.
  243. * By default, this setting is false to provide backward
  244. * compatibility with earlier releases.
  245. * @since Ant 1.6
  246. */
  247. public void setEnableMultipleMappings(boolean enableMultipleMappings) {
  248. this.enableMultipleMappings = enableMultipleMappings;
  249. }
  250. /**
  251. * Get whether multiple mapping is enabled.
  252. * @return true if multiple mapping is enabled; false otherwise.
  253. */
  254. public boolean isEnableMultipleMapping() {
  255. return enableMultipleMappings;
  256. }
  257. /**
  258. * Set whether to fail when errors are encountered. If false, note errors
  259. * to the output but keep going. Default is true.
  260. * @param failonerror true or false.
  261. */
  262. public void setFailOnError(boolean failonerror) {
  263. this.failonerror = failonerror;
  264. }
  265. /**
  266. * Add a set of files to copy.
  267. * @param set a set of files to copy.
  268. */
  269. public void addFileset(FileSet set) {
  270. add(set);
  271. }
  272. /**
  273. * Add a collection of files to copy.
  274. * @param res a resource collection to copy.
  275. * @since Ant 1.7
  276. */
  277. public void add(ResourceCollection res) {
  278. rcs.add(res);
  279. }
  280. /**
  281. * Define the mapper to map source to destination files.
  282. * @return a mapper to be configured.
  283. * @exception BuildException if more than one mapper is defined.
  284. */
  285. public Mapper createMapper() throws BuildException {
  286. if (mapperElement != null) {
  287. throw new BuildException("Cannot define more than one mapper",
  288. getLocation());
  289. }
  290. mapperElement = new Mapper(getProject());
  291. return mapperElement;
  292. }
  293. /**
  294. * Add a nested filenamemapper.
  295. * @param fileNameMapper the mapper to add.
  296. * @since Ant 1.6.3
  297. */
  298. public void add(FileNameMapper fileNameMapper) {
  299. createMapper().add(fileNameMapper);
  300. }
  301. /**
  302. * Set the character encoding.
  303. * @param encoding the character encoding.
  304. * @since 1.32, Ant 1.5
  305. */
  306. public void setEncoding(String encoding) {
  307. this.inputEncoding = encoding;
  308. if (outputEncoding == null) {
  309. outputEncoding = encoding;
  310. }
  311. }
  312. /**
  313. * Get the character encoding to be used.
  314. * @return the character encoding, <code>null</code> if not set.
  315. *
  316. * @since 1.32, Ant 1.5
  317. */
  318. public String getEncoding() {
  319. return inputEncoding;
  320. }
  321. /**
  322. * Set the character encoding for output files.
  323. * @param encoding the output character encoding.
  324. * @since Ant 1.6
  325. */
  326. public void setOutputEncoding(String encoding) {
  327. this.outputEncoding = encoding;
  328. }
  329. /**
  330. * Get the character encoding for output files.
  331. * @return the character encoding for output files,
  332. * <code>null</code> if not set.
  333. *
  334. * @since Ant 1.6
  335. */
  336. public String getOutputEncoding() {
  337. return outputEncoding;
  338. }
  339. /**
  340. * Set the number of milliseconds leeway to give before deciding a
  341. * target is out of date.
  342. *
  343. * <p>Default is 1 second, or 2 seconds on DOS systems.</p>
  344. * @param granularity the granularity used to decide if a target is out of
  345. * date.
  346. * @since Ant 1.6.2
  347. */
  348. public void setGranularity(long granularity) {
  349. this.granularity = granularity;
  350. }
  351. /**
  352. * Perform the copy operation.
  353. * @exception BuildException if an error occurs.
  354. */
  355. public void execute() throws BuildException {
  356. File savedFile = file; // may be altered in validateAttributes
  357. File savedDestFile = destFile;
  358. File savedDestDir = destDir;
  359. ResourceCollection savedRc = null;
  360. if (file == null && destFile != null && rcs.size() == 1) {
  361. // will be removed in validateAttributes
  362. savedRc = (ResourceCollection) rcs.elementAt(0);
  363. }
  364. try {
  365. // make sure we don't have an illegal set of options
  366. try {
  367. validateAttributes();
  368. } catch (BuildException e) {
  369. if (failonerror
  370. || !getMessage(e)
  371. .equals(MSG_WHEN_COPYING_EMPTY_RC_TO_FILE)) {
  372. throw e;
  373. } else {
  374. log("Warning: " + getMessage(e), Project.MSG_ERR);
  375. return;
  376. }
  377. }
  378. // deal with the single file
  379. copySingleFile();
  380. // deal with the ResourceCollections
  381. /* for historical and performance reasons we have to do
  382. things in a rather complex way.
  383. (1) Move is optimized to move directories if a fileset
  384. has been included completely, therefore FileSets need a
  385. special treatment. This is also required to support
  386. the failOnError semantice (skip filesets with broken
  387. basedir but handle the remaining collections).
  388. (2) We carry around a few protected methods that work
  389. on basedirs and arrays of names. To optimize stuff, all
  390. resources with the same basedir get collected in
  391. separate lists and then each list is handled in one go.
  392. */
  393. HashMap filesByBasedir = new HashMap();
  394. HashMap dirsByBasedir = new HashMap();
  395. HashSet baseDirs = new HashSet();
  396. ArrayList nonFileResources = new ArrayList();
  397. for (int i = 0; i < rcs.size(); i++) {
  398. ResourceCollection rc = (ResourceCollection) rcs.elementAt(i);
  399. // Step (1) - beware of the ZipFileSet
  400. if (rc instanceof FileSet && rc.isFilesystemOnly()) {
  401. FileSet fs = (FileSet) rc;
  402. DirectoryScanner ds = null;
  403. try {
  404. ds = fs.getDirectoryScanner(getProject());
  405. } catch (BuildException e) {
  406. if (failonerror
  407. || !getMessage(e).endsWith(DirectoryScanner
  408. .DOES_NOT_EXIST_POSTFIX)) {
  409. throw e;
  410. } else {
  411. log("Warning: " + getMessage(e), Project.MSG_ERR);
  412. continue;
  413. }
  414. }
  415. File fromDir = fs.getDir(getProject());
  416. String[] srcFiles = ds.getIncludedFiles();
  417. String[] srcDirs = ds.getIncludedDirectories();
  418. if (!flatten && mapperElement == null
  419. && ds.isEverythingIncluded() && !fs.hasPatterns()) {
  420. completeDirMap.put(fromDir, destDir);
  421. }
  422. add(fromDir, srcFiles, filesByBasedir);
  423. add(fromDir, srcDirs, dirsByBasedir);
  424. baseDirs.add(fromDir);
  425. } else { // not a fileset or contains non-file resources
  426. if (!rc.isFilesystemOnly() && !supportsNonFileResources()) {
  427. throw new BuildException(
  428. "Only FileSystem resources are supported.");
  429. }
  430. Iterator resources = rc.iterator();
  431. while (resources.hasNext()) {
  432. Resource r = (Resource) resources.next();
  433. if (!r.isExists()) {
  434. String message = "Warning: Could not find resource "
  435. + r.toLongString() + " to copy.";
  436. if (!failonerror) {
  437. log(message, Project.MSG_ERR);
  438. } else {
  439. throw new BuildException(message);
  440. }
  441. continue;
  442. }
  443. File baseDir = NULL_FILE_PLACEHOLDER;
  444. String name = r.getName();
  445. FileProvider fp = (FileProvider) r.as(FileProvider.class);
  446. if (fp != null) {
  447. FileResource fr = ResourceUtils.asFileResource(fp);
  448. baseDir = getKeyFile(fr.getBaseDir());
  449. if (fr.getBaseDir() == null) {
  450. name = fr.getFile().getAbsolutePath();
  451. }
  452. }
  453. // copying of dirs is trivial and can be done
  454. // for non-file resources as well as for real
  455. // files.
  456. if (r.isDirectory() || fp != null) {
  457. add(baseDir, name,
  458. r.isDirectory() ? dirsByBasedir
  459. : filesByBasedir);
  460. baseDirs.add(baseDir);
  461. } else { // a not-directory file resource
  462. // needs special treatment
  463. nonFileResources.add(r);
  464. }
  465. }
  466. }
  467. }
  468. iterateOverBaseDirs(baseDirs, dirsByBasedir, filesByBasedir);
  469. // do all the copy operations now...
  470. try {
  471. doFileOperations();
  472. } catch (BuildException e) {
  473. if (!failonerror) {
  474. log("Warning: " + getMessage(e), Project.MSG_ERR);
  475. } else {
  476. throw e;
  477. }
  478. }
  479. if (nonFileResources.size() > 0) {
  480. Resource[] nonFiles =
  481. (Resource[]) nonFileResources.toArray(new Resource[nonFileResources.size()]);
  482. // restrict to out-of-date resources
  483. Map map = scan(nonFiles, destDir);
  484. try {
  485. doResourceOperations(map);
  486. } catch (BuildException e) {
  487. if (!failonerror) {
  488. log("Warning: " + getMessage(e), Project.MSG_ERR);
  489. } else {
  490. throw e;
  491. }
  492. }
  493. }
  494. } finally {
  495. // clean up again, so this instance can be used a second
  496. // time
  497. file = savedFile;
  498. destFile = savedDestFile;
  499. destDir = savedDestDir;
  500. if (savedRc != null) {
  501. rcs.insertElementAt(savedRc, 0);
  502. }
  503. fileCopyMap.clear();
  504. dirCopyMap.clear();
  505. completeDirMap.clear();
  506. }
  507. }
  508. /************************************************************************
  509. ** protected and private methods
  510. ************************************************************************/
  511. private void copySingleFile() {
  512. // deal with the single file
  513. if (file != null) {
  514. if (file.exists()) {
  515. if (destFile == null) {
  516. destFile = new File(destDir, file.getName());
  517. }
  518. if (forceOverwrite || !destFile.exists()
  519. || (file.lastModified() - granularity
  520. > destFile.lastModified())) {
  521. fileCopyMap.put(file.getAbsolutePath(),
  522. new String[] {destFile.getAbsolutePath()});
  523. } else {
  524. log(file + " omitted as " + destFile
  525. + " is up to date.", Project.MSG_VERBOSE);
  526. }
  527. } else {
  528. String message = "Warning: Could not find file "
  529. + file.getAbsolutePath() + " to copy.";
  530. if (!failonerror) {
  531. log(message, Project.MSG_ERR);
  532. } else {
  533. throw new BuildException(message);
  534. }
  535. }
  536. }
  537. }
  538. private void iterateOverBaseDirs(
  539. HashSet baseDirs, HashMap dirsByBasedir, HashMap filesByBasedir) {
  540. Iterator iter = baseDirs.iterator();
  541. while (iter.hasNext()) {
  542. File f = (File) iter.next();
  543. List files = (List) filesByBasedir.get(f);
  544. List dirs = (List) dirsByBasedir.get(f);
  545. String[] srcFiles = new String[0];
  546. if (files != null) {
  547. srcFiles = (String[]) files.toArray(srcFiles);
  548. }
  549. String[] srcDirs = new String[0];
  550. if (dirs != null) {
  551. srcDirs = (String[]) dirs.toArray(srcDirs);
  552. }
  553. scan(f == NULL_FILE_PLACEHOLDER ? null : f, destDir, srcFiles,
  554. srcDirs);
  555. }
  556. }
  557. /**
  558. * Ensure we have a consistent and legal set of attributes, and set
  559. * any internal flags necessary based on different combinations
  560. * of attributes.
  561. * @exception BuildException if an error occurs.
  562. */
  563. protected void validateAttributes() throws BuildException {
  564. if (file == null && rcs.size() == 0) {
  565. throw new BuildException(
  566. "Specify at least one source--a file or a resource collection.");
  567. }
  568. if (destFile != null && destDir != null) {
  569. throw new BuildException(
  570. "Only one of tofile and todir may be set.");
  571. }
  572. if (destFile == null && destDir == null) {
  573. throw new BuildException("One of tofile or todir must be set.");
  574. }
  575. if (file != null && file.isDirectory()) {
  576. throw new BuildException("Use a resource collection to copy directories.");
  577. }
  578. if (destFile != null && rcs.size() > 0) {
  579. if (rcs.size() > 1) {
  580. throw new BuildException(
  581. "Cannot concatenate multiple files into a single file.");
  582. } else {
  583. ResourceCollection rc = (ResourceCollection) rcs.elementAt(0);
  584. if (!rc.isFilesystemOnly()) {
  585. throw new BuildException("Only FileSystem resources are"
  586. + " supported when concatenating"
  587. + " files.");
  588. }
  589. if (rc.size() == 0) {
  590. throw new BuildException(MSG_WHEN_COPYING_EMPTY_RC_TO_FILE);
  591. } else if (rc.size() == 1) {
  592. Resource res = (Resource) rc.iterator().next();
  593. FileProvider r = (FileProvider) res.as(FileProvider.class);
  594. if (file == null) {
  595. file = r.getFile();
  596. rcs.removeElementAt(0);
  597. } else {
  598. throw new BuildException(
  599. "Cannot concatenate multiple files into a single file.");
  600. }
  601. } else {
  602. throw new BuildException(
  603. "Cannot concatenate multiple files into a single file.");
  604. }
  605. }
  606. }
  607. if (destFile != null) {
  608. destDir = destFile.getParentFile();
  609. }
  610. }
  611. /**
  612. * Compares source files to destination files to see if they should be
  613. * copied.
  614. *
  615. * @param fromDir The source directory.
  616. * @param toDir The destination directory.
  617. * @param files A list of files to copy.
  618. * @param dirs A list of directories to copy.
  619. */
  620. protected void scan(File fromDir, File toDir, String[] files,
  621. String[] dirs) {
  622. FileNameMapper mapper = getMapper();
  623. buildMap(fromDir, toDir, files, mapper, fileCopyMap);
  624. if (includeEmpty) {
  625. buildMap(fromDir, toDir, dirs, mapper, dirCopyMap);
  626. }
  627. }
  628. /**
  629. * Compares source resources to destination files to see if they
  630. * should be copied.
  631. *
  632. * @param fromResources The source resources.
  633. * @param toDir The destination directory.
  634. *
  635. * @return a Map with the out-of-date resources as keys and an
  636. * array of target file names as values.
  637. *
  638. * @since Ant 1.7
  639. */
  640. protected Map scan(Resource[] fromResources, File toDir) {
  641. return buildMap(fromResources, toDir, getMapper());
  642. }
  643. /**
  644. * Add to a map of files/directories to copy.
  645. *
  646. * @param fromDir the source directory.
  647. * @param toDir the destination directory.
  648. * @param names a list of filenames.
  649. * @param mapper a <code>FileNameMapper</code> value.
  650. * @param map a map of source file to array of destination files.
  651. */
  652. protected void buildMap(File fromDir, File toDir, String[] names,
  653. FileNameMapper mapper, Hashtable map) {
  654. String[] toCopy = null;
  655. if (forceOverwrite) {
  656. Vector v = new Vector();
  657. for (int i = 0; i < names.length; i++) {
  658. if (mapper.mapFileName(names[i]) != null) {
  659. v.addElement(names[i]);
  660. }
  661. }
  662. toCopy = new String[v.size()];
  663. v.copyInto(toCopy);
  664. } else {
  665. SourceFileScanner ds = new SourceFileScanner(this);
  666. toCopy = ds.restrict(names, fromDir, toDir, mapper, granularity);
  667. }
  668. for (int i = 0; i < toCopy.length; i++) {
  669. File src = new File(fromDir, toCopy[i]);
  670. String[] mappedFiles = mapper.mapFileName(toCopy[i]);
  671. if (!enableMultipleMappings) {
  672. map.put(src.getAbsolutePath(),
  673. new String[] {new File(toDir, mappedFiles[0]).getAbsolutePath()});
  674. } else {
  675. // reuse the array created by the mapper
  676. for (int k = 0; k < mappedFiles.length; k++) {
  677. mappedFiles[k] = new File(toDir, mappedFiles[k]).getAbsolutePath();
  678. }
  679. map.put(src.getAbsolutePath(), mappedFiles);
  680. }
  681. }
  682. }
  683. /**
  684. * Create a map of resources to copy.
  685. *
  686. * @param fromResources The source resources.
  687. * @param toDir the destination directory.
  688. * @param mapper a <code>FileNameMapper</code> value.
  689. * @return a map of source resource to array of destination files.
  690. * @since Ant 1.7
  691. */
  692. protected Map buildMap(Resource[] fromResources, final File toDir,
  693. FileNameMapper mapper) {
  694. HashMap map = new HashMap();
  695. Resource[] toCopy = null;
  696. if (forceOverwrite) {
  697. Vector v = new Vector();
  698. for (int i = 0; i < fromResources.length; i++) {
  699. if (mapper.mapFileName(fromResources[i].getName()) != null) {
  700. v.addElement(fromResources[i]);
  701. }
  702. }
  703. toCopy = new Resource[v.size()];
  704. v.copyInto(toCopy);
  705. } else {
  706. toCopy =
  707. ResourceUtils.selectOutOfDateSources(this, fromResources,
  708. mapper,
  709. new ResourceFactory() {
  710. public Resource getResource(String name) {
  711. return new FileResource(toDir, name);
  712. }
  713. },
  714. granularity);
  715. }
  716. for (int i = 0; i < toCopy.length; i++) {
  717. String[] mappedFiles = mapper.mapFileName(toCopy[i].getName());
  718. for (int j = 0; j < mappedFiles.length; j++) {
  719. if (mappedFiles[j] == null) {
  720. throw new BuildException("Can't copy a resource without a"
  721. + " name if the mapper doesn't"
  722. + " provide one.");
  723. }
  724. }
  725. if (!enableMultipleMappings) {
  726. map.put(toCopy[i],
  727. new String[] {new File(toDir, mappedFiles[0]).getAbsolutePath()});
  728. } else {
  729. // reuse the array created by the mapper
  730. for (int k = 0; k < mappedFiles.length; k++) {
  731. mappedFiles[k] = new File(toDir, mappedFiles[k]).getAbsolutePath();
  732. }
  733. map.put(toCopy[i], mappedFiles);
  734. }
  735. }
  736. return map;
  737. }
  738. /**
  739. * Actually does the file (and possibly empty directory) copies.
  740. * This is a good method for subclasses to override.
  741. */
  742. protected void doFileOperations() {
  743. if (fileCopyMap.size() > 0) {
  744. log("Copying " + fileCopyMap.size()
  745. + " file" + (fileCopyMap.size() == 1 ? "" : "s")
  746. + " to " + destDir.getAbsolutePath());
  747. Enumeration e = fileCopyMap.keys();
  748. while (e.hasMoreElements()) {
  749. String fromFile = (String) e.nextElement();
  750. String[] toFiles = (String[]) fileCopyMap.get(fromFile);
  751. for (int i = 0; i < toFiles.length; i++) {
  752. String toFile = toFiles[i];
  753. if (fromFile.equals(toFile)) {
  754. log("Skipping self-copy of " + fromFile, verbosity);
  755. continue;
  756. }
  757. try {
  758. log("Copying " + fromFile + " to " + toFile, verbosity);
  759. FilterSetCollection executionFilters =
  760. new FilterSetCollection();
  761. if (filtering) {
  762. executionFilters
  763. .addFilterSet(getProject().getGlobalFilterSet());
  764. }
  765. for (Enumeration filterEnum = filterSets.elements();
  766. filterEnum.hasMoreElements();) {
  767. executionFilters
  768. .addFilterSet((FilterSet) filterEnum.nextElement());
  769. }
  770. fileUtils.copyFile(fromFile, toFile, executionFilters,
  771. filterChains, forceOverwrite,
  772. preserveLastModified, inputEncoding,
  773. outputEncoding, getProject());
  774. } catch (IOException ioe) {
  775. String msg = "Failed to copy " + fromFile + " to " + toFile
  776. + " due to " + getDueTo(ioe);
  777. File targetFile = new File(toFile);
  778. if (targetFile.exists() && !targetFile.delete()) {
  779. msg += " and I couldn't delete the corrupt " + toFile;
  780. }
  781. if (failonerror) {
  782. throw new BuildException(msg, ioe, getLocation());
  783. }
  784. log(msg, Project.MSG_ERR);
  785. }
  786. }
  787. }
  788. }
  789. if (includeEmpty) {
  790. Enumeration e = dirCopyMap.elements();
  791. int createCount = 0;
  792. while (e.hasMoreElements()) {
  793. String[] dirs = (String[]) e.nextElement();
  794. for (int i = 0; i < dirs.length; i++) {
  795. File d = new File(dirs[i]);
  796. if (!d.exists()) {
  797. if (!d.mkdirs()) {
  798. log("Unable to create directory "
  799. + d.getAbsolutePath(), Project.MSG_ERR);
  800. } else {
  801. createCount++;
  802. }
  803. }
  804. }
  805. }
  806. if (createCount > 0) {
  807. log("Copied " + dirCopyMap.size()
  808. + " empty director"
  809. + (dirCopyMap.size() == 1 ? "y" : "ies")
  810. + " to " + createCount
  811. + " empty director"
  812. + (createCount == 1 ? "y" : "ies") + " under "
  813. + destDir.getAbsolutePath());
  814. }
  815. }
  816. }
  817. /**
  818. * Actually does the resource copies.
  819. * This is a good method for subclasses to override.
  820. * @param map a map of source resource to array of destination files.
  821. * @since Ant 1.7
  822. */
  823. protected void doResourceOperations(Map map) {
  824. if (map.size() > 0) {
  825. log("Copying " + map.size()
  826. + " resource" + (map.size() == 1 ? "" : "s")
  827. + " to " + destDir.getAbsolutePath());
  828. Iterator iter = map.keySet().iterator();
  829. while (iter.hasNext()) {
  830. Resource fromResource = (Resource) iter.next();
  831. String[] toFiles = (String[]) map.get(fromResource);
  832. for (int i = 0; i < toFiles.length; i++) {
  833. String toFile = toFiles[i];
  834. try {
  835. log("Copying " + fromResource + " to " + toFile,
  836. verbosity);
  837. FilterSetCollection executionFilters =
  838. new FilterSetCollection();
  839. if (filtering) {
  840. executionFilters
  841. .addFilterSet(getProject().getGlobalFilterSet());
  842. }
  843. for (Enumeration filterEnum = filterSets.elements();
  844. filterEnum.hasMoreElements();) {
  845. executionFilters
  846. .addFilterSet((FilterSet) filterEnum.nextElement());
  847. }
  848. ResourceUtils.copyResource(fromResource,
  849. new FileResource(destDir,
  850. toFile),
  851. executionFilters,
  852. filterChains,
  853. forceOverwrite,
  854. preserveLastModified,
  855. inputEncoding,
  856. outputEncoding,
  857. getProject());
  858. } catch (IOException ioe) {
  859. String msg = "Failed to copy " + fromResource
  860. + " to " + toFile
  861. + " due to " + getDueTo(ioe);
  862. File targetFile = new File(toFile);
  863. if (targetFile.exists() && !targetFile.delete()) {
  864. msg += " and I couldn't delete the corrupt " + toFile;
  865. }
  866. if (failonerror) {
  867. throw new BuildException(msg, ioe, getLocation());
  868. }
  869. log(msg, Project.MSG_ERR);
  870. }
  871. }
  872. }
  873. }
  874. }
  875. /**
  876. * Whether this task can deal with non-file resources.
  877. *
  878. * <p>&lt;copy&gt; can while &lt;move&gt; can't since we don't
  879. * know how to remove non-file resources.</p>
  880. *
  881. * <p>This implementation returns true only if this task is
  882. * &lt;copy&gt;. Any subclass of this class that also wants to
  883. * support non-file resources needs to override this method. We
  884. * need to do so for backwards compatibility reasons since we
  885. * can't expect subclasses to support resources.</p>
  886. * @return true if this task supports non file resources.
  887. * @since Ant 1.7
  888. */
  889. protected boolean supportsNonFileResources() {
  890. return getClass().equals(Copy.class);
  891. }
  892. /**
  893. * Adds the given strings to a list contained in the given map.
  894. * The file is the key into the map.
  895. */
  896. private static void add(File baseDir, String[] names, Map m) {
  897. if (names != null) {
  898. baseDir = getKeyFile(baseDir);
  899. List l = (List) m.get(baseDir);
  900. if (l == null) {
  901. l = new ArrayList(names.length);
  902. m.put(baseDir, l);
  903. }
  904. l.addAll(java.util.Arrays.asList(names));
  905. }
  906. }
  907. /**
  908. * Adds the given string to a list contained in the given map.
  909. * The file is the key into the map.
  910. */
  911. private static void add(File baseDir, String name, Map m) {
  912. if (name != null) {
  913. add(baseDir, new String[] {name}, m);
  914. }
  915. }
  916. /**
  917. * Either returns its argument or a plaeholder if the argument is null.
  918. */
  919. private static File getKeyFile(File f) {
  920. return f == null ? NULL_FILE_PLACEHOLDER : f;
  921. }
  922. /**
  923. * returns the mapper to use based on nested elements or the
  924. * flatten attribute.
  925. */
  926. private FileNameMapper getMapper() {
  927. FileNameMapper mapper = null;
  928. if (mapperElement != null) {
  929. mapper = mapperElement.getImplementation();
  930. } else if (flatten) {
  931. mapper = new FlatFileNameMapper();
  932. } else {
  933. mapper = new IdentityMapper();
  934. }
  935. return mapper;
  936. }
  937. /**
  938. * Handle getMessage() for exceptions.
  939. * @param ex the exception to handle
  940. * @return ex.getMessage() if ex.getMessage() is not null
  941. * otherwise return ex.toString()
  942. */
  943. private String getMessage(Exception ex) {
  944. return ex.getMessage() == null ? ex.toString() : ex.getMessage();
  945. }
  946. /**
  947. * Returns a reason for failure based on
  948. * the exception thrown.
  949. * If the exception is not IOException output the class name,
  950. * output the message
  951. * if the exception is MalformedInput add a little note.
  952. */
  953. private String getDueTo(Exception ex) {
  954. boolean baseIOException = ex.getClass() == IOException.class;
  955. StringBuffer message = new StringBuffer();
  956. if (!baseIOException || ex.getMessage() == null) {
  957. message.append(ex.getClass().getName());
  958. }
  959. if (ex.getMessage() != null) {
  960. if (!baseIOException) {
  961. message.append(" ");
  962. }
  963. message.append(ex.getMessage());
  964. }
  965. if (ex.getClass().getName().indexOf("MalformedInput") != -1) {
  966. message.append(LINE_SEPARATOR);
  967. message.append(
  968. "This is normally due to the input file containing invalid");
  969. message.append(LINE_SEPARATOR);
  970. message.append("bytes for the character encoding used : ");
  971. message.append(
  972. (inputEncoding == null
  973. ? fileUtils.getDefaultEncoding() : inputEncoding));
  974. message.append(LINE_SEPARATOR);
  975. }
  976. return message.toString();
  977. }
  978. }