-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZip.java
More file actions
2275 lines (2052 loc) · 82.5 KB
/
Zip.java
File metadata and controls
2275 lines (2052 loc) · 82.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.tools.ant.taskdefs;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Stack;
import java.util.Vector;
import java.util.zip.CRC32;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.FileScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.ArchiveFileSet;
import org.apache.tools.ant.types.EnumeratedAttribute;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.PatternSet;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.ResourceCollection;
import org.apache.tools.ant.types.ZipFileSet;
import org.apache.tools.ant.types.ZipScanner;
import org.apache.tools.ant.types.resources.ArchiveResource;
import org.apache.tools.ant.types.resources.FileProvider;
import org.apache.tools.ant.types.resources.FileResource;
import org.apache.tools.ant.types.resources.Union;
import org.apache.tools.ant.types.resources.ZipResource;
import org.apache.tools.ant.types.resources.selectors.ResourceSelector;
import org.apache.tools.ant.util.FileNameMapper;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.ant.util.GlobPatternMapper;
import org.apache.tools.ant.util.IdentityMapper;
import org.apache.tools.ant.util.MergingMapper;
import org.apache.tools.ant.util.ResourceUtils;
import org.apache.tools.zip.UnixStat;
import org.apache.tools.zip.Zip64Mode;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipExtraField;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import org.apache.tools.zip.ZipOutputStream.UnicodeExtraFieldPolicy;
/**
* Create a Zip file.
*
* @since Ant 1.1
*
* @ant.task category="packaging"
*/
public class Zip extends MatchingTask {
private static final int BUFFER_SIZE = 8 * 1024;
/**
* The granularity of timestamps inside a ZIP archive.
*/
private static final int ZIP_FILE_TIMESTAMP_GRANULARITY = 2000;
private static final int ROUNDUP_MILLIS = ZIP_FILE_TIMESTAMP_GRANULARITY - 1;
// CheckStyle:VisibilityModifier OFF - bc
protected File zipFile;
// use to scan own archive
private ZipScanner zs;
private File baseDir;
protected Hashtable<String, String> entries = new Hashtable<String, String>();
private final Vector<FileSet> groupfilesets = new Vector<FileSet>();
private final Vector<ZipFileSet> filesetsFromGroupfilesets = new Vector<ZipFileSet>();
protected String duplicate = "add";
private boolean doCompress = true;
private boolean doUpdate = false;
// shadow of the above if the value is altered in execute
private boolean savedDoUpdate = false;
private boolean doFilesonly = false;
protected String archiveType = "zip";
// For directories:
private static final long EMPTY_CRC = new CRC32 ().getValue ();
protected String emptyBehavior = "skip";
private final Vector<ResourceCollection> resources = new Vector<ResourceCollection>();
protected Hashtable<String, String> addedDirs = new Hashtable<String, String>();
private final Vector<String> addedFiles = new Vector<String>();
private static final ResourceSelector MISSING_SELECTOR =
new ResourceSelector() {
public boolean isSelected(final Resource target) {
return !target.isExists();
}
};
private static final ResourceUtils.ResourceSelectorProvider
MISSING_DIR_PROVIDER = new ResourceUtils.ResourceSelectorProvider() {
public ResourceSelector
getTargetSelectorForSource(final Resource sr) {
return MISSING_SELECTOR;
}
};
/**
* If this flag is true, execute() will run most operations twice,
* the first time with {@link #skipWriting skipWriting} set to
* true and the second time with setting it to false.
*
* <p>The only situation in Ant's current code base where this is
* ever going to be true is if the jar task has been configured
* with a filesetmanifest other than "skip".</p>
*/
protected boolean doubleFilePass = false;
/**
* whether the methods should just perform some sort of dry-run.
*
* <p>Will only ever be true in the first pass if the task
* performs two passes because {@link #doubleFilePass
* doubleFilePass} is true.</p>
*/
protected boolean skipWriting = false;
/**
* Whether this is the first time the archive building methods are invoked.
*
* @return true if either {@link #doubleFilePass doubleFilePass}
* is false or {@link #skipWriting skipWriting} is true.
*
* @since Ant 1.8.0
*/
protected final boolean isFirstPass() {
return !doubleFilePass || skipWriting;
}
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
// CheckStyle:VisibilityModifier ON
// This boolean is set if the task detects that the
// target is outofdate and has written to the target file.
private boolean updatedFile = false;
/**
* true when we are adding new files into the Zip file, as opposed
* to adding back the unchanged files
*/
private boolean addingNewFiles = false;
/**
* Encoding to use for filenames, defaults to the platform's
* default encoding.
*/
private String encoding;
/**
* Whether the original compression of entries coming from a ZIP
* archive should be kept (for example when updating an archive).
*
* @since Ant 1.6
*/
private boolean keepCompression = false;
/**
* Whether the file modification times will be rounded up to the
* next even number of seconds.
*
* @since Ant 1.6.2
*/
private boolean roundUp = true;
/**
* Comment for the archive.
* @since Ant 1.6.3
*/
private String comment = "";
private int level = ZipOutputStream.DEFAULT_COMPRESSION;
/**
* Assume 0 Unix mode is intentional.
* @since Ant 1.8.0
*/
private boolean preserve0Permission = false;
/**
* Whether to set the language encoding flag when creating the archive.
*
* @since Ant 1.8.0
*/
private boolean useLanguageEncodingFlag = true;
/**
* Whether to add unicode extra fields.
*
* @since Ant 1.8.0
*/
private UnicodeExtraField createUnicodeExtraFields =
UnicodeExtraField.NEVER;
/**
* Whether to fall back to UTF-8 if a name cannot be encoded using
* the specified encoding.
*
* @since Ant 1.8.0
*/
private boolean fallBackToUTF8 = false;
/**
* Whether to enable Zip64 extensions.
*
* @since Ant 1.9.1
*/
private Zip64ModeAttribute zip64Mode = Zip64ModeAttribute.AS_NEEDED;
/**
* This is the name/location of where to
* create the .zip file.
* @param zipFile the path of the zipFile
* @deprecated since 1.5.x.
* Use setDestFile(File) instead.
* @ant.attribute ignore="true"
*/
@Deprecated
public void setZipfile(final File zipFile) {
setDestFile(zipFile);
}
/**
* This is the name/location of where to
* create the file.
* @param file the path of the zipFile
* @since Ant 1.5
* @deprecated since 1.5.x.
* Use setDestFile(File) instead.
* @ant.attribute ignore="true"
*/
@Deprecated
public void setFile(final File file) {
setDestFile(file);
}
/**
* The file to create; required.
* @since Ant 1.5
* @param destFile The new destination File
*/
public void setDestFile(final File destFile) {
this.zipFile = destFile;
}
/**
* The file to create.
* @return the destination file
* @since Ant 1.5.2
*/
public File getDestFile() {
return zipFile;
}
/**
* Directory from which to archive files; optional.
* @param baseDir the base directory
*/
public void setBasedir(final File baseDir) {
this.baseDir = baseDir;
}
/**
* Whether we want to compress the files or only store them;
* optional, default=true;
* @param c if true, compress the files
*/
public void setCompress(final boolean c) {
doCompress = c;
}
/**
* Whether we want to compress the files or only store them;
* @return true if the files are to be compressed
* @since Ant 1.5.2
*/
public boolean isCompress() {
return doCompress;
}
/**
* If true, emulate Sun's jar utility by not adding parent directories;
* optional, defaults to false.
* @param f if true, emulate sun's jar by not adding parent directories
*/
public void setFilesonly(final boolean f) {
doFilesonly = f;
}
/**
* If true, updates an existing file, otherwise overwrite
* any existing one; optional defaults to false.
* @param c if true, updates an existing zip file
*/
public void setUpdate(final boolean c) {
doUpdate = c;
savedDoUpdate = c;
}
/**
* Are we updating an existing archive?
* @return true if updating an existing archive
*/
public boolean isInUpdateMode() {
return doUpdate;
}
/**
* Adds a set of files.
* @param set the fileset to add
*/
public void addFileset(final FileSet set) {
add(set);
}
/**
* Adds a set of files that can be
* read from an archive and be given a prefix/fullpath.
* @param set the zipfileset to add
*/
public void addZipfileset(final ZipFileSet set) {
add(set);
}
/**
* Add a collection of resources to be archived.
* @param a the resources to archive
* @since Ant 1.7
*/
public void add(final ResourceCollection a) {
resources.add(a);
}
/**
* Adds a group of zip files.
* @param set the group (a fileset) to add
*/
public void addZipGroupFileset(final FileSet set) {
groupfilesets.addElement(set);
}
/**
* Sets behavior for when a duplicate file is about to be added -
* one of <code>add</code>, <code>preserve</code> or <code>fail</code>.
* Possible values are: <code>add</code> (keep both
* of the files); <code>preserve</code> (keep the first version
* of the file found); <code>fail</code> halt a problem
* Default for zip tasks is <code>add</code>
* @param df a <code>Duplicate</code> enumerated value
*/
public void setDuplicate(final Duplicate df) {
duplicate = df.getValue();
}
/**
* Possible behaviors when there are no matching files for the task:
* "fail", "skip", or "create".
*/
public static class WhenEmpty extends EnumeratedAttribute {
/**
* The string values for the enumerated value
* @return the values
*/
@Override
public String[] getValues() {
return new String[] {"fail", "skip", "create"};
}
}
/**
* Sets behavior of the task when no files match.
* Possible values are: <code>fail</code> (throw an exception
* and halt the build); <code>skip</code> (do not create
* any archive, but issue a warning); <code>create</code>
* (make an archive with no entries).
* Default for zip tasks is <code>skip</code>;
* for jar tasks, <code>create</code>.
* @param we a <code>WhenEmpty</code> enumerated value
*/
public void setWhenempty(final WhenEmpty we) {
emptyBehavior = we.getValue();
}
/**
* Encoding to use for filenames, defaults to the platform's
* default encoding.
*
* <p>For a list of possible values see <a
* 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>
* @param encoding the encoding name
*/
public void setEncoding(final String encoding) {
this.encoding = encoding;
}
/**
* Encoding to use for filenames.
* @return the name of the encoding to use
* @since Ant 1.5.2
*/
public String getEncoding() {
return encoding;
}
/**
* Whether the original compression of entries coming from a ZIP
* archive should be kept (for example when updating an archive).
* Default is false.
* @param keep if true, keep the original compression
* @since Ant 1.6
*/
public void setKeepCompression(final boolean keep) {
keepCompression = keep;
}
/**
* Comment to use for archive.
*
* @param comment The content of the comment.
* @since Ant 1.6.3
*/
public void setComment(final String comment) {
this.comment = comment;
}
/**
* Comment of the archive
*
* @return Comment of the archive.
* @since Ant 1.6.3
*/
public String getComment() {
return comment;
}
/**
* Set the compression level to use. Default is
* ZipOutputStream.DEFAULT_COMPRESSION.
* @param level compression level.
* @since Ant 1.7
*/
public void setLevel(final int level) {
this.level = level;
}
/**
* Get the compression level.
* @return compression level.
* @since Ant 1.7
*/
public int getLevel() {
return level;
}
/**
* Whether the file modification times will be rounded up to the
* next even number of seconds.
*
* <p>Zip archives store file modification times with a
* granularity of two seconds, so the times will either be rounded
* up or down. If you round down, the archive will always seem
* out-of-date when you rerun the task, so the default is to round
* up. Rounding up may lead to a different type of problems like
* JSPs inside a web archive that seem to be slightly more recent
* than precompiled pages, rendering precompilation useless.</p>
* @param r a <code>boolean</code> value
* @since Ant 1.6.2
*/
public void setRoundUp(final boolean r) {
roundUp = r;
}
/**
* Assume 0 Unix mode is intentional.
* @since Ant 1.8.0
*/
public void setPreserve0Permissions(final boolean b) {
preserve0Permissions = b;
}
/**
* Assume 0 Unix mode is intentional.
* @since Ant 1.8.0
*/
public boolean getPreserve0Permission() {
return preserve0Permission;
}
/**
* Whether to set the language encoding flag.
* @since Ant 1.8.0
*/
public void setUseLanguageEncodingFlag(final boolean b) {
useLanguageEncodingFlag = b;
}
/**
* Whether the language encoding flag will be used.
* @since Ant 1.8.0
*/
public boolean getUseLanguageEnodingFlag() {
return useLanguageEncodingFlag;
}
/**
* Whether Unicode extra fields will be created.
* @since Ant 1.8.0
*/
public void setCreateUnicodeExtraFields(final UnicodeExtraField b) {
createUnicodeExtraFields = b;
}
/**
* Whether Unicode extra fields will be created.
* @since Ant 1.8.0
*/
public UnicodeExtraField getCreateUnicodeExtraField() {
return createUnicodeExtraFields;
}
/**
* Whether to fall back to UTF-8 if a name cannot be encoded using
* the specified encoding.
*
* <p>Defaults to false.</p>
*
* @since Ant 1.8.0
*/
public void setFallBackToUTF8(final boolean b) {
fallBackToUTF8 = b;
}
/**
* Whether to fall back to UTF-8 if a name cannot be encoded using
* the specified encoding.
*
* @since Ant 1.8.0
*/
public boolean getFallBackToUTF8() {
return fallBackToUTF8;
}
/**
* Whether Zip64 extensions should be used.
* @since Ant 1.9.1
*/
public void setZip64Mode(final Zip64ModeAttribute b) {
zip64Mode = b;
}
/**
* Whether Zip64 extensions will be used.
* @since Ant 1.9.1
*/
public Zip64ModeAttribute getZip64Mode() {
return zip64Mode;
}
/**
* validate and build
* @throws BuildException on error
*/
@Override
public void execute() throws BuildException {
if (doubleFilePass) {
skipWriting = true;
executeMain();
skipWriting = false;
executeMain();
} else {
executeMain();
}
}
/**
* Get the value of the updatedFile attribute.
* This should only be called after executeMain has been
* called.
* @return true if executeMain has written to the zip file.
*/
protected boolean hasUpdatedFile() {
return updatedFile;
}
/**
* Build the zip file.
* This is called twice if doubleFilePass is true.
* @throws BuildException on error
*/
public void executeMain() throws BuildException {
checkAttributesAndElements();
// Renamed version of original file, if it exists
File renamedFile = null;
addingNewFiles = true;
processDoUpdate();
processGroupFilesets();
// collect filesets to pass them to getResourcesToAdd
final Vector<ResourceCollection> vfss = new Vector<ResourceCollection>();
if (baseDir != null) {
final FileSet fs = (FileSet) getImplicitFileSet().clone();
fs.setDir(baseDir);
vfss.addElement(fs);
}
final int size = resources.size();
for (int i = 0; i < size; i++) {
final ResourceCollection rsCollection = resources.elementAt(i);
vfss.addElement(rsCollection);
}
final ResourceCollection[] fss = new ResourceCollection[vfss.size()];
vfss.copyInto(fss);
boolean success = false;
try {
// can also handle empty archives
final ArchiveState state = getResourcesToAdd(fss, zipFile, false);
// quick exit if the target is up to date
if (!state.isOutOfDate()) {
return;
}
final File parent = zipFile.getParentFile();
if (parent != null && !parent.isDirectory()
&& !(parent.mkdirs() || parent.isDirectory())) {
throw new BuildException("Failed to create missing parent"
+ " directory for " + zipFile);
}
updatedFile = true;
if (!zipFile.exists() && state.isWithoutAnyResources()) {
createEmptyZip(zipFile);
return;
}
final Resource[][] addThem = state.getResourcesToAdd();
if (doUpdate) {
renamedFile = renameFile();
}
final String action = doUpdate ? "Updating " : "Building ";
if (!skipWriting) {
log(action + archiveType + ": " + zipFile.getAbsolutePath());
}
ZipOutputStream zOut = null;
try {
if (!skipWriting) {
zOut = new ZipOutputStream(zipFile);
zOut.setEncoding(encoding);
zOut.setUseLanguageEncodingFlag(useLanguageEncodingFlag);
zOut.setCreateUnicodeExtraFields(createUnicodeExtraFields.
getPolicy());
zOut.setFallbackToUTF8(fallBackToUTF8);
zOut.setMethod(doCompress
? ZipOutputStream.DEFLATED : ZipOutputStream.STORED);
zOut.setLevel(level);
zOut.setUseZip64(zip64Mode.getMode());
}
initZipOutputStream(zOut);
// Add the explicit resource collections to the archive.
for (int i = 0; i < fss.length; i++) {
if (addThem[i].length != 0) {
addResources(fss[i], addThem[i], zOut);
}
}
if (doUpdate) {
addingNewFiles = false;
final ZipFileSet oldFiles = new ZipFileSet();
oldFiles.setProject(getProject());
oldFiles.setSrc(renamedFile);
oldFiles.setDefaultexcludes(false);
final int addSize = addedFiles.size();
for (int i = 0; i < addSize; i++) {
final PatternSet.NameEntry ne = oldFiles.createExclude();
ne.setName(addedFiles.elementAt(i));
}
final DirectoryScanner ds =
oldFiles.getDirectoryScanner(getProject());
((ZipScanner) ds).setEncoding(encoding);
final String[] f = ds.getIncludedFiles();
Resource[] r = new Resource[f.length];
for (int i = 0; i < f.length; i++) {
r[i] = ds.getResource(f[i]);
}
if (!doFilesonly) {
final String[] d = ds.getIncludedDirectories();
final Resource[] drResources = new Resource[d.length];
for (int i = 0; i < d.length; i++) {
drResources[i] = ds.getResource(d[i]);
}
final Resource[] tmps = r;
r = new Resource[tmps.length + dr.length];
System.arraycopy(drResources, 0, r, 0, dr.length);
System.arraycopy(tmps, 0, r, drResources.length, tmps.length);
}
addResources(oldFiles, r, zOut);
}
if (zOut != null) {
zOut.setComment(comment);
}
finalizeZipOutputStream(zOut);
// If we've been successful on an update, delete the
// temporary file
if (doUpdate) {
if (!renamedFile.delete()) {
log ("Warning: unable to delete temporary file "
+ renamedFile.getName(), Project.MSG_WARN);
}
}
success = true;
} finally {
// Close the output stream.
closeZout(zOut, success);
}
} catch (final IOException ioe) {
String msg = "Problem creating " + archiveType + ": "
+ ioe.getMessage();
// delete a bogus ZIP file (but only if it's not the original one)
if ((!doUpdate || renamedFile != null) && !zipFile.delete()) {
msg += " (and the archive is probably corrupt but I could not "
+ "delete it)";
}
if (doUpdate && renamedFile != null) {
try {
FILE_UTILS.rename(renamedFile, zipFile);
} catch (final IOException e) {
msg += " (and I couldn't rename the temporary file "
+ renamedFile.getName() + " back)";
}
}
throw new BuildException(msg, ioe, getLocation());
} finally {
cleanUp();
}
}
/** rename the zip file. */
private File renameFile() {
final File renamedFile = FILE_UTILS.createTempFile(
"zip", ".tmp", zipFile.getParentFile(), true, false);
try {
FILE_UTILS.rename(zipFile, renamedFile);
} catch (final SecurityException e) {
throw new BuildException(
"Not allowed to rename old file ("
+ zipFile.getAbsolutePath()
+ ") to temporary file");
} catch (final IOException e) {
throw new BuildException(
"Unable to rename old file ("
+ zipFile.getAbsolutePath()
+ ") to temporary file");
}
return renamedFile;
}
/** Close zout */
private void closeZout(final ZipOutputStream zOut, final boolean success)
throws IOException {
if (zOut == null) {
return;
}
try {
zOut.close();
} catch (final IOException ex) {
// If we're in this finally clause because of an
// exception, we don't really care if there's an
// exception when closing the stream. E.g. if it
// throws "ZIP file must have at least one entry",
// because an exception happened before we added
// any files, then we must swallow this
// exception. Otherwise, the error that's reported
// will be the close() error, which is not the
// real cause of the problem.
if (success) {
throw ex;
}
}
}
/** Check the attributes and elements */
private void checkAttributesAndElements() {
if (baseDir == null && resources.size() == 0
&& groupfilesets.size() == 0 && "zip".equals(archiveType)) {
throw new BuildException("basedir attribute must be set, "
+ "or at least one "
+ "resource collection must be given!");
}
if (zipFile == null) {
throw new BuildException("You must specify the "
+ archiveType + " file to create!");
}
if (zipFile.exists() && !zipFile.isFile()) {
throw new BuildException(zipFile + " is not a file.");
}
if (zipFile.exists() && !zipFile.canWrite()) {
throw new BuildException(zipFile + " is read-only.");
}
}
/** Process doupdate */
private void processDoUpdate() {
// Whether or not an actual update is required -
// we don't need to update if the original file doesn't exist
if (doUpdate && !zipFile.exists()) {
doUpdate = false;
logWhenWriting("ignoring update attribute as " + archiveType
+ " doesn't exist.", Project.MSG_DEBUG);
}
}
/** Process groupfilesets */
private void processGroupFilesets() {
// Add the files found in groupfileset to fileset
final int size = groupfilesets.size();
for (int i = 0; i < size; i++) {
logWhenWriting("Processing groupfileset ", Project.MSG_VERBOSE);
final FileSet fs = groupfilesets.elementAt(i);
final FileScanner scanner = fs.getDirectoryScanner(getProject());
final String[] files = scanner.getIncludedFiles();
final File basedir = scanner.getBasedir();
for (int j = 0; j < files.length; j++) {
logWhenWriting("Adding file " + files[j] + " to fileset",
Project.MSG_VERBOSE);
final ZipFileSet zfSet = new ZipFileSet();
zf.setProject(getProject());
zfSet.setSrc(new File(basedir, files[j]));
add(zfSet);
filesetsFromGroupfilesets.addElement(zfSet);
}
}
}
/**
* Indicates if the task is adding new files into the archive as opposed to
* copying back unchanged files from the backup copy
* @return true if adding new files
*/
protected final boolean isAddingNewFiles() {
return addingNewFiles;
}
/**
* Add the given resources.
*
* @param fileset may give additional information like fullpath or
* permissions.
* @param resources the resources to add
* @param zOut the stream to write to
* @throws IOException on error
*
* @since Ant 1.5.2
*/
protected final void addResources(final FileSet fileset, final Resource[] resources,
final ZipOutputStream zOut)
throws IOException {
String prefix = "";
String fullpath = "";
int dirMode = ArchiveFileSet.DEFAULT_DIR_MODE;
int fileMode = ArchiveFileSet.DEFAULT_FILE_MODE;
ArchiveFileSet zfs = null;
if (fileset instanceof ArchiveFileSet) {
zfs = (ArchiveFileSet) fileset;
prefix = zfs.getPrefix(getProject());
fullpath = zfs.getFullpath(getProject());
dirMode = zfs.getDirMode(getProject());
fileMode = zfs.getFileMode(getProject());
}
if (prefix.length() > 0 && fullpath.length() > 0) {
throw new BuildException("Both prefix and fullpath attributes must"
+ " not be set on the same fileset.");
}
if (resources.length != 1 && fullpath.length() > 0) {
throw new BuildException("fullpath attribute may only be specified"
+ " for filesets that specify a single"
+ " file.");
}
if (prefix.length() > 0) {
if (!prefix.endsWith("/") && !prefix.endsWith("\\")) {
prefix += "/";
}
addParentDirs(null, prefix, zOut, "", dirMode);
}
ZipFile zf = null;
try {
boolean dealingWithFiles = false;
File base = null;
if (zfs == null || zfs.getSrc(getProject()) == null) {
dealingWithFiles = true;
base = fileset.getDir(getProject());
} else if (zfs instanceof ZipFileSet) {
zf = new ZipFile(zfs.getSrc(getProject()), encoding);
}
for (int i = 0; i < resources.length; i++) {
String name = null;
if (fullpath.length() > 0) {
name = fullpath;
} else {
name = resources[i].getName();
}
name = name.replace(File.separatorChar, '/');
if ("".equals(name)) {
continue;
}
if (resources[i].isDirectory()) {
if (doFilesonly) {
continue;
}
final int thisDirMode = zfs != null && zfs.hasDirModeBeenSet()
? dirMode : getUnixMode(resources[i], zf, dirMode);
addDirectoryResource(resources[i], name, prefix,
base, zOut,
dirMode, thisDirMode);
} else { // !isDirectory
addParentDirs(base, name, zOut, prefix, dirMode);
if (dealingWithFiles) {
final File f = FILE_UTILS.resolveFile(base,
resources[i].getName());
zipFile(f, zOut, prefix + name, fileMode);
} else {
final int thisFileMode =
zfs != null && zfs.hasFileModeBeenSet()
? fileMode : getUnixMode(resources[i], zf,
fileMode);
addResource(resources[i], name, prefix,
zOut, thisFileMode, zf,
zfs == null
? null : zfs.getSrc(getProject()));
}
}
}
} finally {
if (zf != null) {
zf.close();
}
}
}