View Javadoc

1   /*
2    * Copyright 2012 The Kuali Foundation.
3    * 
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    * http://www.opensource.org/licenses/ecl2.php
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.ole.utility;
17  
18  import java.io.BufferedInputStream;
19  import java.io.BufferedOutputStream;
20  import java.io.File;
21  import java.io.FileInputStream;
22  import java.io.FileOutputStream;
23  import java.io.IOException;
24  import java.text.Normalizer;
25  import java.text.Normalizer.Form;
26  import java.util.ArrayList;
27  import java.util.List;
28  import java.util.zip.ZipEntry;
29  import java.util.zip.ZipInputStream;
30  import java.util.zip.ZipOutputStream;
31  
32  import org.apache.commons.compress.utils.IOUtils;
33  import org.apache.commons.io.FileUtils;
34  
35  import gov.loc.repository.bagit.BagFactory;
36  import gov.loc.repository.bagit.PreBag;
37  
38  /**
39   * Class for Utility operations on File Compression.
40   * 
41   * @author Rajesh Chowdary K
42   * @created May 24, 2012
43   */
44  public class CompressUtils {
45  
46      private static BagFactory   bagFactory                  = new BagFactory();
47      private static final int    BUFFER_SIZE                 = 1024;
48      private static final String DATA_DIR                    = "data/";
49      private static final Form   FILENAME_NORMALIZATION_FORM = Form.NFC;
50  
51      /**
52       * 
53       * Method to zip all files in a given directory.
54       * 
55       * @param sourceDir
56       * @return
57       * @throws IOException
58       */
59      public File createZipFile(File sourceDir) throws IOException {
60          File zipFile = File.createTempFile("tmp", ".zip");
61          String path = sourceDir.getAbsolutePath();
62          ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile));
63          ArrayList<File> fileList = getAllFilesList(sourceDir);
64          for (File file : fileList) {
65              ZipEntry ze = new ZipEntry(file.getAbsolutePath().substring(path.length() + 1));
66              zip.putNextEntry(ze);
67              FileInputStream fis = new FileInputStream(file);
68              IOUtils.copy(fis, zip);
69              fis.close();
70              zip.closeEntry();
71          }
72          zip.close();
73          return zipFile;
74      }
75  
76      /**
77       * 
78       * Method to create a zipped bag file from a given source directory.
79       * 
80       * @param sourceDir
81       * @return
82       * @throws IOException
83       */
84      public File createZippedBagFile(File sourceDir) throws IOException {
85          File tempDir = File.createTempFile("tmp", ".dir");
86          FileUtils.deleteQuietly(tempDir);
87          File bagDir = new File(tempDir, "bag_dir");
88          bagDir.mkdirs();
89          FileUtils.copyDirectory(sourceDir, bagDir);
90          PreBag preBag;
91          synchronized (bagFactory) {
92              preBag = bagFactory.createPreBag(bagDir);
93          }
94          preBag.makeBagInPlace(BagFactory.Version.V0_96, false);
95          File zipFile = createZipFile(tempDir);
96          FileUtils.deleteQuietly(tempDir);
97          return zipFile;
98      }
99  
100     /**
101      * 
102      * Method to extract a given zipped bag file to a given output directory or to a temp directory if toDir is null.
103      * 
104      * @param bagFilePath
105      * @param toDir
106      * @return
107      * @throws IOException
108      */
109     public File extractZippedBagFile(String bagFilePath, String toDir) throws IOException {
110         File bagFile = new File(bagFilePath);
111         File extractDir = null;
112         if (toDir != null && toDir.trim().length() != 0)
113             extractDir = new File(toDir);
114         else
115             extractDir = File.createTempFile("tmp", ".ext");
116         FileUtils.deleteQuietly(extractDir);
117         extractDir.mkdirs();
118 
119         byte[] buffer = new byte[BUFFER_SIZE];
120         ZipInputStream zip = new ZipInputStream(new BufferedInputStream(new FileInputStream(bagFile)));
121         ZipEntry next;
122         while ((next = zip.getNextEntry()) != null) {
123             String name = next.getName().replace('\\', '/').replaceFirst("[^/]*/", "");
124             if (name.startsWith(DATA_DIR)) {
125                 File localFile = new File(extractDir, Normalizer.normalize(name.substring(DATA_DIR.length()), FILENAME_NORMALIZATION_FORM));
126                 if (next.isDirectory()) {
127                     if (!localFile.exists() && !localFile.mkdir())
128                         throw new IOException("error creating local directories in output directory");
129                 } else {
130                     File parent = localFile.getParentFile();
131                     if (!parent.exists() && !parent.mkdirs())
132                         throw new IOException("error creating local directories in output directory");
133                     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(localFile));
134                     int bytesRead;
135                     while ((bytesRead = zip.read(buffer, 0, BUFFER_SIZE)) != -1) {
136                         bos.write(buffer, 0, bytesRead);
137                     }
138                     bos.close();
139                 }
140             }
141         }
142         zip.close();
143         return extractDir;
144     }
145 
146     /**
147      * 
148      * Method to get All Files List in a given directory.
149      * 
150      * @param directory
151      * @return
152      */
153     public ArrayList<File> getAllFilesList(File directory) {
154         ArrayList<File> fileList = new ArrayList<File>();
155         if (directory.isFile())
156             fileList.add(directory);
157         else if (directory.isDirectory())
158             for (File innerFile : directory.listFiles())
159                 fileList.addAll(getAllFilesList(innerFile));
160         return fileList;
161     }
162 
163     public void deleteFiles(List<File> files) {
164         try {
165             for (File file : files) {
166                 try {
167                     file.delete();
168                 } catch (Exception e) {
169                 }
170             }
171         } catch (Exception e) {
172         }
173     }
174 
175 }