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       * Method to zip all files in a given directory.
53       *
54       * @param sourceDir
55       * @return
56       * @throws IOException
57       */
58      public File createZipFile(File sourceDir) throws IOException {
59          File zipFile = File.createTempFile("tmp", ".zip");
60          String path = sourceDir.getAbsolutePath();
61          ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile));
62          ArrayList<File> fileList = getAllFilesList(sourceDir);
63          for (File file : fileList) {
64              ZipEntry ze = new ZipEntry(file.getAbsolutePath().substring(path.length() + 1));
65              zip.putNextEntry(ze);
66              FileInputStream fis = new FileInputStream(file);
67              IOUtils.copy(fis, zip);
68              fis.close();
69              zip.closeEntry();
70          }
71          zip.close();
72          return zipFile;
73      }
74  
75      /**
76       * Method to create a zipped bag file from a given source directory.
77       *
78       * @param sourceDir
79       * @return
80       * @throws IOException
81       */
82      public File createZippedBagFile(File sourceDir) throws IOException {
83          File tempDir = File.createTempFile("tmp", ".dir");
84          FileUtils.deleteQuietly(tempDir);
85          File bagDir = new File(tempDir, "bag_dir");
86          bagDir.mkdirs();
87          FileUtils.copyDirectory(sourceDir, bagDir);
88          PreBag preBag;
89          synchronized (bagFactory) {
90              preBag = bagFactory.createPreBag(bagDir);
91          }
92          preBag.makeBagInPlace(BagFactory.Version.V0_96, false);
93          File zipFile = createZipFile(tempDir);
94          FileUtils.deleteQuietly(tempDir);
95          return zipFile;
96      }
97  
98      /**
99       * Method to extract a given zipped bag file to a given output directory or to a temp directory if toDir is null.
100      *
101      * @param bagFilePath
102      * @param toDir
103      * @return
104      * @throws IOException
105      */
106     public File extractZippedBagFile(String bagFilePath, String toDir) throws IOException {
107         File bagFile = new File(bagFilePath);
108         File extractDir = null;
109         if (toDir != null && toDir.trim().length() != 0)
110             extractDir = new File(toDir);
111         else
112             extractDir = File.createTempFile("tmp", ".ext");
113         FileUtils.deleteQuietly(extractDir);
114         extractDir.mkdirs();
115 
116         byte[] buffer = new byte[BUFFER_SIZE];
117         ZipInputStream zip = new ZipInputStream(new BufferedInputStream(new FileInputStream(bagFile)));
118         ZipEntry next;
119         while ((next = zip.getNextEntry()) != null) {
120             String name = next.getName().replace('\\', '/').replaceFirst("[^/]*/", "");
121             if (name.startsWith(DATA_DIR)) {
122                 File localFile = new File(extractDir, Normalizer.normalize(name.substring(DATA_DIR.length()), FILENAME_NORMALIZATION_FORM));
123                 if (next.isDirectory()) {
124                     if (!localFile.exists() && !localFile.mkdir())
125                         throw new IOException("error creating local directories in output directory");
126                 } else {
127                     File parent = localFile.getParentFile();
128                     if (!parent.exists() && !parent.mkdirs())
129                         throw new IOException("error creating local directories in output directory");
130                     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(localFile));
131                     int bytesRead;
132                     while ((bytesRead = zip.read(buffer, 0, BUFFER_SIZE)) != -1) {
133                         bos.write(buffer, 0, bytesRead);
134                     }
135                     bos.close();
136                 }
137             }
138             else {
139                 File localFile = new File(extractDir, name);
140                 if (next.isDirectory()) {
141                     if (!localFile.exists() && !localFile.mkdir())
142                         throw new IOException("error creating local directories in output directory");
143                 } else {
144                     File parent = localFile.getParentFile();
145                     if (!parent.exists() && !parent.mkdirs())
146                         throw new IOException("error creating local directories in output directory");
147                     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(localFile));
148                     int bytesRead;
149                     while ((bytesRead = zip.read(buffer, 0, BUFFER_SIZE)) != -1) {
150                         bos.write(buffer, 0, bytesRead);
151                     }
152                     bos.close();
153                 }
154             }
155         }
156         zip.close();
157         return extractDir;
158     }
159 
160     /**
161      * Method to get All Files List in a given directory.
162      *
163      * @param directory
164      * @return
165      */
166     public ArrayList<File> getAllFilesList(File directory) {
167         ArrayList<File> fileList = new ArrayList<File>();
168         if (directory.isFile())
169             fileList.add(directory);
170         else if (directory.isDirectory())
171             for (File innerFile : directory.listFiles())
172                 fileList.addAll(getAllFilesList(innerFile));
173         return fileList;
174     }
175 
176     public void deleteFiles(List<File> files) {
177         try {
178             for (File file : files) {
179                 try {
180                     file.delete();
181                 } catch (Exception e) {
182                 }
183             }
184         } catch (Exception e) {
185         }
186     }
187 
188 }