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  import java.io.File;
24  import java.io.FileInputStream;
25  import java.io.FileNotFoundException;
26  import java.io.FileOutputStream;
27  import java.io.IOException;
28  import java.io.InputStream;
29  import java.io.OutputStream;
30  import java.util.ArrayList;
31  import java.util.List;
32  
33  import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
34  import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
35  import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
36  import org.apache.commons.compress.utils.IOUtils;
37  
38  /**
39   * TAR support
40   * @author Frederic Bregier
41   *
42   */
43  public class TarUtility {
44      /**
45       * Create a new Tar from a root directory
46       * @param directory the base directory
47       * @param filename the output filename
48       * @param absolute store absolute filepath (from directory) or only filename
49       * @return True if OK
50       */
51      public static boolean createTarFromDirectory(String directory, String filename, boolean absolute) {
52          File rootDir = new File(directory);
53          File saveFile = new File(filename);
54          // recursive call
55          TarArchiveOutputStream taos;
56          try {
57              taos = new TarArchiveOutputStream(new FileOutputStream(saveFile));
58          } catch (FileNotFoundException e) {
59              return false;
60          }
61          taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
62          try {
63              recurseFiles(rootDir, rootDir, taos, absolute);
64          } catch (IOException e2) {
65              try {
66                  taos.close();
67              } catch (IOException e) {
68                  // ignore
69              }
70              return false;
71          }
72          try {
73              taos.finish();
74          } catch (IOException e1) {
75              // ignore
76          }
77          try {
78              taos.flush();
79          } catch (IOException e) {
80              // ignore
81          }
82          try {
83              taos.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 taos
94       * @param absolute
95       * @throws IOException 
96       */
97      private static void recurseFiles(File root, File file, TarArchiveOutputStream taos, 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, taos, absolute);
103             }
104         } else if ((! file.getName().endsWith(".tar")) && (! file.getName().endsWith(".TAR"))) {
105             String filename = null;
106             if (absolute) {
107                 filename = file.getAbsolutePath().substring(root.getAbsolutePath().length());
108             } else {
109                 filename = file.getName();
110             }
111             TarArchiveEntry tae = new TarArchiveEntry(filename);
112             tae.setSize(file.length());
113             taos.putArchiveEntry(tae);
114             FileInputStream fis = new FileInputStream(file);
115             IOUtils.copy(fis, taos);
116             taos.closeArchiveEntry();
117         }
118     }
119     /**
120      * Create a new Tar 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 createTarFromFiles(List<File> files, String filename) {
126         File saveFile = new File(filename);
127         // recursive call
128         TarArchiveOutputStream taos;
129         try {
130             taos = new TarArchiveOutputStream(new FileOutputStream(saveFile));
131         } catch (FileNotFoundException e) {
132             return false;
133         }
134         taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
135         for (File file: files) {
136             try {
137                 addFile(file, taos);
138             } catch (IOException e) {
139                 try {
140                     taos.close();
141                 } catch (IOException e1) {
142                     // ignore
143                 }
144                 return false;
145             }
146         }
147         try {
148             taos.finish();
149         } catch (IOException e1) {
150             // ignore
151         }
152         try {
153             taos.flush();
154         } catch (IOException e) {
155             // ignore
156         }
157         try {
158             taos.close();
159         } catch (IOException e) {
160             // ignore
161         }
162         return true;
163     }
164     /**
165      * Create a new Tar from an array of Files (only name of files will be used)
166      * @param files array of files to add
167      * @param filename the output filename
168      * @return True if OK
169      */
170     public static boolean createTarFromFiles(File[] files, String filename) {
171         File saveFile = new File(filename);
172         // recursive call
173         TarArchiveOutputStream taos;
174         try {
175             taos = new TarArchiveOutputStream(new FileOutputStream(saveFile));
176         } catch (FileNotFoundException e) {
177             return false;
178         }
179         taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
180         for (File file: files) {
181             try {
182                 addFile(file, taos);
183             } catch (IOException e) {
184                 try {
185                     taos.close();
186                 } catch (IOException e1) {
187                     // ignore
188                 }
189                 return false;
190             }
191         }
192         try {
193             taos.finish();
194         } catch (IOException e1) {
195             // ignore
196         }
197         try {
198             taos.flush();
199         } catch (IOException e) {
200             // ignore
201         }
202         try {
203             taos.close();
204         } catch (IOException e) {
205             // ignore
206         }
207         return true;
208     }
209     /**
210      * Recursive traversal to add files
211      * @param file
212      * @param taos
213      * @throws IOException 
214      */
215     private static void addFile(File file, TarArchiveOutputStream taos) throws IOException {
216         String filename = null;
217         filename = file.getName();
218         TarArchiveEntry tae = new TarArchiveEntry(filename);
219         tae.setSize(file.length());
220         taos.putArchiveEntry(tae);
221         FileInputStream fis = new FileInputStream(file);
222         IOUtils.copy(fis, taos);
223         taos.closeArchiveEntry();
224     }
225     /**
226      * Extract all files from Tar into the specified directory
227      * @param tarFile
228      * @param directory
229      * @return the list of extracted filenames
230      * @throws IOException
231      */
232     public static List<String> unTar(File tarFile, File directory) throws IOException {
233         List<String> result = new ArrayList<String>();
234         InputStream inputStream = new FileInputStream(tarFile);
235         TarArchiveInputStream in = new TarArchiveInputStream(inputStream);
236         TarArchiveEntry entry = in.getNextTarEntry();
237         while (entry != null) {
238             OutputStream out = new FileOutputStream(new File(directory, entry.getName()));
239             IOUtils.copy(in, out);
240             out.close();
241             result.add(entry.getName());
242             entry = in.getNextTarEntry();
243         }
244         in.close();
245         return result;
246     }
247     
248     public static void main(String []args) {
249         if (args.length < 3) {
250             System.err.println("You need to provide 3 arguments:\n"+
251                     "   option filedest.tar \"source\"\n"+
252                     "   where option=1 means untar and source is a directory\n"+
253                     "   option=2 means tar and source is a directory\n"+
254                     "   option=3 means tar and source is a list of files comma separated");
255             System.exit(1);
256         }
257         int option = Integer.parseInt(args[0]);
258         String tarfile = args[1];
259         String tarsource = args[2];
260         String []tarfiles = null;
261         if (option == 3) {
262             tarfiles = args[2].split(",");
263             File []files = new File[tarfiles.length];
264             for (int i = 0; i < tarfiles.length; i++) {
265                 files[i] = new File(tarfiles[i]);
266             }
267             if (createTarFromFiles(files, tarfile)) {
268                 System.out.println("TAR OK from multiple files");
269             } else {
270                 System.err.println("TAR KO from multiple files");
271             }
272         } else if (option == 2) {
273             if (createTarFromDirectory(tarsource, tarfile, false)) {
274                 System.out.println("TAR OK from directory");
275             } else {
276                 System.err.println("TAR KO from directory");
277             }
278         } else if (option == 1) {
279             File tarFile = new File(tarfile);
280             File directory = new File(tarsource);
281             List<String> result = null;
282             try {
283                 result = unTar(tarFile, directory);
284             } catch (IOException e) {
285                 // TODO Auto-generated catch block
286                 e.printStackTrace();
287             }
288             if (result == null || result.isEmpty()) {
289                 System.err.println("UNTAR KO from directory");
290             } else {
291                 for (String string: result) {
292                     System.out.println("File: "+string);
293                 }
294             }
295         }
296         
297     }
298 }