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.

Expand.java 17 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package org.apache.tools.ant.taskdefs;
  19. import java.io.File;
  20. import java.io.FileNotFoundException;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.util.Date;
  25. import java.util.Enumeration;
  26. import java.util.HashSet;
  27. import java.util.Iterator;
  28. import java.util.Set;
  29. import java.util.Vector;
  30. import org.apache.tools.ant.BuildException;
  31. import org.apache.tools.ant.Project;
  32. import org.apache.tools.ant.Task;
  33. import org.apache.tools.ant.types.FileSet;
  34. import org.apache.tools.ant.types.Mapper;
  35. import org.apache.tools.ant.types.PatternSet;
  36. import org.apache.tools.ant.types.Resource;
  37. import org.apache.tools.ant.types.ResourceCollection;
  38. import org.apache.tools.ant.types.resources.FileProvider;
  39. import org.apache.tools.ant.types.resources.Union;
  40. import org.apache.tools.ant.types.selectors.SelectorUtils;
  41. import org.apache.tools.ant.util.FileNameMapper;
  42. import org.apache.tools.ant.util.FileUtils;
  43. import org.apache.tools.ant.util.IdentityMapper;
  44. import org.apache.tools.zip.ZipEntry;
  45. import org.apache.tools.zip.ZipFile;
  46. /**
  47. * Unzip a file.
  48. *
  49. * @since Ant 1.1
  50. *
  51. * @ant.task category="packaging"
  52. * name="unzip"
  53. * name="unjar"
  54. * name="unwar"
  55. */
  56. public class Expand extends Task {
  57. private static final int BUFFER_SIZE = 1024;
  58. private File dest; //req
  59. private File source; // req
  60. private boolean overwrite = true;
  61. private Mapper mapperElement = null;
  62. private Vector patternsets = new Vector();
  63. private Union resources = new Union();
  64. private boolean resourcesSpecified = false;
  65. private boolean failOnEmptyArchive = false;
  66. private boolean stripAbsolutePathSpec = false;
  67. private boolean scanForUnicodeExtraFields = true;
  68. public static final String NATIVE_ENCODING = "native-encoding";
  69. private String encoding = "UTF8";
  70. /** Error message when more that one mapper is defined */
  71. public static final String ERROR_MULTIPLE_MAPPERS = "Cannot define more than one mapper";
  72. private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
  73. /**
  74. * Whether try ing to expand an empty archive would be an error.
  75. *
  76. * @since Ant 1.8.0
  77. */
  78. public void setFailOnEmptyArchive(boolean b) {
  79. failOnEmptyArchive = b;
  80. }
  81. /**
  82. * Whether try ing to expand an empty archive would be an error.
  83. *
  84. * @since Ant 1.8.0
  85. */
  86. public boolean getFailOnEmptyArchive() {
  87. return failOnEmptyArchive;
  88. }
  89. /**
  90. * Do the work.
  91. *
  92. * @exception BuildException Thrown in unrecoverable error.
  93. */
  94. public void execute() throws BuildException {
  95. if ("expand".equals(getTaskType())) {
  96. log("!! expand is deprecated. Use unzip instead. !!");
  97. }
  98. if (source == null && !resourcesSpecified) {
  99. throw new BuildException("src attribute and/or resources must be "
  100. + "specified");
  101. }
  102. if (dest == null) {
  103. throw new BuildException(
  104. "Dest attribute must be specified");
  105. }
  106. if (dest.exists() && !dest.isDirectory()) {
  107. throw new BuildException("Dest must be a directory.", getLocation());
  108. }
  109. if (source != null) {
  110. if (source.isDirectory()) {
  111. throw new BuildException("Src must not be a directory."
  112. + " Use nested filesets instead.", getLocation());
  113. } else if (!source.exists()) {
  114. throw new BuildException("src '" + source + "' doesn't exist.");
  115. } else if (!source.canRead()) {
  116. throw new BuildException("src '" + source + "' cannot be read.");
  117. } else {
  118. expandFile(FILE_UTILS, source, dest);
  119. }
  120. }
  121. Iterator iter = resources.iterator();
  122. while (iter.hasNext()) {
  123. Resource r = (Resource) iter.next();
  124. if (!r.isExists()) {
  125. log("Skipping '" + r.getName() + "' because it doesn't exist.");
  126. continue;
  127. }
  128. FileProvider fp = (FileProvider) r.as(FileProvider.class);
  129. if (fp != null) {
  130. expandFile(FILE_UTILS, fp.getFile(), dest);
  131. } else {
  132. expandResource(r, dest);
  133. }
  134. }
  135. }
  136. /**
  137. * This method is to be overridden by extending unarchival tasks.
  138. *
  139. * @param fileUtils the fileUtils
  140. * @param srcF the source file
  141. * @param dir the destination directory
  142. */
  143. protected void expandFile(FileUtils fileUtils, File srcF, File dir) {
  144. log("Expanding: " + srcF + " into " + dir, Project.MSG_INFO);
  145. ZipFile zf = null;
  146. FileNameMapper mapper = getMapper();
  147. if (!srcF.exists()) {
  148. throw new BuildException("Unable to expand "
  149. + srcF
  150. + " as the file does not exist",
  151. getLocation());
  152. }
  153. try {
  154. zf = new ZipFile(srcF, encoding, scanForUnicodeExtraFields);
  155. boolean empty = true;
  156. Enumeration e = zf.getEntries();
  157. while (e.hasMoreElements()) {
  158. empty = false;
  159. ZipEntry ze = (ZipEntry) e.nextElement();
  160. extractFile(fileUtils, srcF, dir, zf.getInputStream(ze),
  161. ze.getName(), new Date(ze.getTime()),
  162. ze.isDirectory(), mapper);
  163. }
  164. if (empty && getFailOnEmptyArchive()) {
  165. throw new BuildException("archive '" + srcF + "' is empty");
  166. }
  167. log("expand complete", Project.MSG_VERBOSE);
  168. } catch (IOException ioe) {
  169. throw new BuildException(
  170. "Error while expanding " + srcF.getPath()
  171. + "\n" + ioe.toString(),
  172. ioe);
  173. } finally {
  174. ZipFile.closeQuietly(zf);
  175. }
  176. }
  177. /**
  178. * This method is to be overridden by extending unarchival tasks.
  179. *
  180. * @param srcR the source resource
  181. * @param dir the destination directory
  182. */
  183. protected void expandResource(Resource srcR, File dir) {
  184. throw new BuildException("only filesystem based resources are"
  185. + " supported by this task.");
  186. }
  187. /**
  188. * get a mapper for a file
  189. * @return a filenamemapper for a file
  190. */
  191. protected FileNameMapper getMapper() {
  192. FileNameMapper mapper = null;
  193. if (mapperElement != null) {
  194. mapper = mapperElement.getImplementation();
  195. } else {
  196. mapper = new IdentityMapper();
  197. }
  198. return mapper;
  199. }
  200. // CheckStyle:ParameterNumberCheck OFF - bc
  201. /**
  202. * extract a file to a directory
  203. * @param fileUtils a fileUtils object
  204. * @param srcF the source file
  205. * @param dir the destination directory
  206. * @param compressedInputStream the input stream
  207. * @param entryName the name of the entry
  208. * @param entryDate the date of the entry
  209. * @param isDirectory if this is true the entry is a directory
  210. * @param mapper the filename mapper to use
  211. * @throws IOException on error
  212. */
  213. protected void extractFile(FileUtils fileUtils, File srcF, File dir,
  214. InputStream compressedInputStream,
  215. String entryName, Date entryDate,
  216. boolean isDirectory, FileNameMapper mapper)
  217. throws IOException {
  218. if (stripAbsolutePathSpec && entryName.length() > 0
  219. && (entryName.charAt(0) == File.separatorChar
  220. || entryName.charAt(0) == '/'
  221. || entryName.charAt(0) == '\\')) {
  222. log("stripped absolute path spec from " + entryName,
  223. Project.MSG_VERBOSE);
  224. entryName = entryName.substring(1);
  225. }
  226. if (patternsets != null && patternsets.size() > 0) {
  227. String name = entryName.replace('/', File.separatorChar)
  228. .replace('\\', File.separatorChar);
  229. boolean included = false;
  230. Set includePatterns = new HashSet();
  231. Set excludePatterns = new HashSet();
  232. for (int v = 0, size = patternsets.size(); v < size; v++) {
  233. PatternSet p = (PatternSet) patternsets.elementAt(v);
  234. String[] incls = p.getIncludePatterns(getProject());
  235. if (incls == null || incls.length == 0) {
  236. // no include pattern implicitly means includes="**"
  237. incls = new String[] {"**"};
  238. }
  239. for (int w = 0; w < incls.length; w++) {
  240. String pattern = incls[w].replace('/', File.separatorChar)
  241. .replace('\\', File.separatorChar);
  242. if (pattern.endsWith(File.separator)) {
  243. pattern += "**";
  244. }
  245. includePatterns.add(pattern);
  246. }
  247. String[] excls = p.getExcludePatterns(getProject());
  248. if (excls != null) {
  249. for (int w = 0; w < excls.length; w++) {
  250. String pattern = excls[w]
  251. .replace('/', File.separatorChar)
  252. .replace('\\', File.separatorChar);
  253. if (pattern.endsWith(File.separator)) {
  254. pattern += "**";
  255. }
  256. excludePatterns.add(pattern);
  257. }
  258. }
  259. }
  260. for (Iterator iter = includePatterns.iterator();
  261. !included && iter.hasNext();) {
  262. String pattern = (String) iter.next();
  263. included = SelectorUtils.matchPath(pattern, name);
  264. }
  265. for (Iterator iter = excludePatterns.iterator();
  266. included && iter.hasNext();) {
  267. String pattern = (String) iter.next();
  268. included = !SelectorUtils.matchPath(pattern, name);
  269. }
  270. if (!included) {
  271. //Do not process this file
  272. log("skipping " + entryName
  273. + " as it is excluded or not included.",
  274. Project.MSG_VERBOSE);
  275. return;
  276. }
  277. }
  278. String[] mappedNames = mapper.mapFileName(entryName);
  279. if (mappedNames == null || mappedNames.length == 0) {
  280. mappedNames = new String[] {entryName};
  281. }
  282. File f = fileUtils.resolveFile(dir, mappedNames[0]);
  283. try {
  284. if (!overwrite && f.exists()
  285. && f.lastModified() >= entryDate.getTime()) {
  286. log("Skipping " + f + " as it is up-to-date",
  287. Project.MSG_DEBUG);
  288. return;
  289. }
  290. log("expanding " + entryName + " to " + f,
  291. Project.MSG_VERBOSE);
  292. // create intermediary directories - sometimes zip don't add them
  293. File dirF = f.getParentFile();
  294. if (dirF != null) {
  295. dirF.mkdirs();
  296. }
  297. if (isDirectory) {
  298. f.mkdirs();
  299. } else {
  300. byte[] buffer = new byte[BUFFER_SIZE];
  301. int length = 0;
  302. FileOutputStream fos = null;
  303. try {
  304. fos = new FileOutputStream(f);
  305. while ((length =
  306. compressedInputStream.read(buffer)) >= 0) {
  307. fos.write(buffer, 0, length);
  308. }
  309. fos.close();
  310. fos = null;
  311. } finally {
  312. FileUtils.close(fos);
  313. }
  314. }
  315. fileUtils.setFileLastModified(f, entryDate.getTime());
  316. } catch (FileNotFoundException ex) {
  317. log("Unable to expand to file " + f.getPath(),
  318. ex,
  319. Project.MSG_WARN);
  320. }
  321. }
  322. // CheckStyle:ParameterNumberCheck ON
  323. /**
  324. * Set the destination directory. File will be unzipped into the
  325. * destination directory.
  326. *
  327. * @param d Path to the directory.
  328. */
  329. public void setDest(File d) {
  330. this.dest = d;
  331. }
  332. /**
  333. * Set the path to zip-file.
  334. *
  335. * @param s Path to zip-file.
  336. */
  337. public void setSrc(File s) {
  338. this.source = s;
  339. }
  340. /**
  341. * Should we overwrite files in dest, even if they are newer than
  342. * the corresponding entries in the archive?
  343. * @param b a <code>boolean</code> value
  344. */
  345. public void setOverwrite(boolean b) {
  346. overwrite = b;
  347. }
  348. /**
  349. * Add a patternset.
  350. * @param set a pattern set
  351. */
  352. public void addPatternset(PatternSet set) {
  353. patternsets.addElement(set);
  354. }
  355. /**
  356. * Add a fileset
  357. * @param set a file set
  358. */
  359. public void addFileset(FileSet set) {
  360. add(set);
  361. }
  362. /**
  363. * Add a resource collection.
  364. * @param rc a resource collection.
  365. * @since Ant 1.7
  366. */
  367. public void add(ResourceCollection rc) {
  368. resourcesSpecified = true;
  369. resources.add(rc);
  370. }
  371. /**
  372. * Defines the mapper to map source entries to destination files.
  373. * @return a mapper to be configured
  374. * @exception BuildException if more than one mapper is defined
  375. * @since Ant1.7
  376. */
  377. public Mapper createMapper() throws BuildException {
  378. if (mapperElement != null) {
  379. throw new BuildException(ERROR_MULTIPLE_MAPPERS,
  380. getLocation());
  381. }
  382. mapperElement = new Mapper(getProject());
  383. return mapperElement;
  384. }
  385. /**
  386. * A nested filenamemapper
  387. * @param fileNameMapper the mapper to add
  388. * @since Ant 1.6.3
  389. */
  390. public void add(FileNameMapper fileNameMapper) {
  391. createMapper().add(fileNameMapper);
  392. }
  393. /**
  394. * Sets the encoding to assume for file names and comments.
  395. *
  396. * <p>Set to <code>native-encoding</code> if you want your
  397. * platform's native encoding, defaults to UTF8.</p>
  398. * @param encoding the name of the character encoding
  399. * @since Ant 1.6
  400. */
  401. public void setEncoding(String encoding) {
  402. internalSetEncoding(encoding);
  403. }
  404. /**
  405. * Supports grand-children that want to support the attribute
  406. * where the child-class doesn't (i.e. Unzip in the compress
  407. * Antlib).
  408. *
  409. * @since Ant 1.8.0
  410. */
  411. protected void internalSetEncoding(String encoding) {
  412. if (NATIVE_ENCODING.equals(encoding)) {
  413. encoding = null;
  414. }
  415. this.encoding = encoding;
  416. }
  417. /**
  418. * @since Ant 1.8.0
  419. */
  420. public String getEncoding() {
  421. return encoding;
  422. }
  423. /**
  424. * Whether leading path separators should be stripped.
  425. *
  426. * @since Ant 1.8.0
  427. */
  428. public void setStripAbsolutePathSpec(boolean b) {
  429. stripAbsolutePathSpec = b;
  430. }
  431. /**
  432. * Whether unicode extra fields will be used if present.
  433. *
  434. * @since Ant 1.8.0
  435. */
  436. public void setScanForUnicodeExtraFields(boolean b) {
  437. internalSetScanForUnicodeExtraFields(b);
  438. }
  439. /**
  440. * Supports grand-children that want to support the attribute
  441. * where the child-class doesn't (i.e. Unzip in the compress
  442. * Antlib).
  443. *
  444. * @since Ant 1.8.0
  445. */
  446. protected void internalSetScanForUnicodeExtraFields(boolean b) {
  447. scanForUnicodeExtraFields = b;
  448. }
  449. /**
  450. * @since Ant 1.8.0
  451. */
  452. public boolean getScanForUnicodeExtraFields() {
  453. return scanForUnicodeExtraFields;
  454. }
  455. }