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.

Zip.java 62 kB

Addition of ZipFileset facilities. Descibed by the author --- With these patches, Zip (and derivative tasks such as Jar and War) can merge the entries of multiple zip files into a single output zip file. The contents of an input zip file may be selectively extracted based on include/exclude patterns. An included zip file is specified using a <fileset> with a "src" attribute, as in: <target name="jartest"> <jar jarfile="utils.jar"> <fileset src="weblogic.jar" includes="weblogic/utils/" excludes="weblogic/utils/jars/,**/reflect/" /> </jar> </target> In this example, a subset of the "weblogic/utils" directory is extracted from weblogic.jar, into utils.jar. The fileset may also contain "prefix" and "fullpath" attributes (the functionality of PrefixedFileSet has been retained in the new class ZipFileSet). Prefixes apply to directory-based and zip-based filesets. The fullpath attributes applies only to a single file in a directory-based fileset. The War task may extract entries from a zip file for all of its filesets (including the files in "classes" and "lib"). The motivation for this change is: 1) There is significant overlap between "jlink" and "zip", and it seemed better to combine them. 2) "jlink" does not support include/exclude patterns which are extremely useful for writing packaging-type tasks such as Zip/Jar/War. This was my main motivation. 3) By adding this functionality to the base task, it can also be used in derivative tasks such as Jar and War. --- Submitted By: Don Ferguson <don@bea.com> git-svn-id: https://svn.apache.org/repos/asf/ant/core/trunk@268458 13f79535-47bb-0310-9956-ffa450edef68
25 years ago
Addition of ZipFileset facilities. Descibed by the author --- With these patches, Zip (and derivative tasks such as Jar and War) can merge the entries of multiple zip files into a single output zip file. The contents of an input zip file may be selectively extracted based on include/exclude patterns. An included zip file is specified using a <fileset> with a "src" attribute, as in: <target name="jartest"> <jar jarfile="utils.jar"> <fileset src="weblogic.jar" includes="weblogic/utils/" excludes="weblogic/utils/jars/,**/reflect/" /> </jar> </target> In this example, a subset of the "weblogic/utils" directory is extracted from weblogic.jar, into utils.jar. The fileset may also contain "prefix" and "fullpath" attributes (the functionality of PrefixedFileSet has been retained in the new class ZipFileSet). Prefixes apply to directory-based and zip-based filesets. The fullpath attributes applies only to a single file in a directory-based fileset. The War task may extract entries from a zip file for all of its filesets (including the files in "classes" and "lib"). The motivation for this change is: 1) There is significant overlap between "jlink" and "zip", and it seemed better to combine them. 2) "jlink" does not support include/exclude patterns which are extremely useful for writing packaging-type tasks such as Zip/Jar/War. This was my main motivation. 3) By adding this functionality to the base task, it can also be used in derivative tasks such as Jar and War. --- Submitted By: Don Ferguson <don@bea.com> git-svn-id: https://svn.apache.org/repos/asf/ant/core/trunk@268458 13f79535-47bb-0310-9956-ffa450edef68
25 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712
  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.ByteArrayInputStream;
  20. import java.io.ByteArrayOutputStream;
  21. import java.io.File;
  22. import java.io.FileInputStream;
  23. import java.io.FileOutputStream;
  24. import java.io.IOException;
  25. import java.io.InputStream;
  26. import java.io.OutputStream;
  27. import java.util.ArrayList;
  28. import java.util.Enumeration;
  29. import java.util.Hashtable;
  30. import java.util.Iterator;
  31. import java.util.Stack;
  32. import java.util.Vector;
  33. import java.util.zip.CRC32;
  34. import org.apache.tools.ant.BuildException;
  35. import org.apache.tools.ant.DirectoryScanner;
  36. import org.apache.tools.ant.FileScanner;
  37. import org.apache.tools.ant.Project;
  38. import org.apache.tools.ant.types.ArchiveFileSet;
  39. import org.apache.tools.ant.types.EnumeratedAttribute;
  40. import org.apache.tools.ant.types.FileSet;
  41. import org.apache.tools.ant.types.PatternSet;
  42. import org.apache.tools.ant.types.Resource;
  43. import org.apache.tools.ant.types.ResourceCollection;
  44. import org.apache.tools.ant.types.ZipFileSet;
  45. import org.apache.tools.ant.types.ZipScanner;
  46. import org.apache.tools.ant.types.resources.ArchiveResource;
  47. import org.apache.tools.ant.types.resources.FileResource;
  48. import org.apache.tools.ant.util.FileNameMapper;
  49. import org.apache.tools.ant.util.FileUtils;
  50. import org.apache.tools.ant.util.GlobPatternMapper;
  51. import org.apache.tools.ant.util.IdentityMapper;
  52. import org.apache.tools.ant.util.MergingMapper;
  53. import org.apache.tools.ant.util.ResourceUtils;
  54. import org.apache.tools.zip.ZipEntry;
  55. import org.apache.tools.zip.ZipExtraField;
  56. import org.apache.tools.zip.ZipFile;
  57. import org.apache.tools.zip.ZipOutputStream;
  58. /**
  59. * Create a Zip file.
  60. *
  61. * @since Ant 1.1
  62. *
  63. * @ant.task category="packaging"
  64. */
  65. public class Zip extends MatchingTask {
  66. protected File zipFile;
  67. // use to scan own archive
  68. private ZipScanner zs;
  69. private File baseDir;
  70. protected Hashtable entries = new Hashtable();
  71. private Vector groupfilesets = new Vector();
  72. private Vector filesetsFromGroupfilesets = new Vector();
  73. protected String duplicate = "add";
  74. private boolean doCompress = true;
  75. private boolean doUpdate = false;
  76. // shadow of the above if the value is altered in execute
  77. private boolean savedDoUpdate = false;
  78. private boolean doFilesonly = false;
  79. protected String archiveType = "zip";
  80. // For directories:
  81. private static final long EMPTY_CRC = new CRC32 ().getValue ();
  82. protected String emptyBehavior = "skip";
  83. private Vector resources = new Vector();
  84. protected Hashtable addedDirs = new Hashtable();
  85. private Vector addedFiles = new Vector();
  86. protected boolean doubleFilePass = false;
  87. protected boolean skipWriting = false;
  88. private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
  89. /**
  90. * true when we are adding new files into the Zip file, as opposed
  91. * to adding back the unchanged files
  92. */
  93. private boolean addingNewFiles = false;
  94. /**
  95. * Encoding to use for filenames, defaults to the platform's
  96. * default encoding.
  97. */
  98. private String encoding;
  99. /**
  100. * Whether the original compression of entries coming from a ZIP
  101. * archive should be kept (for example when updating an archive).
  102. *
  103. * @since Ant 1.6
  104. */
  105. private boolean keepCompression = false;
  106. /**
  107. * Whether the file modification times will be rounded up to the
  108. * next even number of seconds.
  109. *
  110. * @since Ant 1.6.2
  111. */
  112. private boolean roundUp = true;
  113. /**
  114. * Comment for the archive.
  115. * @since Ant 1.6.3
  116. */
  117. private String comment = "";
  118. private int level = ZipOutputStream.DEFAULT_COMPRESSION;
  119. /**
  120. * This is the name/location of where to
  121. * create the .zip file.
  122. * @param zipFile the path of the zipFile
  123. * @deprecated since 1.5.x.
  124. * Use setDestFile(File) instead.
  125. * @ant.attribute ignore="true"
  126. */
  127. public void setZipfile(File zipFile) {
  128. setDestFile(zipFile);
  129. }
  130. /**
  131. * This is the name/location of where to
  132. * create the file.
  133. * @param file the path of the zipFile
  134. * @since Ant 1.5
  135. * @deprecated since 1.5.x.
  136. * Use setDestFile(File) instead.
  137. * @ant.attribute ignore="true"
  138. */
  139. public void setFile(File file) {
  140. setDestFile(file);
  141. }
  142. /**
  143. * The file to create; required.
  144. * @since Ant 1.5
  145. * @param destFile The new destination File
  146. */
  147. public void setDestFile(File destFile) {
  148. this.zipFile = destFile;
  149. }
  150. /**
  151. * The file to create.
  152. * @return the destination file
  153. * @since Ant 1.5.2
  154. */
  155. public File getDestFile() {
  156. return zipFile;
  157. }
  158. /**
  159. * Directory from which to archive files; optional.
  160. * @param baseDir the base directory
  161. */
  162. public void setBasedir(File baseDir) {
  163. this.baseDir = baseDir;
  164. }
  165. /**
  166. * Whether we want to compress the files or only store them;
  167. * optional, default=true;
  168. * @param c if true, compress the files
  169. */
  170. public void setCompress(boolean c) {
  171. doCompress = c;
  172. }
  173. /**
  174. * Whether we want to compress the files or only store them;
  175. * @return true if the files are to be compressed
  176. * @since Ant 1.5.2
  177. */
  178. public boolean isCompress() {
  179. return doCompress;
  180. }
  181. /**
  182. * If true, emulate Sun's jar utility by not adding parent directories;
  183. * optional, defaults to false.
  184. * @param f if true, emulate sun's jar by not adding parent directories
  185. */
  186. public void setFilesonly(boolean f) {
  187. doFilesonly = f;
  188. }
  189. /**
  190. * If true, updates an existing file, otherwise overwrite
  191. * any existing one; optional defaults to false.
  192. * @param c if true, updates an existing zip file
  193. */
  194. public void setUpdate(boolean c) {
  195. doUpdate = c;
  196. savedDoUpdate = c;
  197. }
  198. /**
  199. * Are we updating an existing archive?
  200. * @return true if updating an existing archive
  201. */
  202. public boolean isInUpdateMode() {
  203. return doUpdate;
  204. }
  205. /**
  206. * Adds a set of files.
  207. * @param set the fileset to add
  208. */
  209. public void addFileset(FileSet set) {
  210. add(set);
  211. }
  212. /**
  213. * Adds a set of files that can be
  214. * read from an archive and be given a prefix/fullpath.
  215. * @param set the zipfileset to add
  216. */
  217. public void addZipfileset(ZipFileSet set) {
  218. add(set);
  219. }
  220. /**
  221. * Add a collection of resources to be archived.
  222. * @param a the resources to archive
  223. * @since Ant 1.7
  224. */
  225. public void add(ResourceCollection a) {
  226. resources.add(a);
  227. }
  228. /**
  229. * Adds a group of zip files.
  230. * @param set the group (a fileset) to add
  231. */
  232. public void addZipGroupFileset(FileSet set) {
  233. groupfilesets.addElement(set);
  234. }
  235. /**
  236. * Sets behavior for when a duplicate file is about to be added -
  237. * one of <code>add</code>, <code>preserve</code> or <code>fail</code>.
  238. * Possible values are: <code>add</code> (keep both
  239. * of the files); <code>preserve</code> (keep the first version
  240. * of the file found); <code>fail</code> halt a problem
  241. * Default for zip tasks is <code>add</code>
  242. * @param df a <code>Duplicate</code> enumerated value
  243. */
  244. public void setDuplicate(Duplicate df) {
  245. duplicate = df.getValue();
  246. }
  247. /**
  248. * Possible behaviors when there are no matching files for the task:
  249. * "fail", "skip", or "create".
  250. */
  251. public static class WhenEmpty extends EnumeratedAttribute {
  252. /**
  253. * The string values for the enumerated value
  254. * @return the values
  255. */
  256. public String[] getValues() {
  257. return new String[] {"fail", "skip", "create"};
  258. }
  259. }
  260. /**
  261. * Sets behavior of the task when no files match.
  262. * Possible values are: <code>fail</code> (throw an exception
  263. * and halt the build); <code>skip</code> (do not create
  264. * any archive, but issue a warning); <code>create</code>
  265. * (make an archive with no entries).
  266. * Default for zip tasks is <code>skip</code>;
  267. * for jar tasks, <code>create</code>.
  268. * @param we a <code>WhenEmpty</code> enumerated value
  269. */
  270. public void setWhenempty(WhenEmpty we) {
  271. emptyBehavior = we.getValue();
  272. }
  273. /**
  274. * Encoding to use for filenames, defaults to the platform's
  275. * default encoding.
  276. *
  277. * <p>For a list of possible values see <a
  278. * href="http://java.sun.com/j2se/1.5.0/docs/guide/intl/encoding.doc.html">http://java.sun.com/j2se/1.5.0/docs/guide/intl/encoding.doc.html</a>.</p>
  279. * @param encoding the encoding name
  280. */
  281. public void setEncoding(String encoding) {
  282. this.encoding = encoding;
  283. }
  284. /**
  285. * Encoding to use for filenames.
  286. * @return the name of the encoding to use
  287. * @since Ant 1.5.2
  288. */
  289. public String getEncoding() {
  290. return encoding;
  291. }
  292. /**
  293. * Whether the original compression of entries coming from a ZIP
  294. * archive should be kept (for example when updating an archive).
  295. * Default is false.
  296. * @param keep if true, keep the original compression
  297. * @since Ant 1.6
  298. */
  299. public void setKeepCompression(boolean keep) {
  300. keepCompression = keep;
  301. }
  302. /**
  303. * Comment to use for archive.
  304. *
  305. * @param comment The content of the comment.
  306. * @since Ant 1.6.3
  307. */
  308. public void setComment(String comment) {
  309. this.comment = comment;
  310. }
  311. /**
  312. * Comment of the archive
  313. *
  314. * @return Comment of the archive.
  315. * @since Ant 1.6.3
  316. */
  317. public String getComment() {
  318. return comment;
  319. }
  320. /**
  321. * Set the compression level to use. Default is
  322. * ZipOutputStream.DEFAULT_COMPRESSION.
  323. * @param level compression level.
  324. * @since Ant 1.7
  325. */
  326. public void setLevel(int level) {
  327. this.level = level;
  328. }
  329. /**
  330. * Get the compression level.
  331. * @return compression level.
  332. * @since Ant 1.7
  333. */
  334. public int getLevel() {
  335. return level;
  336. }
  337. /**
  338. * Whether the file modification times will be rounded up to the
  339. * next even number of seconds.
  340. *
  341. * <p>Zip archives store file modification times with a
  342. * granularity of two seconds, so the times will either be rounded
  343. * up or down. If you round down, the archive will always seem
  344. * out-of-date when you rerun the task, so the default is to round
  345. * up. Rounding up may lead to a different type of problems like
  346. * JSPs inside a web archive that seem to be slightly more recent
  347. * than precompiled pages, rendering precompilation useless.</p>
  348. * @param r a <code>boolean</code> value
  349. * @since Ant 1.6.2
  350. */
  351. public void setRoundUp(boolean r) {
  352. roundUp = r;
  353. }
  354. /**
  355. * validate and build
  356. * @throws BuildException on error
  357. */
  358. public void execute() throws BuildException {
  359. if (doubleFilePass) {
  360. skipWriting = true;
  361. executeMain();
  362. skipWriting = false;
  363. executeMain();
  364. } else {
  365. executeMain();
  366. }
  367. }
  368. /**
  369. * Build the zip file.
  370. * This is called twice if doubleFilePass is true.
  371. * @throws BuildException on error
  372. */
  373. public void executeMain() throws BuildException {
  374. if (baseDir == null && resources.size() == 0
  375. && groupfilesets.size() == 0 && "zip".equals(archiveType)) {
  376. throw new BuildException("basedir attribute must be set, "
  377. + "or at least one "
  378. + "resource collection must be given!");
  379. }
  380. if (zipFile == null) {
  381. throw new BuildException("You must specify the "
  382. + archiveType + " file to create!");
  383. }
  384. if (zipFile.exists() && !zipFile.isFile()) {
  385. throw new BuildException(zipFile + " is not a file.");
  386. }
  387. if (zipFile.exists() && !zipFile.canWrite()) {
  388. throw new BuildException(zipFile + " is read-only.");
  389. }
  390. // Renamed version of original file, if it exists
  391. File renamedFile = null;
  392. addingNewFiles = true;
  393. // Whether or not an actual update is required -
  394. // we don't need to update if the original file doesn't exist
  395. if (doUpdate && !zipFile.exists()) {
  396. doUpdate = false;
  397. log("ignoring update attribute as " + archiveType
  398. + " doesn't exist.", Project.MSG_DEBUG);
  399. }
  400. // Add the files found in groupfileset to fileset
  401. for (int i = 0; i < groupfilesets.size(); i++) {
  402. log("Processing groupfileset ", Project.MSG_VERBOSE);
  403. FileSet fs = (FileSet) groupfilesets.elementAt(i);
  404. FileScanner scanner = fs.getDirectoryScanner(getProject());
  405. String[] files = scanner.getIncludedFiles();
  406. File basedir = scanner.getBasedir();
  407. for (int j = 0; j < files.length; j++) {
  408. log("Adding file " + files[j] + " to fileset",
  409. Project.MSG_VERBOSE);
  410. ZipFileSet zf = new ZipFileSet();
  411. zf.setProject(getProject());
  412. zf.setSrc(new File(basedir, files[j]));
  413. add(zf);
  414. filesetsFromGroupfilesets.addElement(zf);
  415. }
  416. }
  417. // collect filesets to pass them to getResourcesToAdd
  418. Vector vfss = new Vector();
  419. if (baseDir != null) {
  420. FileSet fs = (FileSet) getImplicitFileSet().clone();
  421. fs.setDir(baseDir);
  422. vfss.addElement(fs);
  423. }
  424. for (int i = 0; i < resources.size(); i++) {
  425. ResourceCollection rc = (ResourceCollection) resources.elementAt(i);
  426. vfss.addElement(rc);
  427. }
  428. ResourceCollection[] fss = new ResourceCollection[vfss.size()];
  429. vfss.copyInto(fss);
  430. boolean success = false;
  431. try {
  432. // can also handle empty archives
  433. ArchiveState state = getResourcesToAdd(fss, zipFile, false);
  434. // quick exit if the target is up to date
  435. if (!state.isOutOfDate()) {
  436. return;
  437. }
  438. if (!zipFile.exists() && state.isWithoutAnyResources()) {
  439. createEmptyZip(zipFile);
  440. return;
  441. }
  442. Resource[][] addThem = state.getResourcesToAdd();
  443. if (doUpdate) {
  444. renamedFile =
  445. FILE_UTILS.createTempFile("zip", ".tmp",
  446. zipFile.getParentFile());
  447. renamedFile.deleteOnExit();
  448. try {
  449. FILE_UTILS.rename(zipFile, renamedFile);
  450. } catch (SecurityException e) {
  451. throw new BuildException(
  452. "Not allowed to rename old file ("
  453. + zipFile.getAbsolutePath()
  454. + ") to temporary file");
  455. } catch (IOException e) {
  456. throw new BuildException(
  457. "Unable to rename old file ("
  458. + zipFile.getAbsolutePath()
  459. + ") to temporary file");
  460. }
  461. }
  462. String action = doUpdate ? "Updating " : "Building ";
  463. log(action + archiveType + ": " + zipFile.getAbsolutePath());
  464. ZipOutputStream zOut = null;
  465. try {
  466. if (!skipWriting) {
  467. zOut = new ZipOutputStream(zipFile);
  468. zOut.setEncoding(encoding);
  469. zOut.setMethod(doCompress
  470. ? ZipOutputStream.DEFLATED : ZipOutputStream.STORED);
  471. zOut.setLevel(level);
  472. }
  473. initZipOutputStream(zOut);
  474. // Add the explicit resource collections to the archive.
  475. for (int i = 0; i < fss.length; i++) {
  476. if (addThem[i].length != 0) {
  477. addResources(fss[i], addThem[i], zOut);
  478. }
  479. }
  480. if (doUpdate) {
  481. addingNewFiles = false;
  482. ZipFileSet oldFiles = new ZipFileSet();
  483. oldFiles.setProject(getProject());
  484. oldFiles.setSrc(renamedFile);
  485. oldFiles.setDefaultexcludes(false);
  486. for (int i = 0; i < addedFiles.size(); i++) {
  487. PatternSet.NameEntry ne = oldFiles.createExclude();
  488. ne.setName((String) addedFiles.elementAt(i));
  489. }
  490. DirectoryScanner ds =
  491. oldFiles.getDirectoryScanner(getProject());
  492. ((ZipScanner) ds).setEncoding(encoding);
  493. String[] f = ds.getIncludedFiles();
  494. Resource[] r = new Resource[f.length];
  495. for (int i = 0; i < f.length; i++) {
  496. r[i] = ds.getResource(f[i]);
  497. }
  498. if (!doFilesonly) {
  499. String[] d = ds.getIncludedDirectories();
  500. Resource[] dr = new Resource[d.length];
  501. for (int i = 0; i < d.length; i++) {
  502. dr[i] = ds.getResource(d[i]);
  503. }
  504. Resource[] tmp = r;
  505. r = new Resource[tmp.length + dr.length];
  506. System.arraycopy(dr, 0, r, 0, dr.length);
  507. System.arraycopy(tmp, 0, r, dr.length, tmp.length);
  508. }
  509. addResources(oldFiles, r, zOut);
  510. }
  511. if (zOut != null) {
  512. zOut.setComment(comment);
  513. }
  514. finalizeZipOutputStream(zOut);
  515. // If we've been successful on an update, delete the
  516. // temporary file
  517. if (doUpdate) {
  518. if (!renamedFile.delete()) {
  519. log ("Warning: unable to delete temporary file "
  520. + renamedFile.getName(), Project.MSG_WARN);
  521. }
  522. }
  523. success = true;
  524. } finally {
  525. // Close the output stream.
  526. try {
  527. if (zOut != null) {
  528. zOut.close();
  529. }
  530. } catch (IOException ex) {
  531. // If we're in this finally clause because of an
  532. // exception, we don't really care if there's an
  533. // exception when closing the stream. E.g. if it
  534. // throws "ZIP file must have at least one entry",
  535. // because an exception happened before we added
  536. // any files, then we must swallow this
  537. // exception. Otherwise, the error that's reported
  538. // will be the close() error, which is not the
  539. // real cause of the problem.
  540. if (success) {
  541. throw ex;
  542. }
  543. }
  544. }
  545. } catch (IOException ioe) {
  546. String msg = "Problem creating " + archiveType + ": "
  547. + ioe.getMessage();
  548. // delete a bogus ZIP file (but only if it's not the original one)
  549. if ((!doUpdate || renamedFile != null) && !zipFile.delete()) {
  550. msg += " (and the archive is probably corrupt but I could not "
  551. + "delete it)";
  552. }
  553. if (doUpdate && renamedFile != null) {
  554. try {
  555. FILE_UTILS.rename(renamedFile, zipFile);
  556. } catch (IOException e) {
  557. msg += " (and I couldn't rename the temporary file "
  558. + renamedFile.getName() + " back)";
  559. }
  560. }
  561. throw new BuildException(msg, ioe, getLocation());
  562. } finally {
  563. cleanUp();
  564. }
  565. }
  566. /**
  567. * Indicates if the task is adding new files into the archive as opposed to
  568. * copying back unchanged files from the backup copy
  569. * @return true if adding new files
  570. */
  571. protected final boolean isAddingNewFiles() {
  572. return addingNewFiles;
  573. }
  574. /**
  575. * Add the given resources.
  576. *
  577. * @param fileset may give additional information like fullpath or
  578. * permissions.
  579. * @param resources the resources to add
  580. * @param zOut the stream to write to
  581. * @throws IOException on error
  582. *
  583. * @since Ant 1.5.2
  584. */
  585. protected final void addResources(FileSet fileset, Resource[] resources,
  586. ZipOutputStream zOut)
  587. throws IOException {
  588. String prefix = "";
  589. String fullpath = "";
  590. int dirMode = ArchiveFileSet.DEFAULT_DIR_MODE;
  591. int fileMode = ArchiveFileSet.DEFAULT_FILE_MODE;
  592. ArchiveFileSet zfs = null;
  593. if (fileset instanceof ArchiveFileSet) {
  594. zfs = (ArchiveFileSet) fileset;
  595. prefix = zfs.getPrefix(getProject());
  596. fullpath = zfs.getFullpath(getProject());
  597. dirMode = zfs.getDirMode(getProject());
  598. fileMode = zfs.getFileMode(getProject());
  599. }
  600. if (prefix.length() > 0 && fullpath.length() > 0) {
  601. throw new BuildException("Both prefix and fullpath attributes must"
  602. + " not be set on the same fileset.");
  603. }
  604. if (resources.length != 1 && fullpath.length() > 0) {
  605. throw new BuildException("fullpath attribute may only be specified"
  606. + " for filesets that specify a single"
  607. + " file.");
  608. }
  609. if (prefix.length() > 0) {
  610. if (!prefix.endsWith("/") && !prefix.endsWith("\\")) {
  611. prefix += "/";
  612. }
  613. addParentDirs(null, prefix, zOut, "", dirMode);
  614. }
  615. ZipFile zf = null;
  616. try {
  617. boolean dealingWithFiles = false;
  618. File base = null;
  619. if (zfs == null || zfs.getSrc(getProject()) == null) {
  620. dealingWithFiles = true;
  621. base = fileset.getDir(getProject());
  622. } else if (zfs instanceof ZipFileSet) {
  623. zf = new ZipFile(zfs.getSrc(getProject()), encoding);
  624. }
  625. for (int i = 0; i < resources.length; i++) {
  626. String name = null;
  627. if (fullpath.length() > 0) {
  628. name = fullpath;
  629. } else {
  630. name = resources[i].getName();
  631. }
  632. name = name.replace(File.separatorChar, '/');
  633. if ("".equals(name)) {
  634. continue;
  635. }
  636. if (resources[i].isDirectory() && !name.endsWith("/")) {
  637. name = name + "/";
  638. }
  639. if (!doFilesonly && !dealingWithFiles
  640. && resources[i].isDirectory()
  641. && !zfs.hasDirModeBeenSet()) {
  642. int nextToLastSlash = name.lastIndexOf("/",
  643. name.length() - 2);
  644. if (nextToLastSlash != -1) {
  645. addParentDirs(base, name.substring(0,
  646. nextToLastSlash + 1),
  647. zOut, prefix, dirMode);
  648. }
  649. if (zf != null) {
  650. ZipEntry ze = zf.getEntry(resources[i].getName());
  651. addParentDirs(base, name, zOut, prefix,
  652. ze.getUnixMode());
  653. } else {
  654. ArchiveResource tr = (ArchiveResource) resources[i];
  655. addParentDirs(base, name, zOut, prefix,
  656. tr.getMode());
  657. }
  658. } else {
  659. addParentDirs(base, name, zOut, prefix, dirMode);
  660. }
  661. if (!resources[i].isDirectory() && dealingWithFiles) {
  662. File f = FILE_UTILS.resolveFile(base,
  663. resources[i].getName());
  664. zipFile(f, zOut, prefix + name, fileMode);
  665. } else if (!resources[i].isDirectory()) {
  666. if (zf != null) {
  667. ZipEntry ze = zf.getEntry(resources[i].getName());
  668. if (ze != null) {
  669. boolean oldCompress = doCompress;
  670. if (keepCompression) {
  671. doCompress = (ze.getMethod() == ZipEntry.DEFLATED);
  672. }
  673. try {
  674. zipFile(zf.getInputStream(ze), zOut, prefix + name,
  675. ze.getTime(), zfs.getSrc(getProject()),
  676. zfs.hasFileModeBeenSet() ? fileMode
  677. : ze.getUnixMode());
  678. } finally {
  679. doCompress = oldCompress;
  680. }
  681. }
  682. } else {
  683. ArchiveResource tr = (ArchiveResource) resources[i];
  684. InputStream is = null;
  685. try {
  686. is = tr.getInputStream();
  687. zipFile(is, zOut, prefix + name,
  688. resources[i].getLastModified(),
  689. zfs.getSrc(getProject()),
  690. zfs.hasFileModeBeenSet() ? fileMode
  691. : tr.getMode());
  692. } finally {
  693. FileUtils.close(is);
  694. }
  695. }
  696. }
  697. }
  698. } finally {
  699. if (zf != null) {
  700. zf.close();
  701. }
  702. }
  703. }
  704. /**
  705. * Add the given resources.
  706. *
  707. * @param rc may give additional information like fullpath or
  708. * permissions.
  709. * @param resources the resources to add
  710. * @param zOut the stream to write to
  711. * @throws IOException on error
  712. *
  713. * @since Ant 1.7
  714. */
  715. protected final void addResources(ResourceCollection rc,
  716. Resource[] resources,
  717. ZipOutputStream zOut)
  718. throws IOException {
  719. if (rc instanceof FileSet) {
  720. addResources((FileSet) rc, resources, zOut);
  721. return;
  722. }
  723. for (int i = 0; i < resources.length; i++) {
  724. String name = resources[i].getName().replace(File.separatorChar,
  725. '/');
  726. if ("".equals(name)) {
  727. continue;
  728. }
  729. if (resources[i].isDirectory() && doFilesonly) {
  730. continue;
  731. }
  732. File base = null;
  733. if (resources[i] instanceof FileResource) {
  734. base = ((FileResource) resources[i]).getBaseDir();
  735. }
  736. if (resources[i].isDirectory()) {
  737. if (!name.endsWith("/")) {
  738. name = name + "/";
  739. }
  740. }
  741. addParentDirs(base, name, zOut, "",
  742. ArchiveFileSet.DEFAULT_DIR_MODE);
  743. if (!resources[i].isDirectory()) {
  744. if (resources[i] instanceof FileResource) {
  745. File f = ((FileResource) resources[i]).getFile();
  746. zipFile(f, zOut, name, ArchiveFileSet.DEFAULT_FILE_MODE);
  747. } else {
  748. InputStream is = null;
  749. try {
  750. is = resources[i].getInputStream();
  751. zipFile(is, zOut, name,
  752. resources[i].getLastModified(),
  753. null, ArchiveFileSet.DEFAULT_FILE_MODE);
  754. } finally {
  755. FileUtils.close(is);
  756. }
  757. }
  758. }
  759. }
  760. }
  761. /**
  762. * method for subclasses to override
  763. * @param zOut the zip output stream
  764. * @throws IOException on output error
  765. * @throws BuildException on other errors
  766. */
  767. protected void initZipOutputStream(ZipOutputStream zOut)
  768. throws IOException, BuildException {
  769. }
  770. /**
  771. * method for subclasses to override
  772. * @param zOut the zip output stream
  773. * @throws IOException on output error
  774. * @throws BuildException on other errors
  775. */
  776. protected void finalizeZipOutputStream(ZipOutputStream zOut)
  777. throws IOException, BuildException {
  778. }
  779. /**
  780. * Create an empty zip file
  781. * @param zipFile the zip file
  782. * @return true for historic reasons
  783. * @throws BuildException on error
  784. */
  785. protected boolean createEmptyZip(File zipFile) throws BuildException {
  786. // In this case using java.util.zip will not work
  787. // because it does not permit a zero-entry archive.
  788. // Must create it manually.
  789. log("Note: creating empty " + archiveType + " archive " + zipFile,
  790. Project.MSG_INFO);
  791. OutputStream os = null;
  792. try {
  793. os = new FileOutputStream(zipFile);
  794. // Cf. PKZIP specification.
  795. byte[] empty = new byte[22];
  796. empty[0] = 80; // P
  797. empty[1] = 75; // K
  798. empty[2] = 5;
  799. empty[3] = 6;
  800. // remainder zeros
  801. os.write(empty);
  802. } catch (IOException ioe) {
  803. throw new BuildException("Could not create empty ZIP archive "
  804. + "(" + ioe.getMessage() + ")", ioe,
  805. getLocation());
  806. } finally {
  807. if (os != null) {
  808. try {
  809. os.close();
  810. } catch (IOException e) {
  811. //ignore
  812. }
  813. }
  814. }
  815. return true;
  816. }
  817. /**
  818. * @since Ant 1.5.2
  819. */
  820. private synchronized ZipScanner getZipScanner() {
  821. if (zs == null) {
  822. zs = new ZipScanner();
  823. zs.setEncoding(encoding);
  824. zs.setSrc(zipFile);
  825. }
  826. return zs;
  827. }
  828. /**
  829. * Collect the resources that are newer than the corresponding
  830. * entries (or missing) in the original archive.
  831. *
  832. * <p>If we are going to recreate the archive instead of updating
  833. * it, all resources should be considered as new, if a single one
  834. * is. Because of this, subclasses overriding this method must
  835. * call <code>super.getResourcesToAdd</code> and indicate with the
  836. * third arg if they already know that the archive is
  837. * out-of-date.</p>
  838. *
  839. * <p>This method first delegates to getNonFileSetResourceToAdd
  840. * and then invokes the FileSet-arg version. All this to keep
  841. * backwards compatibility for subclasses that don't know how to
  842. * deal with non-FileSet ResourceCollections.</p>
  843. *
  844. * @param rcs The resource collections to grab resources from
  845. * @param zipFile intended archive file (may or may not exist)
  846. * @param needsUpdate whether we already know that the archive is
  847. * out-of-date. Subclasses overriding this method are supposed to
  848. * set this value correctly in their call to
  849. * <code>super.getResourcesToAdd</code>.
  850. * @return an array of resources to add for each fileset passed in as well
  851. * as a flag that indicates whether the archive is uptodate.
  852. *
  853. * @exception BuildException if it likes
  854. * @since Ant 1.7
  855. */
  856. protected ArchiveState getResourcesToAdd(ResourceCollection[] rcs,
  857. File zipFile,
  858. boolean needsUpdate)
  859. throws BuildException {
  860. ArrayList filesets = new ArrayList();
  861. ArrayList rest = new ArrayList();
  862. for (int i = 0; i < rcs.length; i++) {
  863. if (rcs[i] instanceof FileSet) {
  864. filesets.add(rcs[i]);
  865. } else {
  866. rest.add(rcs[i]);
  867. }
  868. }
  869. ResourceCollection[] rc = (ResourceCollection[])
  870. rest.toArray(new ResourceCollection[rest.size()]);
  871. ArchiveState as = getNonFileSetResourcesToAdd(rc, zipFile,
  872. needsUpdate);
  873. FileSet[] fs = (FileSet[]) filesets.toArray(new FileSet[filesets
  874. .size()]);
  875. ArchiveState as2 = getResourcesToAdd(fs, zipFile, as.isOutOfDate());
  876. if (!as.isOutOfDate() && as2.isOutOfDate()) {
  877. /*
  878. * Bad luck.
  879. *
  880. * There are resources in the filesets that make the
  881. * archive out of date, but not in the non-fileset
  882. * resources. We need to rescan the non-FileSets to grab
  883. * all of them now.
  884. */
  885. as = getNonFileSetResourcesToAdd(rc, zipFile, true);
  886. }
  887. Resource[][] toAdd = new Resource[rcs.length][];
  888. int fsIndex = 0;
  889. int restIndex = 0;
  890. for (int i = 0; i < rcs.length; i++) {
  891. if (rcs[i] instanceof FileSet) {
  892. toAdd[i] = as2.getResourcesToAdd()[fsIndex++];
  893. } else {
  894. toAdd[i] = as.getResourcesToAdd()[restIndex++];
  895. }
  896. }
  897. return new ArchiveState(as2.isOutOfDate(), toAdd);
  898. }
  899. /**
  900. * Collect the resources that are newer than the corresponding
  901. * entries (or missing) in the original archive.
  902. *
  903. * <p>If we are going to recreate the archive instead of updating
  904. * it, all resources should be considered as new, if a single one
  905. * is. Because of this, subclasses overriding this method must
  906. * call <code>super.getResourcesToAdd</code> and indicate with the
  907. * third arg if they already know that the archive is
  908. * out-of-date.</p>
  909. *
  910. * @param filesets The filesets to grab resources from
  911. * @param zipFile intended archive file (may or may not exist)
  912. * @param needsUpdate whether we already know that the archive is
  913. * out-of-date. Subclasses overriding this method are supposed to
  914. * set this value correctly in their call to
  915. * <code>super.getResourcesToAdd</code>.
  916. * @return an array of resources to add for each fileset passed in as well
  917. * as a flag that indicates whether the archive is uptodate.
  918. *
  919. * @exception BuildException if it likes
  920. */
  921. protected ArchiveState getResourcesToAdd(FileSet[] filesets,
  922. File zipFile,
  923. boolean needsUpdate)
  924. throws BuildException {
  925. Resource[][] initialResources = grabResources(filesets);
  926. if (isEmpty(initialResources)) {
  927. if (needsUpdate && doUpdate) {
  928. /*
  929. * This is a rather hairy case.
  930. *
  931. * One of our subclasses knows that we need to update the
  932. * archive, but at the same time, there are no resources
  933. * known to us that would need to be added. Only the
  934. * subclass seems to know what's going on.
  935. *
  936. * This happens if <jar> detects that the manifest has changed,
  937. * for example. The manifest is not part of any resources
  938. * because of our support for inline <manifest>s.
  939. *
  940. * If we invoke createEmptyZip like Ant 1.5.2 did,
  941. * we'll loose all stuff that has been in the original
  942. * archive (bugzilla report 17780).
  943. */
  944. return new ArchiveState(true, initialResources);
  945. }
  946. if (emptyBehavior.equals("skip")) {
  947. if (doUpdate) {
  948. log(archiveType + " archive " + zipFile
  949. + " not updated because no new files were included.",
  950. Project.MSG_VERBOSE);
  951. } else {
  952. log("Warning: skipping " + archiveType + " archive "
  953. + zipFile + " because no files were included.",
  954. Project.MSG_WARN);
  955. }
  956. } else if (emptyBehavior.equals("fail")) {
  957. throw new BuildException("Cannot create " + archiveType
  958. + " archive " + zipFile
  959. + ": no files were included.",
  960. getLocation());
  961. } else {
  962. // Create.
  963. if (!zipFile.exists()) {
  964. needsUpdate = true;
  965. }
  966. }
  967. return new ArchiveState(needsUpdate, initialResources);
  968. }
  969. // initialResources is not empty
  970. if (!zipFile.exists()) {
  971. return new ArchiveState(true, initialResources);
  972. }
  973. if (needsUpdate && !doUpdate) {
  974. // we are recreating the archive, need all resources
  975. return new ArchiveState(true, initialResources);
  976. }
  977. Resource[][] newerResources = new Resource[filesets.length][];
  978. for (int i = 0; i < filesets.length; i++) {
  979. if (!(fileset instanceof ZipFileSet)
  980. || ((ZipFileSet) fileset).getSrc(getProject()) == null) {
  981. File base = filesets[i].getDir(getProject());
  982. for (int j = 0; j < initialResources[i].length; j++) {
  983. File resourceAsFile =
  984. FILE_UTILS.resolveFile(base,
  985. initialResources[i][j].getName());
  986. if (resourceAsFile.equals(zipFile)) {
  987. throw new BuildException("A zip file cannot include "
  988. + "itself", getLocation());
  989. }
  990. }
  991. }
  992. }
  993. for (int i = 0; i < filesets.length; i++) {
  994. if (initialResources[i].length == 0) {
  995. newerResources[i] = new Resource[] {};
  996. continue;
  997. }
  998. FileNameMapper myMapper = new IdentityMapper();
  999. if (filesets[i] instanceof ZipFileSet) {
  1000. ZipFileSet zfs = (ZipFileSet) filesets[i];
  1001. if (zfs.getFullpath(getProject()) != null
  1002. && !zfs.getFullpath(getProject()).equals("")) {
  1003. // in this case all files from origin map to
  1004. // the fullPath attribute of the zipfileset at
  1005. // destination
  1006. MergingMapper fm = new MergingMapper();
  1007. fm.setTo(zfs.getFullpath(getProject()));
  1008. myMapper = fm;
  1009. } else if (zfs.getPrefix(getProject()) != null
  1010. && !zfs.getPrefix(getProject()).equals("")) {
  1011. GlobPatternMapper gm = new GlobPatternMapper();
  1012. gm.setFrom("*");
  1013. String prefix = zfs.getPrefix(getProject());
  1014. if (!prefix.endsWith("/") && !prefix.endsWith("\\")) {
  1015. prefix += "/";
  1016. }
  1017. gm.setTo(prefix + "*");
  1018. myMapper = gm;
  1019. }
  1020. }
  1021. Resource[] resources = initialResources[i];
  1022. if (doFilesonly) {
  1023. resources = selectFileResources(resources);
  1024. }
  1025. newerResources[i] =
  1026. ResourceUtils.selectOutOfDateSources(this,
  1027. resources,
  1028. myMapper,
  1029. getZipScanner());
  1030. needsUpdate = needsUpdate || (newerResources[i].length > 0);
  1031. if (needsUpdate && !doUpdate) {
  1032. // we will return initialResources anyway, no reason
  1033. // to scan further.
  1034. break;
  1035. }
  1036. }
  1037. if (needsUpdate && !doUpdate) {
  1038. // we are recreating the archive, need all resources
  1039. return new ArchiveState(true, initialResources);
  1040. }
  1041. return new ArchiveState(needsUpdate, newerResources);
  1042. }
  1043. /**
  1044. * Collect the resources that are newer than the corresponding
  1045. * entries (or missing) in the original archive.
  1046. *
  1047. * <p>If we are going to recreate the archive instead of updating
  1048. * it, all resources should be considered as new, if a single one
  1049. * is. Because of this, subclasses overriding this method must
  1050. * call <code>super.getResourcesToAdd</code> and indicate with the
  1051. * third arg if they already know that the archive is
  1052. * out-of-date.</p>
  1053. *
  1054. * @param rcs The filesets to grab resources from
  1055. * @param zipFile intended archive file (may or may not exist)
  1056. * @param needsUpdate whether we already know that the archive is
  1057. * out-of-date. Subclasses overriding this method are supposed to
  1058. * set this value correctly in their call to
  1059. * <code>super.getResourcesToAdd</code>.
  1060. * @return an array of resources to add for each fileset passed in as well
  1061. * as a flag that indicates whether the archive is uptodate.
  1062. *
  1063. * @exception BuildException if it likes
  1064. */
  1065. protected ArchiveState getNonFileSetResourcesToAdd(ResourceCollection[] rcs,
  1066. File zipFile,
  1067. boolean needsUpdate)
  1068. throws BuildException {
  1069. /*
  1070. * Backwards compatibility forces us to repeat the logic of
  1071. * getResourcesToAdd(FileSet[], ...) here once again.
  1072. */
  1073. Resource[][] initialResources = grabNonFileSetResources(rcs);
  1074. if (isEmpty(initialResources)) {
  1075. // no emptyBehavior handling since the FileSet version
  1076. // will take care of it.
  1077. return new ArchiveState(needsUpdate, initialResources);
  1078. }
  1079. // initialResources is not empty
  1080. if (!zipFile.exists()) {
  1081. return new ArchiveState(true, initialResources);
  1082. }
  1083. if (needsUpdate && !doUpdate) {
  1084. // we are recreating the archive, need all resources
  1085. return new ArchiveState(true, initialResources);
  1086. }
  1087. Resource[][] newerResources = new Resource[rcs.length][];
  1088. for (int i = 0; i < rcs.length; i++) {
  1089. if (initialResources[i].length == 0) {
  1090. newerResources[i] = new Resource[] {};
  1091. continue;
  1092. }
  1093. for (int j = 0; j < initialResources[i].length; j++) {
  1094. if (initialResources[i][j] instanceof FileResource
  1095. && zipFile.equals(((FileResource)
  1096. initialResources[i][j]).getFile())) {
  1097. throw new BuildException("A zip file cannot include "
  1098. + "itself", getLocation());
  1099. }
  1100. }
  1101. Resource[] rs = initialResources[i];
  1102. if (doFilesonly) {
  1103. rs = selectFileResources(rs);
  1104. }
  1105. newerResources[i] =
  1106. ResourceUtils.selectOutOfDateSources(this,
  1107. rs,
  1108. new IdentityMapper(),
  1109. getZipScanner());
  1110. needsUpdate = needsUpdate || (newerResources[i].length > 0);
  1111. if (needsUpdate && !doUpdate) {
  1112. // we will return initialResources anyway, no reason
  1113. // to scan further.
  1114. break;
  1115. }
  1116. }
  1117. if (needsUpdate && !doUpdate) {
  1118. // we are recreating the archive, need all resources
  1119. return new ArchiveState(true, initialResources);
  1120. }
  1121. return new ArchiveState(needsUpdate, newerResources);
  1122. }
  1123. /**
  1124. * Fetch all included and not excluded resources from the sets.
  1125. *
  1126. * <p>Included directories will precede included files.</p>
  1127. * @param filesets an array of filesets
  1128. * @return the resources included
  1129. * @since Ant 1.5.2
  1130. */
  1131. protected Resource[][] grabResources(FileSet[] filesets) {
  1132. Resource[][] result = new Resource[filesets.length][];
  1133. for (int i = 0; i < filesets.length; i++) {
  1134. boolean skipEmptyNames = true;
  1135. if (filesets[i] instanceof ZipFileSet) {
  1136. ZipFileSet zfs = (ZipFileSet) filesets[i];
  1137. skipEmptyNames = zfs.getPrefix(getProject()).equals("")
  1138. && zfs.getFullpath(getProject()).equals("");
  1139. }
  1140. DirectoryScanner rs =
  1141. filesets[i].getDirectoryScanner(getProject());
  1142. if (rs instanceof ZipScanner) {
  1143. ((ZipScanner) rs).setEncoding(encoding);
  1144. }
  1145. Vector resources = new Vector();
  1146. if (!doFilesonly) {
  1147. String[] directories = rs.getIncludedDirectories();
  1148. for (int j = 0; j < directories.length; j++) {
  1149. if (!"".equals(directories[j]) || !skipEmptyNames) {
  1150. resources.addElement(rs.getResource(directories[j]));
  1151. }
  1152. }
  1153. }
  1154. String[] files = rs.getIncludedFiles();
  1155. for (int j = 0; j < files.length; j++) {
  1156. if (!"".equals(files[j]) || !skipEmptyNames) {
  1157. resources.addElement(rs.getResource(files[j]));
  1158. }
  1159. }
  1160. result[i] = new Resource[resources.size()];
  1161. resources.copyInto(result[i]);
  1162. }
  1163. return result;
  1164. }
  1165. /**
  1166. * Fetch all included and not excluded resources from the collections.
  1167. *
  1168. * <p>Included directories will precede included files.</p>
  1169. * @param rcs an array of resource collections
  1170. * @return the resources included
  1171. * @since Ant 1.7
  1172. */
  1173. protected Resource[][] grabNonFileSetResources(ResourceCollection[] rcs) {
  1174. Resource[][] result = new Resource[rcs.length][];
  1175. for (int i = 0; i < rcs.length; i++) {
  1176. Iterator iter = rcs[i].iterator();
  1177. ArrayList rs = new ArrayList();
  1178. int lastDir = 0;
  1179. while (iter.hasNext()) {
  1180. Resource r = (Resource) iter.next();
  1181. if (r.isExists()) {
  1182. if (r.isDirectory()) {
  1183. rs.add(lastDir++, r);
  1184. } else {
  1185. rs.add(r);
  1186. }
  1187. }
  1188. }
  1189. result[i] = (Resource[]) rs.toArray(new Resource[rs.size()]);
  1190. }
  1191. return result;
  1192. }
  1193. /**
  1194. * Add a directory to the zip stream.
  1195. * @param dir the directort to add to the archive
  1196. * @param zOut the stream to write to
  1197. * @param vPath the name this entry shall have in the archive
  1198. * @param mode the Unix permissions to set.
  1199. * @throws IOException on error
  1200. * @since Ant 1.5.2
  1201. */
  1202. protected void zipDir(File dir, ZipOutputStream zOut, String vPath,
  1203. int mode)
  1204. throws IOException {
  1205. zipDir(dir, zOut, vPath, mode, null);
  1206. }
  1207. /**
  1208. * Add a directory to the zip stream.
  1209. * @param dir the directort to add to the archive
  1210. * @param zOut the stream to write to
  1211. * @param vPath the name this entry shall have in the archive
  1212. * @param mode the Unix permissions to set.
  1213. * @param extra ZipExtraFields to add
  1214. * @throws IOException on error
  1215. * @since Ant 1.6.3
  1216. */
  1217. protected void zipDir(File dir, ZipOutputStream zOut, String vPath,
  1218. int mode, ZipExtraField[] extra)
  1219. throws IOException {
  1220. if (doFilesonly) {
  1221. log("skipping directory " + vPath + " for file-only archive",
  1222. Project.MSG_VERBOSE);
  1223. return;
  1224. }
  1225. if (addedDirs.get(vPath) != null) {
  1226. // don't add directories we've already added.
  1227. // no warning if we try, it is harmless in and of itself
  1228. return;
  1229. }
  1230. log("adding directory " + vPath, Project.MSG_VERBOSE);
  1231. addedDirs.put(vPath, vPath);
  1232. if (!skipWriting) {
  1233. ZipEntry ze = new ZipEntry (vPath);
  1234. if (dir != null && dir.exists()) {
  1235. // ZIPs store time with a granularity of 2 seconds, round up
  1236. ze.setTime(dir.lastModified() + (roundUp ? 1999 : 0));
  1237. } else {
  1238. // ZIPs store time with a granularity of 2 seconds, round up
  1239. ze.setTime(System.currentTimeMillis() + (roundUp ? 1999 : 0));
  1240. }
  1241. ze.setSize (0);
  1242. ze.setMethod (ZipEntry.STORED);
  1243. // This is faintly ridiculous:
  1244. ze.setCrc (EMPTY_CRC);
  1245. ze.setUnixMode(mode);
  1246. if (extra != null) {
  1247. ze.setExtraFields(extra);
  1248. }
  1249. zOut.putNextEntry(ze);
  1250. }
  1251. }
  1252. /**
  1253. * Adds a new entry to the archive, takes care of duplicates as well.
  1254. *
  1255. * @param in the stream to read data for the entry from.
  1256. * @param zOut the stream to write to.
  1257. * @param vPath the name this entry shall have in the archive.
  1258. * @param lastModified last modification time for the entry.
  1259. * @param fromArchive the original archive we are copying this
  1260. * entry from, will be null if we are not copying from an archive.
  1261. * @param mode the Unix permissions to set.
  1262. *
  1263. * @since Ant 1.5.2
  1264. * @throws IOException on error
  1265. */
  1266. protected void zipFile(InputStream in, ZipOutputStream zOut, String vPath,
  1267. long lastModified, File fromArchive, int mode)
  1268. throws IOException {
  1269. if (entries.contains(vPath)) {
  1270. if (duplicate.equals("preserve")) {
  1271. log(vPath + " already added, skipping", Project.MSG_INFO);
  1272. return;
  1273. } else if (duplicate.equals("fail")) {
  1274. throw new BuildException("Duplicate file " + vPath
  1275. + " was found and the duplicate "
  1276. + "attribute is 'fail'.");
  1277. } else {
  1278. // duplicate equal to add, so we continue
  1279. log("duplicate file " + vPath
  1280. + " found, adding.", Project.MSG_VERBOSE);
  1281. }
  1282. } else {
  1283. log("adding entry " + vPath, Project.MSG_VERBOSE);
  1284. }
  1285. entries.put(vPath, vPath);
  1286. if (!skipWriting) {
  1287. ZipEntry ze = new ZipEntry(vPath);
  1288. ze.setTime(lastModified);
  1289. ze.setMethod(doCompress ? ZipEntry.DEFLATED : ZipEntry.STORED);
  1290. /*
  1291. * ZipOutputStream.putNextEntry expects the ZipEntry to
  1292. * know its size and the CRC sum before you start writing
  1293. * the data when using STORED mode - unless it is seekable.
  1294. *
  1295. * This forces us to process the data twice.
  1296. */
  1297. if (!zOut.isSeekable() && !doCompress) {
  1298. long size = 0;
  1299. CRC32 cal = new CRC32();
  1300. if (!in.markSupported()) {
  1301. // Store data into a byte[]
  1302. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  1303. byte[] buffer = new byte[8 * 1024];
  1304. int count = 0;
  1305. do {
  1306. size += count;
  1307. cal.update(buffer, 0, count);
  1308. bos.write(buffer, 0, count);
  1309. count = in.read(buffer, 0, buffer.length);
  1310. } while (count != -1);
  1311. in = new ByteArrayInputStream(bos.toByteArray());
  1312. } else {
  1313. in.mark(Integer.MAX_VALUE);
  1314. byte[] buffer = new byte[8 * 1024];
  1315. int count = 0;
  1316. do {
  1317. size += count;
  1318. cal.update(buffer, 0, count);
  1319. count = in.read(buffer, 0, buffer.length);
  1320. } while (count != -1);
  1321. in.reset();
  1322. }
  1323. ze.setSize(size);
  1324. ze.setCrc(cal.getValue());
  1325. }
  1326. ze.setUnixMode(mode);
  1327. zOut.putNextEntry(ze);
  1328. byte[] buffer = new byte[8 * 1024];
  1329. int count = 0;
  1330. do {
  1331. if (count != 0) {
  1332. zOut.write(buffer, 0, count);
  1333. }
  1334. count = in.read(buffer, 0, buffer.length);
  1335. } while (count != -1);
  1336. }
  1337. addedFiles.addElement(vPath);
  1338. }
  1339. /**
  1340. * Method that gets called when adding from <code>java.io.File</code> instances.
  1341. *
  1342. * <p>This implementation delegates to the six-arg version.</p>
  1343. *
  1344. * @param file the file to add to the archive
  1345. * @param zOut the stream to write to
  1346. * @param vPath the name this entry shall have in the archive
  1347. * @param mode the Unix permissions to set.
  1348. * @throws IOException on error
  1349. *
  1350. * @since Ant 1.5.2
  1351. */
  1352. protected void zipFile(File file, ZipOutputStream zOut, String vPath,
  1353. int mode)
  1354. throws IOException {
  1355. if (file.equals(zipFile)) {
  1356. throw new BuildException("A zip file cannot include itself",
  1357. getLocation());
  1358. }
  1359. FileInputStream fIn = new FileInputStream(file);
  1360. try {
  1361. // ZIPs store time with a granularity of 2 seconds, round up
  1362. zipFile(fIn, zOut, vPath,
  1363. file.lastModified() + (roundUp ? 1999 : 0),
  1364. null, mode);
  1365. } finally {
  1366. fIn.close();
  1367. }
  1368. }
  1369. /**
  1370. * Ensure all parent dirs of a given entry have been added.
  1371. * @param baseDir the base directory to use (may be null)
  1372. * @param entry the entry name to create directories from
  1373. * @param zOut the stream to write to
  1374. * @param prefix a prefix to place on the created entries
  1375. * @param dirMode the directory mode
  1376. * @throws IOException on error
  1377. * @since Ant 1.5.2
  1378. */
  1379. protected final void addParentDirs(File baseDir, String entry,
  1380. ZipOutputStream zOut, String prefix,
  1381. int dirMode)
  1382. throws IOException {
  1383. if (!doFilesonly) {
  1384. Stack directories = new Stack();
  1385. int slashPos = entry.length();
  1386. while ((slashPos = entry.lastIndexOf('/', slashPos - 1)) != -1) {
  1387. String dir = entry.substring(0, slashPos + 1);
  1388. if (addedDirs.get(prefix + dir) != null) {
  1389. break;
  1390. }
  1391. directories.push(dir);
  1392. }
  1393. while (!directories.isEmpty()) {
  1394. String dir = (String) directories.pop();
  1395. File f = null;
  1396. if (baseDir != null) {
  1397. f = new File(baseDir, dir);
  1398. } else {
  1399. f = new File(dir);
  1400. }
  1401. zipDir(f, zOut, prefix + dir, dirMode);
  1402. }
  1403. }
  1404. }
  1405. /**
  1406. * Do any clean up necessary to allow this instance to be used again.
  1407. *
  1408. * <p>When we get here, the Zip file has been closed and all we
  1409. * need to do is to reset some globals.</p>
  1410. *
  1411. * <p>This method will only reset globals that have been changed
  1412. * during execute(), it will not alter the attributes or nested
  1413. * child elements. If you want to reset the instance so that you
  1414. * can later zip a completely different set of files, you must use
  1415. * the reset method.</p>
  1416. *
  1417. * @see #reset
  1418. */
  1419. protected void cleanUp() {
  1420. addedDirs.clear();
  1421. addedFiles.removeAllElements();
  1422. entries.clear();
  1423. addingNewFiles = false;
  1424. doUpdate = savedDoUpdate;
  1425. Enumeration e = filesetsFromGroupfilesets.elements();
  1426. while (e.hasMoreElements()) {
  1427. ZipFileSet zf = (ZipFileSet) e.nextElement();
  1428. resources.removeElement(zf);
  1429. }
  1430. filesetsFromGroupfilesets.removeAllElements();
  1431. }
  1432. /**
  1433. * Makes this instance reset all attributes to their default
  1434. * values and forget all children.
  1435. *
  1436. * @since Ant 1.5
  1437. *
  1438. * @see #cleanUp
  1439. */
  1440. public void reset() {
  1441. resources.removeAllElements();
  1442. zipFile = null;
  1443. baseDir = null;
  1444. groupfilesets.removeAllElements();
  1445. duplicate = "add";
  1446. archiveType = "zip";
  1447. doCompress = true;
  1448. emptyBehavior = "skip";
  1449. doUpdate = false;
  1450. doFilesonly = false;
  1451. encoding = null;
  1452. }
  1453. /**
  1454. * Check is the resource arrays are empty.
  1455. * @param r the arrays to check
  1456. * @return true if all individual arrays are empty
  1457. *
  1458. * @since Ant 1.5.2
  1459. */
  1460. protected static final boolean isEmpty(Resource[][] r) {
  1461. for (int i = 0; i < r.length; i++) {
  1462. if (r[i].length > 0) {
  1463. return false;
  1464. }
  1465. }
  1466. return true;
  1467. }
  1468. /**
  1469. * Drops all non-file resources from the given array.
  1470. * @param orig the resources to filter
  1471. * @return the filters resources
  1472. * @since Ant 1.6
  1473. */
  1474. protected Resource[] selectFileResources(Resource[] orig) {
  1475. if (orig.length == 0) {
  1476. return orig;
  1477. }
  1478. Vector v = new Vector(orig.length);
  1479. for (int i = 0; i < orig.length; i++) {
  1480. if (!orig[i].isDirectory()) {
  1481. v.addElement(orig[i]);
  1482. } else {
  1483. log("Ignoring directory " + orig[i].getName()
  1484. + " as only files will be added.", Project.MSG_VERBOSE);
  1485. }
  1486. }
  1487. if (v.size() != orig.length) {
  1488. Resource[] r = new Resource[v.size()];
  1489. v.copyInto(r);
  1490. return r;
  1491. }
  1492. return orig;
  1493. }
  1494. /**
  1495. * Possible behaviors when a duplicate file is added:
  1496. * "add", "preserve" or "fail"
  1497. */
  1498. public static class Duplicate extends EnumeratedAttribute {
  1499. /**
  1500. * @see EnumeratedAttribute#getValues()
  1501. */
  1502. public String[] getValues() {
  1503. return new String[] {"add", "preserve", "fail"};
  1504. }
  1505. }
  1506. /**
  1507. * Holds the up-to-date status and the out-of-date resources of
  1508. * the original archive.
  1509. *
  1510. * @since Ant 1.5.3
  1511. */
  1512. public static class ArchiveState {
  1513. private boolean outOfDate;
  1514. private Resource[][] resourcesToAdd;
  1515. ArchiveState(boolean state, Resource[][] r) {
  1516. outOfDate = state;
  1517. resourcesToAdd = r;
  1518. }
  1519. /**
  1520. * Return the outofdate status.
  1521. * @return the outofdate status
  1522. */
  1523. public boolean isOutOfDate() {
  1524. return outOfDate;
  1525. }
  1526. /**
  1527. * Get the resources to add.
  1528. * @return the resources to add
  1529. */
  1530. public Resource[][] getResourcesToAdd() {
  1531. return resourcesToAdd;
  1532. }
  1533. /**
  1534. * find out if there are absolutely no resources to add
  1535. * @since Ant 1.6.3
  1536. * @return true if there are no resources to add
  1537. */
  1538. public boolean isWithoutAnyResources() {
  1539. if (resourcesToAdd == null) {
  1540. return true;
  1541. }
  1542. for (int counter = 0; counter < resourcesToAdd.length; counter++) {
  1543. if (resourcesToAdd[counter] != null) {
  1544. if (resourcesToAdd[counter].length > 0) {
  1545. return false;
  1546. }
  1547. }
  1548. }
  1549. return true;
  1550. }
  1551. }
  1552. }