View Javadoc

1   /**
2      This file is part of GoldenGate Project (named also GoldenGate or GG).
3   
4      Copyright 2009, Frederic Bregier, and individual contributors by the @author
5      tags. See the COPYRIGHT.txt in the distribution for a full listing of
6      individual contributors.
7   
8      All GoldenGate Project is free software: you can redistribute it and/or 
9      modify it under the terms of the GNU General Public License as published 
10     by the Free Software Foundation, either version 3 of the License, or
11     (at your option) any later version.
12  
13     GoldenGate is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17  
18     You should have received a copy of the GNU General Public License
19     along with GoldenGate .  If not, see <http://www.gnu.org/licenses/>.
20   */
21  package goldengate.common.tar;
22  
23  
24  import java.io.File;
25  import java.io.FileInputStream;
26  import java.io.FileNotFoundException;
27  import java.io.FileOutputStream;
28  import java.io.IOException;
29  import java.io.InputStream;
30  import java.io.OutputStream;
31  import java.util.ArrayList;
32  import java.util.List;
33  
34  import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
35  import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
36  import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
37  import org.apache.commons.compress.utils.IOUtils;
38  
39  /**
40   * @author Frederic Bregier
41   *
42   */
43  public class ZipUtility {
44  
45      /**
46       * Create a new Zip from a root directory
47       * @param directory the base directory
48       * @param filename the output filename
49       * @param absolute store absolute filepath (from directory) or only filename
50       * @return True if OK
51       */
52      public static boolean createZipFromDirectory(String directory, String filename, boolean absolute) {
53          File rootDir = new File(directory);
54          File saveFile = new File(filename);
55          // recursive call
56          ZipArchiveOutputStream zaos;
57          try {
58              zaos = new ZipArchiveOutputStream(new FileOutputStream(saveFile));
59          } catch (FileNotFoundException e) {
60              return false;
61          }
62          try {
63              recurseFiles(rootDir, rootDir, zaos, absolute);
64          } catch (IOException e2) {
65              try {
66                  zaos.close();
67              } catch (IOException e) {
68                  // ignore
69              }
70              return false;
71          }
72          try {
73              zaos.finish();
74          } catch (IOException e1) {
75              // ignore
76          }
77          try {
78              zaos.flush();
79          } catch (IOException e) {
80              // ignore
81          }
82          try {
83              zaos.close();
84          } catch (IOException e) {
85              // ignore
86          }
87          return true;
88      }
89      /**
90       * Recursive traversal to add files
91       * @param root
92       * @param file
93       * @param zaos
94       * @param absolute
95       * @throws IOException 
96       */
97      private static void recurseFiles(File root, File file, ZipArchiveOutputStream zaos, boolean absolute) throws IOException {
98          if (file.isDirectory()) {
99              // recursive call
100             File [] files = file.listFiles();
101             for (File file2: files) {
102                 recurseFiles(root, file2, zaos, absolute);
103             }
104         } else if ((! file.getName().endsWith(".zip")) && (! file.getName().endsWith(".ZIP"))) {
105             String filename = null;
106             if (absolute) {
107                 filename = file.getAbsolutePath().substring(root.getAbsolutePath().length());
108             } else {
109                 filename = file.getName();
110             }
111             ZipArchiveEntry zae = new ZipArchiveEntry(filename);
112             zae.setSize(file.length());
113             zaos.putArchiveEntry(zae);
114             FileInputStream fis = new FileInputStream(file);
115             IOUtils.copy(fis, zaos);
116             zaos.closeArchiveEntry();
117         }
118     }
119     /**
120      * Create a new Zip from a list of Files (only name of files will be used)
121      * @param files list of files to add
122      * @param filename the output filename
123      * @return True if OK
124      */
125     public static boolean createZipFromFiles(List<File> files, String filename) {
126         File saveFile = new File(filename);
127         ZipArchiveOutputStream zaos;
128         try {
129             zaos = new ZipArchiveOutputStream(new FileOutputStream(saveFile));
130         } catch (FileNotFoundException e) {
131             return false;
132         }
133         for (File file: files) {
134             try {
135                 addFile(file, zaos);
136             } catch (IOException e) {
137                 try {
138                     zaos.close();
139                 } catch (IOException e1) {
140                     // ignore
141                 }
142                 return false;
143             }
144         }
145         try {
146             zaos.finish();
147         } catch (IOException e1) {
148             // ignore
149         }
150         try {
151             zaos.flush();
152         } catch (IOException e) {
153             // ignore
154         }
155         try {
156             zaos.close();
157         } catch (IOException e) {
158             // ignore
159         }
160         return true;
161     }
162     /**
163      * Create a new Zip from an array of Files (only name of files will be used)
164      * @param files array of files to add
165      * @param filename the output filename
166      * @return True if OK
167      */
168     public static boolean createZipFromFiles(File[] files, String filename) {
169         File saveFile = new File(filename);
170         ZipArchiveOutputStream zaos;
171         try {
172             zaos = new ZipArchiveOutputStream(new FileOutputStream(saveFile));
173         } catch (FileNotFoundException e) {
174             return false;
175         }
176         for (File file: files) {
177             try {
178                 addFile(file, zaos);
179             } catch (IOException e) {
180                 try {
181                     zaos.close();
182                 } catch (IOException e1) {
183                     // ignore
184                 }
185                 return false;
186             }
187         }
188         try {
189             zaos.finish();
190         } catch (IOException e1) {
191             // ignore
192         }
193         try {
194             zaos.flush();
195         } catch (IOException e) {
196             // ignore
197         }
198         try {
199             zaos.close();
200         } catch (IOException e) {
201             // ignore
202         }
203         return true;
204     }
205     /**
206      * Recursive traversal to add files
207      * @param file
208      * @param zaos
209      * @throws IOException 
210      */
211     private static void addFile(File file, ZipArchiveOutputStream zaos) throws IOException {
212         String filename = null;
213         filename = file.getName();
214         ZipArchiveEntry zae = new ZipArchiveEntry(filename);
215         zae.setSize(file.length());
216         zaos.putArchiveEntry(zae);
217         FileInputStream fis = new FileInputStream(file);
218         IOUtils.copy(fis, zaos);
219         zaos.closeArchiveEntry();
220     }
221     /**
222      * Extract all files from Tar into the specified directory
223      * @param tarFile
224      * @param directory
225      * @return the list of extracted filenames
226      * @throws IOException
227      */
228     public static List<String> unZip(File tarFile, File directory) throws IOException {
229         List<String> result = new ArrayList<String>();
230         InputStream inputStream = new FileInputStream(tarFile);
231         ZipArchiveInputStream in = new ZipArchiveInputStream(inputStream);
232         ZipArchiveEntry entry = in.getNextZipEntry();
233         while (entry != null) {
234             OutputStream out = new FileOutputStream(new File(directory, entry.getName()));
235             IOUtils.copy(in, out);
236             out.close();
237             result.add(entry.getName());
238             entry = in.getNextZipEntry();
239         }
240         in.close();
241         return result;
242     }
243     
244     public static void main(String []args) {
245         if (args.length < 3) {
246             System.err.println("You need to provide 3 arguments:\n"+
247                     "   option filedest.tar \"source\"\n"+
248                     "   where option=1 means unzip and source is a directory\n"+
249                     "   option=2 means zip and source is a directory\n"+
250                     "   option=3 means zip and source is a list of files comma separated");
251             System.exit(1);
252         }
253         int option = Integer.parseInt(args[0]);
254         String tarfile = args[1];
255         String tarsource = args[2];
256         String []tarfiles = null;
257         if (option == 3) {
258             tarfiles = args[2].split(",");
259             File []files = new File[tarfiles.length];
260             for (int i = 0; i < tarfiles.length; i++) {
261                 files[i] = new File(tarfiles[i]);
262             }
263             if (createZipFromFiles(files, tarfile)) {
264                 System.out.println("ZIP OK from multiple files");
265             } else {
266                 System.err.println("ZIP KO from multiple files");
267             }
268         } else if (option == 2) {
269             if (createZipFromDirectory(tarsource, tarfile, false)) {
270                 System.out.println("ZIP OK from directory");
271             } else {
272                 System.err.println("ZIP KO from directory");
273             }
274         } else if (option == 1) {
275             File tarFile = new File(tarfile);
276             File directory = new File(tarsource);
277             List<String> result = null;
278             try {
279                 result = unZip(tarFile, directory);
280             } catch (IOException e) {
281                 // TODO Auto-generated catch block
282                 e.printStackTrace();
283             }
284             if (result == null || result.isEmpty()) {
285                 System.err.println("UNZIP KO from directory");
286             } else {
287                 for (String string: result) {
288                     System.out.println("File: "+string);
289                 }
290             }
291         }
292         
293     }
294 }