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 76 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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158
  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.Arrays;
  29. import java.util.Collections;
  30. import java.util.Comparator;
  31. import java.util.Enumeration;
  32. import java.util.HashMap;
  33. import java.util.Hashtable;
  34. import java.util.Iterator;
  35. import java.util.Map;
  36. import java.util.Stack;
  37. import java.util.Vector;
  38. import java.util.zip.CRC32;
  39. import org.apache.tools.ant.BuildException;
  40. import org.apache.tools.ant.DirectoryScanner;
  41. import org.apache.tools.ant.FileScanner;
  42. import org.apache.tools.ant.Project;
  43. import org.apache.tools.ant.types.ArchiveFileSet;
  44. import org.apache.tools.ant.types.EnumeratedAttribute;
  45. import org.apache.tools.ant.types.FileSet;
  46. import org.apache.tools.ant.types.PatternSet;
  47. import org.apache.tools.ant.types.Resource;
  48. import org.apache.tools.ant.types.ResourceCollection;
  49. import org.apache.tools.ant.types.ZipFileSet;
  50. import org.apache.tools.ant.types.ZipScanner;
  51. import org.apache.tools.ant.types.resources.ArchiveResource;
  52. import org.apache.tools.ant.types.resources.FileProvider;
  53. import org.apache.tools.ant.types.resources.FileResource;
  54. import org.apache.tools.ant.types.resources.Union;
  55. import org.apache.tools.ant.types.resources.ZipResource;
  56. import org.apache.tools.ant.types.resources.selectors.ResourceSelector;
  57. import org.apache.tools.ant.util.FileNameMapper;
  58. import org.apache.tools.ant.util.FileUtils;
  59. import org.apache.tools.ant.util.GlobPatternMapper;
  60. import org.apache.tools.ant.util.IdentityMapper;
  61. import org.apache.tools.ant.util.MergingMapper;
  62. import org.apache.tools.ant.util.ResourceUtils;
  63. import org.apache.tools.zip.UnixStat;
  64. import org.apache.tools.zip.ZipEntry;
  65. import org.apache.tools.zip.ZipExtraField;
  66. import org.apache.tools.zip.ZipFile;
  67. import org.apache.tools.zip.ZipOutputStream;
  68. /**
  69. * Create a Zip file.
  70. *
  71. * @since Ant 1.1
  72. *
  73. * @ant.task category="packaging"
  74. */
  75. public class Zip extends MatchingTask {
  76. private static final int BUFFER_SIZE = 8 * 1024;
  77. private static final int ROUNDUP_MILLIS = 1999; // 2 seconds - 1
  78. // CheckStyle:VisibilityModifier OFF - bc
  79. protected File zipFile;
  80. // use to scan own archive
  81. private ZipScanner zs;
  82. private File baseDir;
  83. protected Hashtable entries = new Hashtable();
  84. private Vector groupfilesets = new Vector();
  85. private Vector filesetsFromGroupfilesets = new Vector();
  86. protected String duplicate = "add";
  87. private boolean doCompress = true;
  88. private boolean doUpdate = false;
  89. // shadow of the above if the value is altered in execute
  90. private boolean savedDoUpdate = false;
  91. private boolean doFilesonly = false;
  92. protected String archiveType = "zip";
  93. // For directories:
  94. private static final long EMPTY_CRC = new CRC32 ().getValue ();
  95. protected String emptyBehavior = "skip";
  96. private Vector resources = new Vector();
  97. protected Hashtable addedDirs = new Hashtable();
  98. private Vector addedFiles = new Vector();
  99. private static final ResourceSelector MISSING_SELECTOR =
  100. new ResourceSelector() {
  101. public boolean isSelected(Resource target) {
  102. return !target.isExists();
  103. }
  104. };
  105. private static final ResourceUtils.ResourceSelectorProvider
  106. MISSING_DIR_PROVIDER = new ResourceUtils.ResourceSelectorProvider() {
  107. public ResourceSelector
  108. getTargetSelectorForSource(Resource sr) {
  109. return MISSING_SELECTOR;
  110. }
  111. };
  112. /**
  113. * If this flag is true, execute() will run most operations twice,
  114. * the first time with {@link #skipWriting skipWriting} set to
  115. * true and the second time with setting it to false.
  116. *
  117. * <p>The only situation in Ant's current code base where this is
  118. * ever going to be true is if the jar task has been configured
  119. * with a filesetmanifest other than "skip".</p>
  120. */
  121. protected boolean doubleFilePass = false;
  122. /**
  123. * whether the methods should just perform some sort of dry-run.
  124. *
  125. * <p>Will only ever be true in the first pass if the task
  126. * performs two passes because {@link #doubleFilePass
  127. * doubleFilePass} is true.</p>
  128. */
  129. protected boolean skipWriting = false;
  130. /**
  131. * Whether this is the first time the archive building methods are invoked.
  132. *
  133. * @return true if either {@link #doubleFilePass doubleFilePass}
  134. * is false or {@link #skipWriting skipWriting} is true.
  135. *
  136. * @since Ant 1.8.0
  137. */
  138. protected final boolean isFirstPass() {
  139. return !doubleFilePass || skipWriting;
  140. }
  141. private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
  142. // CheckStyle:VisibilityModifier ON
  143. // This boolean is set if the task detects that the
  144. // target is outofdate and has written to the target file.
  145. private boolean updatedFile = false;
  146. /**
  147. * true when we are adding new files into the Zip file, as opposed
  148. * to adding back the unchanged files
  149. */
  150. private boolean addingNewFiles = false;
  151. /**
  152. * Encoding to use for filenames, defaults to the platform's
  153. * default encoding.
  154. */
  155. private String encoding;
  156. /**
  157. * Whether the original compression of entries coming from a ZIP
  158. * archive should be kept (for example when updating an archive).
  159. *
  160. * @since Ant 1.6
  161. */
  162. private boolean keepCompression = false;
  163. /**
  164. * Whether the file modification times will be rounded up to the
  165. * next even number of seconds.
  166. *
  167. * @since Ant 1.6.2
  168. */
  169. private boolean roundUp = true;
  170. /**
  171. * Comment for the archive.
  172. * @since Ant 1.6.3
  173. */
  174. private String comment = "";
  175. private int level = ZipOutputStream.DEFAULT_COMPRESSION;
  176. /**
  177. * Assume 0 Unix mode is intentional.
  178. * @since Ant 1.8.0
  179. */
  180. private boolean preserve0Permissions = false;
  181. /**
  182. * Whether to set the language encoding flag when creating the archive.
  183. *
  184. * @since Ant 1.8.0
  185. */
  186. private boolean useLanguageEncodingFlag = true;
  187. /**
  188. * Whether to add unicode extra fields.
  189. *
  190. * @since Ant 1.8.0
  191. */
  192. private UnicodeExtraField createUnicodeExtraFields =
  193. UnicodeExtraField.NEVER;
  194. /**
  195. * Whether to fall back to UTF-8 if a name cannot be enoded using
  196. * the specified encoding.
  197. *
  198. * @since Ant 1.8.0
  199. */
  200. private boolean fallBackToUTF8 = false;
  201. /**
  202. * This is the name/location of where to
  203. * create the .zip file.
  204. * @param zipFile the path of the zipFile
  205. * @deprecated since 1.5.x.
  206. * Use setDestFile(File) instead.
  207. * @ant.attribute ignore="true"
  208. */
  209. public void setZipfile(File zipFile) {
  210. setDestFile(zipFile);
  211. }
  212. /**
  213. * This is the name/location of where to
  214. * create the file.
  215. * @param file the path of the zipFile
  216. * @since Ant 1.5
  217. * @deprecated since 1.5.x.
  218. * Use setDestFile(File) instead.
  219. * @ant.attribute ignore="true"
  220. */
  221. public void setFile(File file) {
  222. setDestFile(file);
  223. }
  224. /**
  225. * The file to create; required.
  226. * @since Ant 1.5
  227. * @param destFile The new destination File
  228. */
  229. public void setDestFile(File destFile) {
  230. this.zipFile = destFile;
  231. }
  232. /**
  233. * The file to create.
  234. * @return the destination file
  235. * @since Ant 1.5.2
  236. */
  237. public File getDestFile() {
  238. return zipFile;
  239. }
  240. /**
  241. * Directory from which to archive files; optional.
  242. * @param baseDir the base directory
  243. */
  244. public void setBasedir(File baseDir) {
  245. this.baseDir = baseDir;
  246. }
  247. /**
  248. * Whether we want to compress the files or only store them;
  249. * optional, default=true;
  250. * @param c if true, compress the files
  251. */
  252. public void setCompress(boolean c) {
  253. doCompress = c;
  254. }
  255. /**
  256. * Whether we want to compress the files or only store them;
  257. * @return true if the files are to be compressed
  258. * @since Ant 1.5.2
  259. */
  260. public boolean isCompress() {
  261. return doCompress;
  262. }
  263. /**
  264. * If true, emulate Sun's jar utility by not adding parent directories;
  265. * optional, defaults to false.
  266. * @param f if true, emulate sun's jar by not adding parent directories
  267. */
  268. public void setFilesonly(boolean f) {
  269. doFilesonly = f;
  270. }
  271. /**
  272. * If true, updates an existing file, otherwise overwrite
  273. * any existing one; optional defaults to false.
  274. * @param c if true, updates an existing zip file
  275. */
  276. public void setUpdate(boolean c) {
  277. doUpdate = c;
  278. savedDoUpdate = c;
  279. }
  280. /**
  281. * Are we updating an existing archive?
  282. * @return true if updating an existing archive
  283. */
  284. public boolean isInUpdateMode() {
  285. return doUpdate;
  286. }
  287. /**
  288. * Adds a set of files.
  289. * @param set the fileset to add
  290. */
  291. public void addFileset(FileSet set) {
  292. add(set);
  293. }
  294. /**
  295. * Adds a set of files that can be
  296. * read from an archive and be given a prefix/fullpath.
  297. * @param set the zipfileset to add
  298. */
  299. public void addZipfileset(ZipFileSet set) {
  300. add(set);
  301. }
  302. /**
  303. * Add a collection of resources to be archived.
  304. * @param a the resources to archive
  305. * @since Ant 1.7
  306. */
  307. public void add(ResourceCollection a) {
  308. resources.add(a);
  309. }
  310. /**
  311. * Adds a group of zip files.
  312. * @param set the group (a fileset) to add
  313. */
  314. public void addZipGroupFileset(FileSet set) {
  315. groupfilesets.addElement(set);
  316. }
  317. /**
  318. * Sets behavior for when a duplicate file is about to be added -
  319. * one of <code>add</code>, <code>preserve</code> or <code>fail</code>.
  320. * Possible values are: <code>add</code> (keep both
  321. * of the files); <code>preserve</code> (keep the first version
  322. * of the file found); <code>fail</code> halt a problem
  323. * Default for zip tasks is <code>add</code>
  324. * @param df a <code>Duplicate</code> enumerated value
  325. */
  326. public void setDuplicate(Duplicate df) {
  327. duplicate = df.getValue();
  328. }
  329. /**
  330. * Possible behaviors when there are no matching files for the task:
  331. * "fail", "skip", or "create".
  332. */
  333. public static class WhenEmpty extends EnumeratedAttribute {
  334. /**
  335. * The string values for the enumerated value
  336. * @return the values
  337. */
  338. public String[] getValues() {
  339. return new String[] {"fail", "skip", "create"};
  340. }
  341. }
  342. /**
  343. * Sets behavior of the task when no files match.
  344. * Possible values are: <code>fail</code> (throw an exception
  345. * and halt the build); <code>skip</code> (do not create
  346. * any archive, but issue a warning); <code>create</code>
  347. * (make an archive with no entries).
  348. * Default for zip tasks is <code>skip</code>;
  349. * for jar tasks, <code>create</code>.
  350. * @param we a <code>WhenEmpty</code> enumerated value
  351. */
  352. public void setWhenempty(WhenEmpty we) {
  353. emptyBehavior = we.getValue();
  354. }
  355. /**
  356. * Encoding to use for filenames, defaults to the platform's
  357. * default encoding.
  358. *
  359. * <p>For a list of possible values see <a
  360. * 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>
  361. * @param encoding the encoding name
  362. */
  363. public void setEncoding(String encoding) {
  364. this.encoding = encoding;
  365. }
  366. /**
  367. * Encoding to use for filenames.
  368. * @return the name of the encoding to use
  369. * @since Ant 1.5.2
  370. */
  371. public String getEncoding() {
  372. return encoding;
  373. }
  374. /**
  375. * Whether the original compression of entries coming from a ZIP
  376. * archive should be kept (for example when updating an archive).
  377. * Default is false.
  378. * @param keep if true, keep the original compression
  379. * @since Ant 1.6
  380. */
  381. public void setKeepCompression(boolean keep) {
  382. keepCompression = keep;
  383. }
  384. /**
  385. * Comment to use for archive.
  386. *
  387. * @param comment The content of the comment.
  388. * @since Ant 1.6.3
  389. */
  390. public void setComment(String comment) {
  391. this.comment = comment;
  392. }
  393. /**
  394. * Comment of the archive
  395. *
  396. * @return Comment of the archive.
  397. * @since Ant 1.6.3
  398. */
  399. public String getComment() {
  400. return comment;
  401. }
  402. /**
  403. * Set the compression level to use. Default is
  404. * ZipOutputStream.DEFAULT_COMPRESSION.
  405. * @param level compression level.
  406. * @since Ant 1.7
  407. */
  408. public void setLevel(int level) {
  409. this.level = level;
  410. }
  411. /**
  412. * Get the compression level.
  413. * @return compression level.
  414. * @since Ant 1.7
  415. */
  416. public int getLevel() {
  417. return level;
  418. }
  419. /**
  420. * Whether the file modification times will be rounded up to the
  421. * next even number of seconds.
  422. *
  423. * <p>Zip archives store file modification times with a
  424. * granularity of two seconds, so the times will either be rounded
  425. * up or down. If you round down, the archive will always seem
  426. * out-of-date when you rerun the task, so the default is to round
  427. * up. Rounding up may lead to a different type of problems like
  428. * JSPs inside a web archive that seem to be slightly more recent
  429. * than precompiled pages, rendering precompilation useless.</p>
  430. * @param r a <code>boolean</code> value
  431. * @since Ant 1.6.2
  432. */
  433. public void setRoundUp(boolean r) {
  434. roundUp = r;
  435. }
  436. /**
  437. * Assume 0 Unix mode is intentional.
  438. * @since Ant 1.8.0
  439. */
  440. public void setPreserve0Permissions(boolean b) {
  441. preserve0Permissions = b;
  442. }
  443. /**
  444. * Assume 0 Unix mode is intentional.
  445. * @since Ant 1.8.0
  446. */
  447. public boolean getPreserve0Permissions() {
  448. return preserve0Permissions;
  449. }
  450. /**
  451. * Whether to set the language encoding flag.
  452. * @since Ant 1.8.0
  453. */
  454. public void setUseLanguageEncodingFlag(boolean b) {
  455. useLanguageEncodingFlag = b;
  456. }
  457. /**
  458. * Whether the language encoding flag will be used.
  459. * @since Ant 1.8.0
  460. */
  461. public boolean getUseLanguageEnodingFlag() {
  462. return useLanguageEncodingFlag;
  463. }
  464. /**
  465. * Whether Unicode extra fields will be created.
  466. * @since Ant 1.8.0
  467. */
  468. public void setCreateUnicodeExtraFields(UnicodeExtraField b) {
  469. createUnicodeExtraFields = b;
  470. }
  471. /**
  472. * Whether Unicode extra fields will be created.
  473. * @since Ant 1.8.0
  474. */
  475. public UnicodeExtraField getCreateUnicodeExtraFields() {
  476. return createUnicodeExtraFields;
  477. }
  478. /**
  479. * Whether to fall back to UTF-8 if a name cannot be enoded using
  480. * the specified encoding.
  481. *
  482. * <p>Defaults to false.</p>
  483. *
  484. * @since Ant 1.8.0
  485. */
  486. public void setFallBackToUTF8(boolean b) {
  487. fallBackToUTF8 = b;
  488. }
  489. /**
  490. * Whether to fall back to UTF-8 if a name cannot be enoded using
  491. * the specified encoding.
  492. *
  493. * @since Ant 1.8.0
  494. */
  495. public boolean getFallBackToUTF8() {
  496. return fallBackToUTF8;
  497. }
  498. /**
  499. * validate and build
  500. * @throws BuildException on error
  501. */
  502. public void execute() throws BuildException {
  503. if (doubleFilePass) {
  504. skipWriting = true;
  505. executeMain();
  506. skipWriting = false;
  507. executeMain();
  508. } else {
  509. executeMain();
  510. }
  511. }
  512. /**
  513. * Get the value of the updatedFile attribute.
  514. * This should only be called after executeMain has been
  515. * called.
  516. * @return true if executeMain has written to the zip file.
  517. */
  518. protected boolean hasUpdatedFile() {
  519. return updatedFile;
  520. }
  521. /**
  522. * Build the zip file.
  523. * This is called twice if doubleFilePass is true.
  524. * @throws BuildException on error
  525. */
  526. public void executeMain() throws BuildException {
  527. checkAttributesAndElements();
  528. // Renamed version of original file, if it exists
  529. File renamedFile = null;
  530. addingNewFiles = true;
  531. processDoUpdate();
  532. processGroupFilesets();
  533. // collect filesets to pass them to getResourcesToAdd
  534. Vector vfss = new Vector();
  535. if (baseDir != null) {
  536. FileSet fs = (FileSet) getImplicitFileSet().clone();
  537. fs.setDir(baseDir);
  538. vfss.addElement(fs);
  539. }
  540. for (int i = 0; i < resources.size(); i++) {
  541. ResourceCollection rc = (ResourceCollection) resources.elementAt(i);
  542. vfss.addElement(rc);
  543. }
  544. ResourceCollection[] fss = new ResourceCollection[vfss.size()];
  545. vfss.copyInto(fss);
  546. boolean success = false;
  547. try {
  548. // can also handle empty archives
  549. ArchiveState state = getResourcesToAdd(fss, zipFile, false);
  550. // quick exit if the target is up to date
  551. if (!state.isOutOfDate()) {
  552. return;
  553. }
  554. File parent = zipFile.getParentFile();
  555. if (parent != null && !parent.isDirectory() && !parent.mkdirs()) {
  556. throw new BuildException("Failed to create missing parent"
  557. + " directory for " + zipFile);
  558. }
  559. updatedFile = true;
  560. if (!zipFile.exists() && state.isWithoutAnyResources()) {
  561. createEmptyZip(zipFile);
  562. return;
  563. }
  564. Resource[][] addThem = state.getResourcesToAdd();
  565. if (doUpdate) {
  566. renamedFile = renameFile();
  567. }
  568. String action = doUpdate ? "Updating " : "Building ";
  569. if (!skipWriting) {
  570. log(action + archiveType + ": " + zipFile.getAbsolutePath());
  571. }
  572. ZipOutputStream zOut = null;
  573. try {
  574. if (!skipWriting) {
  575. zOut = new ZipOutputStream(zipFile);
  576. zOut.setEncoding(encoding);
  577. zOut.setUseLanguageEncodingFlag(useLanguageEncodingFlag);
  578. zOut.setCreateUnicodeExtraFields(createUnicodeExtraFields.
  579. getPolicy());
  580. zOut.setFallbackToUTF8(fallBackToUTF8);
  581. zOut.setMethod(doCompress
  582. ? ZipOutputStream.DEFLATED : ZipOutputStream.STORED);
  583. zOut.setLevel(level);
  584. }
  585. initZipOutputStream(zOut);
  586. // Add the explicit resource collections to the archive.
  587. for (int i = 0; i < fss.length; i++) {
  588. if (addThem[i].length != 0) {
  589. addResources(fss[i], addThem[i], zOut);
  590. }
  591. }
  592. if (doUpdate) {
  593. addingNewFiles = false;
  594. ZipFileSet oldFiles = new ZipFileSet();
  595. oldFiles.setProject(getProject());
  596. oldFiles.setSrc(renamedFile);
  597. oldFiles.setDefaultexcludes(false);
  598. for (int i = 0; i < addedFiles.size(); i++) {
  599. PatternSet.NameEntry ne = oldFiles.createExclude();
  600. ne.setName((String) addedFiles.elementAt(i));
  601. }
  602. DirectoryScanner ds =
  603. oldFiles.getDirectoryScanner(getProject());
  604. ((ZipScanner) ds).setEncoding(encoding);
  605. String[] f = ds.getIncludedFiles();
  606. Resource[] r = new Resource[f.length];
  607. for (int i = 0; i < f.length; i++) {
  608. r[i] = ds.getResource(f[i]);
  609. }
  610. if (!doFilesonly) {
  611. String[] d = ds.getIncludedDirectories();
  612. Resource[] dr = new Resource[d.length];
  613. for (int i = 0; i < d.length; i++) {
  614. dr[i] = ds.getResource(d[i]);
  615. }
  616. Resource[] tmp = r;
  617. r = new Resource[tmp.length + dr.length];
  618. System.arraycopy(dr, 0, r, 0, dr.length);
  619. System.arraycopy(tmp, 0, r, dr.length, tmp.length);
  620. }
  621. addResources(oldFiles, r, zOut);
  622. }
  623. if (zOut != null) {
  624. zOut.setComment(comment);
  625. }
  626. finalizeZipOutputStream(zOut);
  627. // If we've been successful on an update, delete the
  628. // temporary file
  629. if (doUpdate) {
  630. if (!renamedFile.delete()) {
  631. log ("Warning: unable to delete temporary file "
  632. + renamedFile.getName(), Project.MSG_WARN);
  633. }
  634. }
  635. success = true;
  636. } finally {
  637. // Close the output stream.
  638. closeZout(zOut, success);
  639. }
  640. } catch (IOException ioe) {
  641. String msg = "Problem creating " + archiveType + ": "
  642. + ioe.getMessage();
  643. // delete a bogus ZIP file (but only if it's not the original one)
  644. if ((!doUpdate || renamedFile != null) && !zipFile.delete()) {
  645. msg += " (and the archive is probably corrupt but I could not "
  646. + "delete it)";
  647. }
  648. if (doUpdate && renamedFile != null) {
  649. try {
  650. FILE_UTILS.rename(renamedFile, zipFile);
  651. } catch (IOException e) {
  652. msg += " (and I couldn't rename the temporary file "
  653. + renamedFile.getName() + " back)";
  654. }
  655. }
  656. throw new BuildException(msg, ioe, getLocation());
  657. } finally {
  658. cleanUp();
  659. }
  660. }
  661. /** rename the zip file. */
  662. private File renameFile() {
  663. File renamedFile = FILE_UTILS.createTempFile(
  664. "zip", ".tmp", zipFile.getParentFile(), true, false);
  665. try {
  666. FILE_UTILS.rename(zipFile, renamedFile);
  667. } catch (SecurityException e) {
  668. throw new BuildException(
  669. "Not allowed to rename old file ("
  670. + zipFile.getAbsolutePath()
  671. + ") to temporary file");
  672. } catch (IOException e) {
  673. throw new BuildException(
  674. "Unable to rename old file ("
  675. + zipFile.getAbsolutePath()
  676. + ") to temporary file");
  677. }
  678. return renamedFile;
  679. }
  680. /** Close zout */
  681. private void closeZout(ZipOutputStream zOut, boolean success)
  682. throws IOException {
  683. if (zOut == null) {
  684. return;
  685. }
  686. try {
  687. zOut.close();
  688. } catch (IOException ex) {
  689. // If we're in this finally clause because of an
  690. // exception, we don't really care if there's an
  691. // exception when closing the stream. E.g. if it
  692. // throws "ZIP file must have at least one entry",
  693. // because an exception happened before we added
  694. // any files, then we must swallow this
  695. // exception. Otherwise, the error that's reported
  696. // will be the close() error, which is not the
  697. // real cause of the problem.
  698. if (success) {
  699. throw ex;
  700. }
  701. }
  702. }
  703. /** Check the attributes and elements */
  704. private void checkAttributesAndElements() {
  705. if (baseDir == null && resources.size() == 0
  706. && groupfilesets.size() == 0 && "zip".equals(archiveType)) {
  707. throw new BuildException("basedir attribute must be set, "
  708. + "or at least one "
  709. + "resource collection must be given!");
  710. }
  711. if (zipFile == null) {
  712. throw new BuildException("You must specify the "
  713. + archiveType + " file to create!");
  714. }
  715. if (zipFile.exists() && !zipFile.isFile()) {
  716. throw new BuildException(zipFile + " is not a file.");
  717. }
  718. if (zipFile.exists() && !zipFile.canWrite()) {
  719. throw new BuildException(zipFile + " is read-only.");
  720. }
  721. }
  722. /** Process doupdate */
  723. private void processDoUpdate() {
  724. // Whether or not an actual update is required -
  725. // we don't need to update if the original file doesn't exist
  726. if (doUpdate && !zipFile.exists()) {
  727. doUpdate = false;
  728. logWhenWriting("ignoring update attribute as " + archiveType
  729. + " doesn't exist.", Project.MSG_DEBUG);
  730. }
  731. }
  732. /** Process groupfilesets */
  733. private void processGroupFilesets() {
  734. // Add the files found in groupfileset to fileset
  735. for (int i = 0; i < groupfilesets.size(); i++) {
  736. logWhenWriting("Processing groupfileset ", Project.MSG_VERBOSE);
  737. FileSet fs = (FileSet) groupfilesets.elementAt(i);
  738. FileScanner scanner = fs.getDirectoryScanner(getProject());
  739. String[] files = scanner.getIncludedFiles();
  740. File basedir = scanner.getBasedir();
  741. for (int j = 0; j < files.length; j++) {
  742. logWhenWriting("Adding file " + files[j] + " to fileset",
  743. Project.MSG_VERBOSE);
  744. ZipFileSet zf = new ZipFileSet();
  745. zf.setProject(getProject());
  746. zf.setSrc(new File(basedir, files[j]));
  747. add(zf);
  748. filesetsFromGroupfilesets.addElement(zf);
  749. }
  750. }
  751. }
  752. /**
  753. * Indicates if the task is adding new files into the archive as opposed to
  754. * copying back unchanged files from the backup copy
  755. * @return true if adding new files
  756. */
  757. protected final boolean isAddingNewFiles() {
  758. return addingNewFiles;
  759. }
  760. /**
  761. * Add the given resources.
  762. *
  763. * @param fileset may give additional information like fullpath or
  764. * permissions.
  765. * @param resources the resources to add
  766. * @param zOut the stream to write to
  767. * @throws IOException on error
  768. *
  769. * @since Ant 1.5.2
  770. */
  771. protected final void addResources(FileSet fileset, Resource[] resources,
  772. ZipOutputStream zOut)
  773. throws IOException {
  774. String prefix = "";
  775. String fullpath = "";
  776. int dirMode = ArchiveFileSet.DEFAULT_DIR_MODE;
  777. int fileMode = ArchiveFileSet.DEFAULT_FILE_MODE;
  778. ArchiveFileSet zfs = null;
  779. if (fileset instanceof ArchiveFileSet) {
  780. zfs = (ArchiveFileSet) fileset;
  781. prefix = zfs.getPrefix(getProject());
  782. fullpath = zfs.getFullpath(getProject());
  783. dirMode = zfs.getDirMode(getProject());
  784. fileMode = zfs.getFileMode(getProject());
  785. }
  786. if (prefix.length() > 0 && fullpath.length() > 0) {
  787. throw new BuildException("Both prefix and fullpath attributes must"
  788. + " not be set on the same fileset.");
  789. }
  790. if (resources.length != 1 && fullpath.length() > 0) {
  791. throw new BuildException("fullpath attribute may only be specified"
  792. + " for filesets that specify a single"
  793. + " file.");
  794. }
  795. if (prefix.length() > 0) {
  796. if (!prefix.endsWith("/") && !prefix.endsWith("\\")) {
  797. prefix += "/";
  798. }
  799. addParentDirs(null, prefix, zOut, "", dirMode);
  800. }
  801. ZipFile zf = null;
  802. try {
  803. boolean dealingWithFiles = false;
  804. File base = null;
  805. if (zfs == null || zfs.getSrc(getProject()) == null) {
  806. dealingWithFiles = true;
  807. base = fileset.getDir(getProject());
  808. } else if (zfs instanceof ZipFileSet) {
  809. zf = new ZipFile(zfs.getSrc(getProject()), encoding);
  810. }
  811. for (int i = 0; i < resources.length; i++) {
  812. String name = null;
  813. if (fullpath.length() > 0) {
  814. name = fullpath;
  815. } else {
  816. name = resources[i].getName();
  817. }
  818. name = name.replace(File.separatorChar, '/');
  819. if ("".equals(name)) {
  820. continue;
  821. }
  822. if (resources[i].isDirectory()) {
  823. if (doFilesonly) {
  824. continue;
  825. }
  826. int thisDirMode = zfs != null && zfs.hasDirModeBeenSet()
  827. ? dirMode : getUnixMode(resources[i], zf, dirMode);
  828. addDirectoryResource(resources[i], name, prefix,
  829. base, zOut,
  830. dirMode, thisDirMode);
  831. } else { // !isDirectory
  832. addParentDirs(base, name, zOut, prefix, dirMode);
  833. if (dealingWithFiles) {
  834. File f = FILE_UTILS.resolveFile(base,
  835. resources[i].getName());
  836. zipFile(f, zOut, prefix + name, fileMode);
  837. } else {
  838. int thisFileMode =
  839. zfs != null && zfs.hasFileModeBeenSet()
  840. ? fileMode : getUnixMode(resources[i], zf,
  841. fileMode);
  842. addResource(resources[i], name, prefix,
  843. zOut, thisFileMode, zf,
  844. zfs == null
  845. ? null : zfs.getSrc(getProject()));
  846. }
  847. }
  848. }
  849. } finally {
  850. if (zf != null) {
  851. zf.close();
  852. }
  853. }
  854. }
  855. /**
  856. * Add a directory entry to the archive using a specified
  857. * Unix-mode and the default mode for its parent directories (if
  858. * necessary).
  859. */
  860. private void addDirectoryResource(Resource r, String name, String prefix,
  861. File base, ZipOutputStream zOut,
  862. int defaultDirMode, int thisDirMode)
  863. throws IOException {
  864. if (!name.endsWith("/")) {
  865. name = name + "/";
  866. }
  867. int nextToLastSlash = name.lastIndexOf("/", name.length() - 2);
  868. if (nextToLastSlash != -1) {
  869. addParentDirs(base, name.substring(0, nextToLastSlash + 1),
  870. zOut, prefix, defaultDirMode);
  871. }
  872. zipDir(r, zOut, prefix + name, thisDirMode,
  873. r instanceof ZipResource
  874. ? ((ZipResource) r).getExtraFields() : null);
  875. }
  876. /**
  877. * Determine a Resource's Unix mode or return the given default
  878. * value if not available.
  879. */
  880. private int getUnixMode(Resource r, ZipFile zf, int defaultMode)
  881. throws IOException {
  882. int unixMode = defaultMode;
  883. if (zf != null) {
  884. ZipEntry ze = zf.getEntry(r.getName());
  885. unixMode = ze.getUnixMode();
  886. if ((unixMode == 0 || unixMode == UnixStat.DIR_FLAG)
  887. && !preserve0Permissions) {
  888. unixMode = defaultMode;
  889. }
  890. } else if (r instanceof ArchiveResource) {
  891. unixMode = ((ArchiveResource) r).getMode();
  892. }
  893. return unixMode;
  894. }
  895. /**
  896. * Add a file entry.
  897. */
  898. private void addResource(Resource r, String name, String prefix,
  899. ZipOutputStream zOut, int mode,
  900. ZipFile zf, File fromArchive)
  901. throws IOException {
  902. if (zf != null) {
  903. ZipEntry ze = zf.getEntry(r.getName());
  904. if (ze != null) {
  905. boolean oldCompress = doCompress;
  906. if (keepCompression) {
  907. doCompress = (ze.getMethod() == ZipEntry.DEFLATED);
  908. }
  909. InputStream is = null;
  910. try {
  911. is = zf.getInputStream(ze);
  912. zipFile(is, zOut, prefix + name, ze.getTime(),
  913. fromArchive, mode, ze.getExtraFields());
  914. } finally {
  915. doCompress = oldCompress;
  916. FileUtils.close(is);
  917. }
  918. }
  919. } else {
  920. InputStream is = null;
  921. try {
  922. is = r.getInputStream();
  923. zipFile(is, zOut, prefix + name, r.getLastModified(),
  924. fromArchive, mode, r instanceof ZipResource
  925. ? ((ZipResource) r).getExtraFields() : null);
  926. } finally {
  927. FileUtils.close(is);
  928. }
  929. }
  930. }
  931. /**
  932. * Add the given resources.
  933. *
  934. * @param rc may give additional information like fullpath or
  935. * permissions.
  936. * @param resources the resources to add
  937. * @param zOut the stream to write to
  938. * @throws IOException on error
  939. *
  940. * @since Ant 1.7
  941. */
  942. protected final void addResources(ResourceCollection rc,
  943. Resource[] resources,
  944. ZipOutputStream zOut)
  945. throws IOException {
  946. if (rc instanceof FileSet) {
  947. addResources((FileSet) rc, resources, zOut);
  948. return;
  949. }
  950. for (int i = 0; i < resources.length; i++) {
  951. String name = resources[i].getName().replace(File.separatorChar,
  952. '/');
  953. if ("".equals(name)) {
  954. continue;
  955. }
  956. if (resources[i].isDirectory() && doFilesonly) {
  957. continue;
  958. }
  959. File base = null;
  960. FileProvider fp = (FileProvider) resources[i].as(FileProvider.class);
  961. if (fp != null) {
  962. base = ResourceUtils.asFileResource(fp).getBaseDir();
  963. }
  964. if (resources[i].isDirectory()) {
  965. addDirectoryResource(resources[i], name, "", base, zOut,
  966. ArchiveFileSet.DEFAULT_DIR_MODE,
  967. ArchiveFileSet.DEFAULT_DIR_MODE);
  968. } else {
  969. addParentDirs(base, name, zOut, "",
  970. ArchiveFileSet.DEFAULT_DIR_MODE);
  971. if (fp != null) {
  972. File f = (fp).getFile();
  973. zipFile(f, zOut, name, ArchiveFileSet.DEFAULT_FILE_MODE);
  974. } else {
  975. addResource(resources[i], name, "", zOut,
  976. ArchiveFileSet.DEFAULT_FILE_MODE,
  977. null, null);
  978. }
  979. }
  980. }
  981. }
  982. /**
  983. * method for subclasses to override
  984. * @param zOut the zip output stream
  985. * @throws IOException on output error
  986. * @throws BuildException on other errors
  987. */
  988. protected void initZipOutputStream(ZipOutputStream zOut)
  989. throws IOException, BuildException {
  990. }
  991. /**
  992. * method for subclasses to override
  993. * @param zOut the zip output stream
  994. * @throws IOException on output error
  995. * @throws BuildException on other errors
  996. */
  997. protected void finalizeZipOutputStream(ZipOutputStream zOut)
  998. throws IOException, BuildException {
  999. }
  1000. /**
  1001. * Create an empty zip file
  1002. * @param zipFile the zip file
  1003. * @return true for historic reasons
  1004. * @throws BuildException on error
  1005. */
  1006. protected boolean createEmptyZip(File zipFile) throws BuildException {
  1007. // In this case using java.util.zip will not work
  1008. // because it does not permit a zero-entry archive.
  1009. // Must create it manually.
  1010. if (!skipWriting) {
  1011. log("Note: creating empty " + archiveType + " archive " + zipFile,
  1012. Project.MSG_INFO);
  1013. }
  1014. OutputStream os = null;
  1015. try {
  1016. os = new FileOutputStream(zipFile);
  1017. // CheckStyle:MagicNumber OFF
  1018. // Cf. PKZIP specification.
  1019. byte[] empty = new byte[22];
  1020. empty[0] = 80; // P
  1021. empty[1] = 75; // K
  1022. empty[2] = 5;
  1023. empty[3] = 6;
  1024. // remainder zeros
  1025. // CheckStyle:MagicNumber ON
  1026. os.write(empty);
  1027. } catch (IOException ioe) {
  1028. throw new BuildException("Could not create empty ZIP archive "
  1029. + "(" + ioe.getMessage() + ")", ioe,
  1030. getLocation());
  1031. } finally {
  1032. FileUtils.close(os);
  1033. }
  1034. return true;
  1035. }
  1036. /**
  1037. * @since Ant 1.5.2
  1038. */
  1039. private synchronized ZipScanner getZipScanner() {
  1040. if (zs == null) {
  1041. zs = new ZipScanner();
  1042. zs.setEncoding(encoding);
  1043. zs.setSrc(zipFile);
  1044. }
  1045. return zs;
  1046. }
  1047. /**
  1048. * Collect the resources that are newer than the corresponding
  1049. * entries (or missing) in the original archive.
  1050. *
  1051. * <p>If we are going to recreate the archive instead of updating
  1052. * it, all resources should be considered as new, if a single one
  1053. * is. Because of this, subclasses overriding this method must
  1054. * call <code>super.getResourcesToAdd</code> and indicate with the
  1055. * third arg if they already know that the archive is
  1056. * out-of-date.</p>
  1057. *
  1058. * <p>This method first delegates to getNonFileSetResourceToAdd
  1059. * and then invokes the FileSet-arg version. All this to keep
  1060. * backwards compatibility for subclasses that don't know how to
  1061. * deal with non-FileSet ResourceCollections.</p>
  1062. *
  1063. * @param rcs The resource collections to grab resources from
  1064. * @param zipFile intended archive file (may or may not exist)
  1065. * @param needsUpdate whether we already know that the archive is
  1066. * out-of-date. Subclasses overriding this method are supposed to
  1067. * set this value correctly in their call to
  1068. * <code>super.getResourcesToAdd</code>.
  1069. * @return an array of resources to add for each fileset passed in as well
  1070. * as a flag that indicates whether the archive is uptodate.
  1071. *
  1072. * @exception BuildException if it likes
  1073. * @since Ant 1.7
  1074. */
  1075. protected ArchiveState getResourcesToAdd(ResourceCollection[] rcs,
  1076. File zipFile,
  1077. boolean needsUpdate)
  1078. throws BuildException {
  1079. ArrayList filesets = new ArrayList();
  1080. ArrayList rest = new ArrayList();
  1081. for (int i = 0; i < rcs.length; i++) {
  1082. if (rcs[i] instanceof FileSet) {
  1083. filesets.add(rcs[i]);
  1084. } else {
  1085. rest.add(rcs[i]);
  1086. }
  1087. }
  1088. ResourceCollection[] rc = (ResourceCollection[])
  1089. rest.toArray(new ResourceCollection[rest.size()]);
  1090. ArchiveState as = getNonFileSetResourcesToAdd(rc, zipFile,
  1091. needsUpdate);
  1092. FileSet[] fs = (FileSet[]) filesets.toArray(new FileSet[filesets
  1093. .size()]);
  1094. ArchiveState as2 = getResourcesToAdd(fs, zipFile, as.isOutOfDate());
  1095. if (!as.isOutOfDate() && as2.isOutOfDate()) {
  1096. /*
  1097. * Bad luck.
  1098. *
  1099. * There are resources in the filesets that make the
  1100. * archive out of date, but not in the non-fileset
  1101. * resources. We need to rescan the non-FileSets to grab
  1102. * all of them now.
  1103. */
  1104. as = getNonFileSetResourcesToAdd(rc, zipFile, true);
  1105. }
  1106. Resource[][] toAdd = new Resource[rcs.length][];
  1107. int fsIndex = 0;
  1108. int restIndex = 0;
  1109. for (int i = 0; i < rcs.length; i++) {
  1110. if (rcs[i] instanceof FileSet) {
  1111. toAdd[i] = as2.getResourcesToAdd()[fsIndex++];
  1112. } else {
  1113. toAdd[i] = as.getResourcesToAdd()[restIndex++];
  1114. }
  1115. }
  1116. return new ArchiveState(as2.isOutOfDate(), toAdd);
  1117. }
  1118. /**
  1119. * Collect the resources that are newer than the corresponding
  1120. * entries (or missing) in the original archive.
  1121. *
  1122. * <p>If we are going to recreate the archive instead of updating
  1123. * it, all resources should be considered as new, if a single one
  1124. * is. Because of this, subclasses overriding this method must
  1125. * call <code>super.getResourcesToAdd</code> and indicate with the
  1126. * third arg if they already know that the archive is
  1127. * out-of-date.</p>
  1128. *
  1129. * @param filesets The filesets to grab resources from
  1130. * @param zipFile intended archive file (may or may not exist)
  1131. * @param needsUpdate whether we already know that the archive is
  1132. * out-of-date. Subclasses overriding this method are supposed to
  1133. * set this value correctly in their call to
  1134. * <code>super.getResourcesToAdd</code>.
  1135. * @return an array of resources to add for each fileset passed in as well
  1136. * as a flag that indicates whether the archive is uptodate.
  1137. *
  1138. * @exception BuildException if it likes
  1139. */
  1140. protected ArchiveState getResourcesToAdd(FileSet[] filesets,
  1141. File zipFile,
  1142. boolean needsUpdate)
  1143. throws BuildException {
  1144. Resource[][] initialResources = grabResources(filesets);
  1145. if (isEmpty(initialResources)) {
  1146. if (needsUpdate && doUpdate) {
  1147. /*
  1148. * This is a rather hairy case.
  1149. *
  1150. * One of our subclasses knows that we need to update the
  1151. * archive, but at the same time, there are no resources
  1152. * known to us that would need to be added. Only the
  1153. * subclass seems to know what's going on.
  1154. *
  1155. * This happens if <jar> detects that the manifest has changed,
  1156. * for example. The manifest is not part of any resources
  1157. * because of our support for inline <manifest>s.
  1158. *
  1159. * If we invoke createEmptyZip like Ant 1.5.2 did,
  1160. * we'll loose all stuff that has been in the original
  1161. * archive (bugzilla report 17780).
  1162. */
  1163. return new ArchiveState(true, initialResources);
  1164. }
  1165. if (emptyBehavior.equals("skip")) {
  1166. if (doUpdate) {
  1167. logWhenWriting(archiveType + " archive " + zipFile
  1168. + " not updated because no new files were"
  1169. + " included.", Project.MSG_VERBOSE);
  1170. } else {
  1171. logWhenWriting("Warning: skipping " + archiveType
  1172. + " archive " + zipFile
  1173. + " because no files were included.",
  1174. Project.MSG_WARN);
  1175. }
  1176. } else if (emptyBehavior.equals("fail")) {
  1177. throw new BuildException("Cannot create " + archiveType
  1178. + " archive " + zipFile
  1179. + ": no files were included.",
  1180. getLocation());
  1181. } else {
  1182. // Create.
  1183. if (!zipFile.exists()) {
  1184. needsUpdate = true;
  1185. }
  1186. }
  1187. return new ArchiveState(needsUpdate, initialResources);
  1188. }
  1189. // initialResources is not empty
  1190. if (!zipFile.exists()) {
  1191. return new ArchiveState(true, initialResources);
  1192. }
  1193. if (needsUpdate && !doUpdate) {
  1194. // we are recreating the archive, need all resources
  1195. return new ArchiveState(true, initialResources);
  1196. }
  1197. Resource[][] newerResources = new Resource[filesets.length][];
  1198. for (int i = 0; i < filesets.length; i++) {
  1199. if (!(fileset instanceof ZipFileSet)
  1200. || ((ZipFileSet) fileset).getSrc(getProject()) == null) {
  1201. File base = filesets[i].getDir(getProject());
  1202. for (int j = 0; j < initialResources[i].length; j++) {
  1203. File resourceAsFile =
  1204. FILE_UTILS.resolveFile(base,
  1205. initialResources[i][j].getName());
  1206. if (resourceAsFile.equals(zipFile)) {
  1207. throw new BuildException("A zip file cannot include "
  1208. + "itself", getLocation());
  1209. }
  1210. }
  1211. }
  1212. }
  1213. for (int i = 0; i < filesets.length; i++) {
  1214. if (initialResources[i].length == 0) {
  1215. newerResources[i] = new Resource[] {};
  1216. continue;
  1217. }
  1218. FileNameMapper myMapper = new IdentityMapper();
  1219. if (filesets[i] instanceof ZipFileSet) {
  1220. ZipFileSet zfs = (ZipFileSet) filesets[i];
  1221. if (zfs.getFullpath(getProject()) != null
  1222. && !zfs.getFullpath(getProject()).equals("")) {
  1223. // in this case all files from origin map to
  1224. // the fullPath attribute of the zipfileset at
  1225. // destination
  1226. MergingMapper fm = new MergingMapper();
  1227. fm.setTo(zfs.getFullpath(getProject()));
  1228. myMapper = fm;
  1229. } else if (zfs.getPrefix(getProject()) != null
  1230. && !zfs.getPrefix(getProject()).equals("")) {
  1231. GlobPatternMapper gm = new GlobPatternMapper();
  1232. gm.setFrom("*");
  1233. String prefix = zfs.getPrefix(getProject());
  1234. if (!prefix.endsWith("/") && !prefix.endsWith("\\")) {
  1235. prefix += "/";
  1236. }
  1237. gm.setTo(prefix + "*");
  1238. myMapper = gm;
  1239. }
  1240. }
  1241. newerResources[i] = selectOutOfDateResources(initialResources[i],
  1242. myMapper);
  1243. needsUpdate = needsUpdate || (newerResources[i].length > 0);
  1244. if (needsUpdate && !doUpdate) {
  1245. // we will return initialResources anyway, no reason
  1246. // to scan further.
  1247. break;
  1248. }
  1249. }
  1250. if (needsUpdate && !doUpdate) {
  1251. // we are recreating the archive, need all resources
  1252. return new ArchiveState(true, initialResources);
  1253. }
  1254. return new ArchiveState(needsUpdate, newerResources);
  1255. }
  1256. /**
  1257. * Collect the resources that are newer than the corresponding
  1258. * entries (or missing) in the original archive.
  1259. *
  1260. * <p>If we are going to recreate the archive instead of updating
  1261. * it, all resources should be considered as new, if a single one
  1262. * is. Because of this, subclasses overriding this method must
  1263. * call <code>super.getResourcesToAdd</code> and indicate with the
  1264. * third arg if they already know that the archive is
  1265. * out-of-date.</p>
  1266. *
  1267. * @param rcs The filesets to grab resources from
  1268. * @param zipFile intended archive file (may or may not exist)
  1269. * @param needsUpdate whether we already know that the archive is
  1270. * out-of-date. Subclasses overriding this method are supposed to
  1271. * set this value correctly in their call to
  1272. * <code>super.getResourcesToAdd</code>.
  1273. * @return an array of resources to add for each fileset passed in as well
  1274. * as a flag that indicates whether the archive is uptodate.
  1275. *
  1276. * @exception BuildException if it likes
  1277. */
  1278. protected ArchiveState getNonFileSetResourcesToAdd(ResourceCollection[] rcs,
  1279. File zipFile,
  1280. boolean needsUpdate)
  1281. throws BuildException {
  1282. /*
  1283. * Backwards compatibility forces us to repeat the logic of
  1284. * getResourcesToAdd(FileSet[], ...) here once again.
  1285. */
  1286. Resource[][] initialResources = grabNonFileSetResources(rcs);
  1287. if (isEmpty(initialResources)) {
  1288. // no emptyBehavior handling since the FileSet version
  1289. // will take care of it.
  1290. return new ArchiveState(needsUpdate, initialResources);
  1291. }
  1292. // initialResources is not empty
  1293. if (!zipFile.exists()) {
  1294. return new ArchiveState(true, initialResources);
  1295. }
  1296. if (needsUpdate && !doUpdate) {
  1297. // we are recreating the archive, need all resources
  1298. return new ArchiveState(true, initialResources);
  1299. }
  1300. Resource[][] newerResources = new Resource[rcs.length][];
  1301. for (int i = 0; i < rcs.length; i++) {
  1302. if (initialResources[i].length == 0) {
  1303. newerResources[i] = new Resource[] {};
  1304. continue;
  1305. }
  1306. for (int j = 0; j < initialResources[i].length; j++) {
  1307. FileProvider fp =
  1308. (FileProvider) initialResources[i][j].as(FileProvider.class);
  1309. if (fp != null && zipFile.equals(fp.getFile())) {
  1310. throw new BuildException("A zip file cannot include "
  1311. + "itself", getLocation());
  1312. }
  1313. }
  1314. newerResources[i] = selectOutOfDateResources(initialResources[i],
  1315. new IdentityMapper());
  1316. needsUpdate = needsUpdate || (newerResources[i].length > 0);
  1317. if (needsUpdate && !doUpdate) {
  1318. // we will return initialResources anyway, no reason
  1319. // to scan further.
  1320. break;
  1321. }
  1322. }
  1323. if (needsUpdate && !doUpdate) {
  1324. // we are recreating the archive, need all resources
  1325. return new ArchiveState(true, initialResources);
  1326. }
  1327. return new ArchiveState(needsUpdate, newerResources);
  1328. }
  1329. private Resource[] selectOutOfDateResources(Resource[] initial,
  1330. FileNameMapper mapper) {
  1331. Resource[] rs = selectFileResources(initial);
  1332. Resource[] result =
  1333. ResourceUtils.selectOutOfDateSources(this, rs, mapper,
  1334. getZipScanner());
  1335. if (!doFilesonly) {
  1336. Union u = new Union();
  1337. u.addAll(Arrays.asList(selectDirectoryResources(initial)));
  1338. ResourceCollection rc =
  1339. ResourceUtils.selectSources(this, u, mapper,
  1340. getZipScanner(),
  1341. MISSING_DIR_PROVIDER);
  1342. if (rc.size() > 0) {
  1343. ArrayList newer = new ArrayList();
  1344. newer.addAll(Arrays.asList(((Union) rc).listResources()));
  1345. newer.addAll(Arrays.asList(result));
  1346. result = (Resource[]) newer.toArray(result);
  1347. }
  1348. }
  1349. return result;
  1350. }
  1351. /**
  1352. * Fetch all included and not excluded resources from the sets.
  1353. *
  1354. * <p>Included directories will precede included files.</p>
  1355. * @param filesets an array of filesets
  1356. * @return the resources included
  1357. * @since Ant 1.5.2
  1358. */
  1359. protected Resource[][] grabResources(FileSet[] filesets) {
  1360. Resource[][] result = new Resource[filesets.length][];
  1361. for (int i = 0; i < filesets.length; i++) {
  1362. boolean skipEmptyNames = true;
  1363. if (filesets[i] instanceof ZipFileSet) {
  1364. ZipFileSet zfs = (ZipFileSet) filesets[i];
  1365. skipEmptyNames = zfs.getPrefix(getProject()).equals("")
  1366. && zfs.getFullpath(getProject()).equals("");
  1367. }
  1368. DirectoryScanner rs =
  1369. filesets[i].getDirectoryScanner(getProject());
  1370. if (rs instanceof ZipScanner) {
  1371. ((ZipScanner) rs).setEncoding(encoding);
  1372. }
  1373. Vector resources = new Vector();
  1374. if (!doFilesonly) {
  1375. String[] directories = rs.getIncludedDirectories();
  1376. for (int j = 0; j < directories.length; j++) {
  1377. if (!"".equals(directories[j]) || !skipEmptyNames) {
  1378. resources.addElement(rs.getResource(directories[j]));
  1379. }
  1380. }
  1381. }
  1382. String[] files = rs.getIncludedFiles();
  1383. for (int j = 0; j < files.length; j++) {
  1384. if (!"".equals(files[j]) || !skipEmptyNames) {
  1385. resources.addElement(rs.getResource(files[j]));
  1386. }
  1387. }
  1388. result[i] = new Resource[resources.size()];
  1389. resources.copyInto(result[i]);
  1390. }
  1391. return result;
  1392. }
  1393. /**
  1394. * Fetch all included and not excluded resources from the collections.
  1395. *
  1396. * <p>Included directories will precede included files.</p>
  1397. * @param rcs an array of resource collections
  1398. * @return the resources included
  1399. * @since Ant 1.7
  1400. */
  1401. protected Resource[][] grabNonFileSetResources(ResourceCollection[] rcs) {
  1402. Resource[][] result = new Resource[rcs.length][];
  1403. for (int i = 0; i < rcs.length; i++) {
  1404. Iterator iter = rcs[i].iterator();
  1405. ArrayList dirs = new ArrayList();
  1406. ArrayList files = new ArrayList();
  1407. while (iter.hasNext()) {
  1408. Resource r = (Resource) iter.next();
  1409. if (r.isExists()) {
  1410. if (r.isDirectory()) {
  1411. dirs.add(r);
  1412. } else {
  1413. files.add(r);
  1414. }
  1415. }
  1416. }
  1417. // make sure directories are in alpha-order - this also
  1418. // ensures parents come before their children
  1419. Collections.sort(dirs, new Comparator() {
  1420. public int compare(Object o1, Object o2) {
  1421. Resource r1 = (Resource) o1;
  1422. Resource r2 = (Resource) o2;
  1423. return r1.getName().compareTo(r2.getName());
  1424. }
  1425. });
  1426. ArrayList rs = new ArrayList(dirs);
  1427. rs.addAll(files);
  1428. result[i] = (Resource[]) rs.toArray(new Resource[rs.size()]);
  1429. }
  1430. return result;
  1431. }
  1432. /**
  1433. * Add a directory to the zip stream.
  1434. * @param dir the directort to add to the archive
  1435. * @param zOut the stream to write to
  1436. * @param vPath the name this entry shall have in the archive
  1437. * @param mode the Unix permissions to set.
  1438. * @throws IOException on error
  1439. * @since Ant 1.5.2
  1440. */
  1441. protected void zipDir(File dir, ZipOutputStream zOut, String vPath,
  1442. int mode)
  1443. throws IOException {
  1444. zipDir(dir, zOut, vPath, mode, null);
  1445. }
  1446. /**
  1447. * Add a directory to the zip stream.
  1448. * @param dir the directory to add to the archive
  1449. * @param zOut the stream to write to
  1450. * @param vPath the name this entry shall have in the archive
  1451. * @param mode the Unix permissions to set.
  1452. * @param extra ZipExtraFields to add
  1453. * @throws IOException on error
  1454. * @since Ant 1.6.3
  1455. */
  1456. protected void zipDir(File dir, ZipOutputStream zOut, String vPath,
  1457. int mode, ZipExtraField[] extra)
  1458. throws IOException {
  1459. zipDir(dir == null ? (Resource) null : new FileResource(dir),
  1460. zOut, vPath, mode, extra);
  1461. }
  1462. /**
  1463. * Add a directory to the zip stream.
  1464. * @param dir the directory to add to the archive
  1465. * @param zOut the stream to write to
  1466. * @param vPath the name this entry shall have in the archive
  1467. * @param mode the Unix permissions to set.
  1468. * @param extra ZipExtraFields to add
  1469. * @throws IOException on error
  1470. * @since Ant 1.8.0
  1471. */
  1472. protected void zipDir(Resource dir, ZipOutputStream zOut, String vPath,
  1473. int mode, ZipExtraField[] extra)
  1474. throws IOException {
  1475. if (doFilesonly) {
  1476. logWhenWriting("skipping directory " + vPath
  1477. + " for file-only archive",
  1478. Project.MSG_VERBOSE);
  1479. return;
  1480. }
  1481. if (addedDirs.get(vPath) != null) {
  1482. // don't add directories we've already added.
  1483. // no warning if we try, it is harmless in and of itself
  1484. return;
  1485. }
  1486. logWhenWriting("adding directory " + vPath, Project.MSG_VERBOSE);
  1487. addedDirs.put(vPath, vPath);
  1488. if (!skipWriting) {
  1489. ZipEntry ze = new ZipEntry (vPath);
  1490. // ZIPs store time with a granularity of 2 seconds, round up
  1491. int millisToAdd = roundUp ? ROUNDUP_MILLIS : 0;
  1492. if (dir != null && dir.isExists()) {
  1493. ze.setTime(dir.getLastModified() + millisToAdd);
  1494. } else {
  1495. ze.setTime(System.currentTimeMillis() + millisToAdd);
  1496. }
  1497. ze.setSize (0);
  1498. ze.setMethod (ZipEntry.STORED);
  1499. // This is faintly ridiculous:
  1500. ze.setCrc (EMPTY_CRC);
  1501. ze.setUnixMode(mode);
  1502. if (extra != null) {
  1503. ze.setExtraFields(extra);
  1504. }
  1505. zOut.putNextEntry(ze);
  1506. }
  1507. }
  1508. /*
  1509. * This is a hacky construct to extend the zipFile method to
  1510. * support a new parameter (extra fields to preserve) without
  1511. * breaking subclasses that override the old method signature.
  1512. */
  1513. private static ThreadLocal currentZipExtra = new ThreadLocal() {
  1514. protected Object initialValue() {
  1515. return null;
  1516. }
  1517. };
  1518. /**
  1519. * Provides the extra fields for the zip entry currently being
  1520. * added to the archive - if any.
  1521. * @since Ant 1.8.0
  1522. */
  1523. protected final ZipExtraField[] getCurrentExtraFields() {
  1524. return (ZipExtraField[]) currentZipExtra.get();
  1525. }
  1526. /**
  1527. * Sets the extra fields for the zip entry currently being
  1528. * added to the archive - if any.
  1529. * @since Ant 1.8.0
  1530. */
  1531. protected final void setCurrentExtraFields(ZipExtraField[] extra) {
  1532. currentZipExtra.set(extra);
  1533. }
  1534. /**
  1535. * Adds a new entry to the archive, takes care of duplicates as well.
  1536. *
  1537. * @param in the stream to read data for the entry from. The
  1538. * caller of the method is responsible for closing the stream.
  1539. * @param zOut the stream to write to.
  1540. * @param vPath the name this entry shall have in the archive.
  1541. * @param lastModified last modification time for the entry.
  1542. * @param fromArchive the original archive we are copying this
  1543. * entry from, will be null if we are not copying from an archive.
  1544. * @param mode the Unix permissions to set.
  1545. *
  1546. * @since Ant 1.5.2
  1547. * @throws IOException on error
  1548. */
  1549. protected void zipFile(InputStream in, ZipOutputStream zOut, String vPath,
  1550. long lastModified, File fromArchive, int mode)
  1551. throws IOException {
  1552. // fromArchive is used in subclasses overriding this method
  1553. if (entries.contains(vPath)) {
  1554. if (duplicate.equals("preserve")) {
  1555. logWhenWriting(vPath + " already added, skipping",
  1556. Project.MSG_INFO);
  1557. return;
  1558. } else if (duplicate.equals("fail")) {
  1559. throw new BuildException("Duplicate file " + vPath
  1560. + " was found and the duplicate "
  1561. + "attribute is 'fail'.");
  1562. } else {
  1563. // duplicate equal to add, so we continue
  1564. logWhenWriting("duplicate file " + vPath
  1565. + " found, adding.", Project.MSG_VERBOSE);
  1566. }
  1567. } else {
  1568. logWhenWriting("adding entry " + vPath, Project.MSG_VERBOSE);
  1569. }
  1570. entries.put(vPath, vPath);
  1571. if (!skipWriting) {
  1572. ZipEntry ze = new ZipEntry(vPath);
  1573. ze.setTime(lastModified);
  1574. ze.setMethod(doCompress ? ZipEntry.DEFLATED : ZipEntry.STORED);
  1575. /*
  1576. * ZipOutputStream.putNextEntry expects the ZipEntry to
  1577. * know its size and the CRC sum before you start writing
  1578. * the data when using STORED mode - unless it is seekable.
  1579. *
  1580. * This forces us to process the data twice.
  1581. */
  1582. if (!zOut.isSeekable() && !doCompress) {
  1583. long size = 0;
  1584. CRC32 cal = new CRC32();
  1585. if (!in.markSupported()) {
  1586. // Store data into a byte[]
  1587. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  1588. byte[] buffer = new byte[BUFFER_SIZE];
  1589. int count = 0;
  1590. do {
  1591. size += count;
  1592. cal.update(buffer, 0, count);
  1593. bos.write(buffer, 0, count);
  1594. count = in.read(buffer, 0, buffer.length);
  1595. } while (count != -1);
  1596. in = new ByteArrayInputStream(bos.toByteArray());
  1597. } else {
  1598. in.mark(Integer.MAX_VALUE);
  1599. byte[] buffer = new byte[BUFFER_SIZE];
  1600. int count = 0;
  1601. do {
  1602. size += count;
  1603. cal.update(buffer, 0, count);
  1604. count = in.read(buffer, 0, buffer.length);
  1605. } while (count != -1);
  1606. in.reset();
  1607. }
  1608. ze.setSize(size);
  1609. ze.setCrc(cal.getValue());
  1610. }
  1611. ze.setUnixMode(mode);
  1612. ZipExtraField[] extra = getCurrentExtraFields();
  1613. if (extra != null) {
  1614. ze.setExtraFields(extra);
  1615. }
  1616. zOut.putNextEntry(ze);
  1617. byte[] buffer = new byte[BUFFER_SIZE];
  1618. int count = 0;
  1619. do {
  1620. if (count != 0) {
  1621. zOut.write(buffer, 0, count);
  1622. }
  1623. count = in.read(buffer, 0, buffer.length);
  1624. } while (count != -1);
  1625. }
  1626. addedFiles.addElement(vPath);
  1627. }
  1628. /**
  1629. * Adds a new entry to the archive, takes care of duplicates as well.
  1630. *
  1631. * @param in the stream to read data for the entry from. The
  1632. * caller of the method is responsible for closing the stream.
  1633. * @param zOut the stream to write to.
  1634. * @param vPath the name this entry shall have in the archive.
  1635. * @param lastModified last modification time for the entry.
  1636. * @param fromArchive the original archive we are copying this
  1637. * entry from, will be null if we are not copying from an archive.
  1638. * @param mode the Unix permissions to set.
  1639. * @param extra ZipExtraFields to add
  1640. *
  1641. * @since Ant 1.8.0
  1642. * @throws IOException on error
  1643. */
  1644. protected final void zipFile(InputStream in, ZipOutputStream zOut,
  1645. String vPath, long lastModified,
  1646. File fromArchive, int mode,
  1647. ZipExtraField[] extra)
  1648. throws IOException {
  1649. try {
  1650. setCurrentExtraFields(extra);
  1651. zipFile(in, zOut, vPath, lastModified, fromArchive, mode);
  1652. } finally {
  1653. setCurrentExtraFields(null);
  1654. }
  1655. }
  1656. /**
  1657. * Method that gets called when adding from <code>java.io.File</code> instances.
  1658. *
  1659. * <p>This implementation delegates to the six-arg version.</p>
  1660. *
  1661. * @param file the file to add to the archive
  1662. * @param zOut the stream to write to
  1663. * @param vPath the name this entry shall have in the archive
  1664. * @param mode the Unix permissions to set.
  1665. * @throws IOException on error
  1666. *
  1667. * @since Ant 1.5.2
  1668. */
  1669. protected void zipFile(File file, ZipOutputStream zOut, String vPath,
  1670. int mode)
  1671. throws IOException {
  1672. if (file.equals(zipFile)) {
  1673. throw new BuildException("A zip file cannot include itself",
  1674. getLocation());
  1675. }
  1676. FileInputStream fIn = new FileInputStream(file);
  1677. try {
  1678. // ZIPs store time with a granularity of 2 seconds, round up
  1679. zipFile(fIn, zOut, vPath,
  1680. file.lastModified() + (roundUp ? ROUNDUP_MILLIS : 0),
  1681. null, mode);
  1682. } finally {
  1683. fIn.close();
  1684. }
  1685. }
  1686. /**
  1687. * Ensure all parent dirs of a given entry have been added.
  1688. * @param baseDir the base directory to use (may be null)
  1689. * @param entry the entry name to create directories from
  1690. * @param zOut the stream to write to
  1691. * @param prefix a prefix to place on the created entries
  1692. * @param dirMode the directory mode
  1693. * @throws IOException on error
  1694. * @since Ant 1.5.2
  1695. */
  1696. protected final void addParentDirs(File baseDir, String entry,
  1697. ZipOutputStream zOut, String prefix,
  1698. int dirMode)
  1699. throws IOException {
  1700. if (!doFilesonly) {
  1701. Stack directories = new Stack();
  1702. int slashPos = entry.length();
  1703. while ((slashPos = entry.lastIndexOf('/', slashPos - 1)) != -1) {
  1704. String dir = entry.substring(0, slashPos + 1);
  1705. if (addedDirs.get(prefix + dir) != null) {
  1706. break;
  1707. }
  1708. directories.push(dir);
  1709. }
  1710. while (!directories.isEmpty()) {
  1711. String dir = (String) directories.pop();
  1712. File f = null;
  1713. if (baseDir != null) {
  1714. f = new File(baseDir, dir);
  1715. } else {
  1716. f = new File(dir);
  1717. }
  1718. zipDir(f, zOut, prefix + dir, dirMode);
  1719. }
  1720. }
  1721. }
  1722. /**
  1723. * Do any clean up necessary to allow this instance to be used again.
  1724. *
  1725. * <p>When we get here, the Zip file has been closed and all we
  1726. * need to do is to reset some globals.</p>
  1727. *
  1728. * <p>This method will only reset globals that have been changed
  1729. * during execute(), it will not alter the attributes or nested
  1730. * child elements. If you want to reset the instance so that you
  1731. * can later zip a completely different set of files, you must use
  1732. * the reset method.</p>
  1733. *
  1734. * @see #reset
  1735. */
  1736. protected void cleanUp() {
  1737. addedDirs.clear();
  1738. addedFiles.removeAllElements();
  1739. entries.clear();
  1740. addingNewFiles = false;
  1741. doUpdate = savedDoUpdate;
  1742. Enumeration e = filesetsFromGroupfilesets.elements();
  1743. while (e.hasMoreElements()) {
  1744. ZipFileSet zf = (ZipFileSet) e.nextElement();
  1745. resources.removeElement(zf);
  1746. }
  1747. filesetsFromGroupfilesets.removeAllElements();
  1748. }
  1749. /**
  1750. * Makes this instance reset all attributes to their default
  1751. * values and forget all children.
  1752. *
  1753. * @since Ant 1.5
  1754. *
  1755. * @see #cleanUp
  1756. */
  1757. public void reset() {
  1758. resources.removeAllElements();
  1759. zipFile = null;
  1760. baseDir = null;
  1761. groupfilesets.removeAllElements();
  1762. duplicate = "add";
  1763. archiveType = "zip";
  1764. doCompress = true;
  1765. emptyBehavior = "skip";
  1766. doUpdate = false;
  1767. doFilesonly = false;
  1768. encoding = null;
  1769. }
  1770. /**
  1771. * Check is the resource arrays are empty.
  1772. * @param r the arrays to check
  1773. * @return true if all individual arrays are empty
  1774. *
  1775. * @since Ant 1.5.2
  1776. */
  1777. protected static final boolean isEmpty(Resource[][] r) {
  1778. for (int i = 0; i < r.length; i++) {
  1779. if (r[i].length > 0) {
  1780. return false;
  1781. }
  1782. }
  1783. return true;
  1784. }
  1785. /**
  1786. * Drops all non-file resources from the given array.
  1787. * @param orig the resources to filter
  1788. * @return the filters resources
  1789. * @since Ant 1.6
  1790. */
  1791. protected Resource[] selectFileResources(Resource[] orig) {
  1792. return selectResources(orig,
  1793. new ResourceSelector() {
  1794. public boolean isSelected(Resource r) {
  1795. if (!r.isDirectory()) {
  1796. return true;
  1797. } else if (doFilesonly) {
  1798. logWhenWriting("Ignoring directory "
  1799. + r.getName()
  1800. + " as only files will"
  1801. + " be added.",
  1802. Project.MSG_VERBOSE);
  1803. }
  1804. return false;
  1805. }
  1806. });
  1807. }
  1808. /**
  1809. * Drops all non-directory resources from the given array.
  1810. * @param orig the resources to filter
  1811. * @return the filters resources
  1812. * @since Ant 1.8.0
  1813. */
  1814. protected Resource[] selectDirectoryResources(Resource[] orig) {
  1815. return selectResources(orig,
  1816. new ResourceSelector() {
  1817. public boolean isSelected(Resource r) {
  1818. return r.isDirectory();
  1819. }
  1820. });
  1821. }
  1822. /**
  1823. * Drops all resources from the given array that are not selected
  1824. * @param orig the resources to filter
  1825. * @return the filters resources
  1826. * @since Ant 1.8.0
  1827. */
  1828. protected Resource[] selectResources(Resource[] orig,
  1829. ResourceSelector selector) {
  1830. if (orig.length == 0) {
  1831. return orig;
  1832. }
  1833. ArrayList v = new ArrayList(orig.length);
  1834. for (int i = 0; i < orig.length; i++) {
  1835. if (selector.isSelected(orig[i])) {
  1836. v.add(orig[i]);
  1837. }
  1838. }
  1839. if (v.size() != orig.length) {
  1840. Resource[] r = new Resource[v.size()];
  1841. return (Resource[]) v.toArray(r);
  1842. }
  1843. return orig;
  1844. }
  1845. /**
  1846. * Logs a message at the given output level, but only if this is
  1847. * the pass that will actually create the archive.
  1848. *
  1849. * @since Ant 1.8.0
  1850. */
  1851. protected void logWhenWriting(String msg, int level) {
  1852. if (!skipWriting) {
  1853. log(msg, level);
  1854. }
  1855. }
  1856. /**
  1857. * Possible behaviors when a duplicate file is added:
  1858. * "add", "preserve" or "fail"
  1859. */
  1860. public static class Duplicate extends EnumeratedAttribute {
  1861. /**
  1862. * @see EnumeratedAttribute#getValues()
  1863. */
  1864. /** {@inheritDoc} */
  1865. public String[] getValues() {
  1866. return new String[] {"add", "preserve", "fail"};
  1867. }
  1868. }
  1869. /**
  1870. * Holds the up-to-date status and the out-of-date resources of
  1871. * the original archive.
  1872. *
  1873. * @since Ant 1.5.3
  1874. */
  1875. public static class ArchiveState {
  1876. private boolean outOfDate;
  1877. private Resource[][] resourcesToAdd;
  1878. ArchiveState(boolean state, Resource[][] r) {
  1879. outOfDate = state;
  1880. resourcesToAdd = r;
  1881. }
  1882. /**
  1883. * Return the outofdate status.
  1884. * @return the outofdate status
  1885. */
  1886. public boolean isOutOfDate() {
  1887. return outOfDate;
  1888. }
  1889. /**
  1890. * Get the resources to add.
  1891. * @return the resources to add
  1892. */
  1893. public Resource[][] getResourcesToAdd() {
  1894. return resourcesToAdd;
  1895. }
  1896. /**
  1897. * find out if there are absolutely no resources to add
  1898. * @since Ant 1.6.3
  1899. * @return true if there are no resources to add
  1900. */
  1901. public boolean isWithoutAnyResources() {
  1902. if (resourcesToAdd == null) {
  1903. return true;
  1904. }
  1905. for (int counter = 0; counter < resourcesToAdd.length; counter++) {
  1906. if (resourcesToAdd[counter] != null) {
  1907. if (resourcesToAdd[counter].length > 0) {
  1908. return false;
  1909. }
  1910. }
  1911. }
  1912. return true;
  1913. }
  1914. }
  1915. /**
  1916. * Policiy for creation of Unicode extra fields: never, always or
  1917. * not-encodeable.
  1918. *
  1919. * @since Ant 1.8.0
  1920. */
  1921. public static final class UnicodeExtraField extends EnumeratedAttribute {
  1922. private static final Map POLICIES = new HashMap();
  1923. private static final String NEVER_KEY = "never";
  1924. private static final String ALWAYS_KEY = "always";
  1925. private static final String N_E_KEY = "not-encodeable";
  1926. static {
  1927. POLICIES.put(NEVER_KEY,
  1928. ZipOutputStream.UnicodeExtraFieldPolicy.NEVER);
  1929. POLICIES.put(ALWAYS_KEY,
  1930. ZipOutputStream.UnicodeExtraFieldPolicy.ALWAYS);
  1931. POLICIES.put(N_E_KEY,
  1932. ZipOutputStream.UnicodeExtraFieldPolicy
  1933. .NOT_ENCODEABLE);
  1934. }
  1935. public String[] getValues() {
  1936. return new String[] {NEVER_KEY, ALWAYS_KEY, N_E_KEY};
  1937. }
  1938. public static final UnicodeExtraField NEVER =
  1939. new UnicodeExtraField(NEVER_KEY);
  1940. private UnicodeExtraField(String name) {
  1941. setValue(name);
  1942. }
  1943. public UnicodeExtraField() {
  1944. }
  1945. public ZipOutputStream.UnicodeExtraFieldPolicy getPolicy() {
  1946. return (ZipOutputStream.UnicodeExtraFieldPolicy)
  1947. POLICIES.get(getValue());
  1948. }
  1949. }
  1950. }