Dateiverwaltung für die WebBox
ulrich
2018-04-03 e639c2788805fce3f6c266f48444db3099906586
commit | author | age
8931b7 1 /*
U 2     Dateiverwaltung - File management in your browser
3     Copyright (C) 2017 Ulrich Hilger, http://uhilger.de
4
5     This program is free software: you can redistribute it and/or modify
6     it under the terms of the GNU Affero General Public License as
7     published by the Free Software Foundation, either version 3 of the
8     License, or (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU Affero General Public License for more details.
14
15     You should have received a copy of the GNU Affero General Public License
16     along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
c7c502 19 package de.uhilger.filecms.api;
U 20
6e70be 21 import de.uhilger.filecms.data.FileRef;
e639c2 22 import de.uhilger.filecms.data.Inhalt;
d14d78 23 import de.uhilger.filecms.pub.AbstractComparator;
U 24 import de.uhilger.filecms.pub.FileNameComparator;
bb9f8c 25 import de.uhilger.wbx.Bild;
e639c2 26 import de.uhilger.wbx.WbxUtils;
U 27 import static de.uhilger.wbx.web.FeedServlet.WBX_FILE_BASE;
8e51b7 28 import java.io.File;
af9930 29 import java.io.FileInputStream;
3ad4db 30 import java.io.FileNotFoundException;
6bd2c1 31 import java.io.FileOutputStream;
3ad4db 32 import java.io.FileReader;
e5ff42 33 import java.io.FileWriter;
U 34 import java.io.IOException;
6bd2c1 35 import java.io.InputStream;
fab80c 36 import java.io.Reader;
e5ff42 37 import java.security.Principal;
7342b1 38 import java.util.ArrayList;
d14d78 39 import java.util.Arrays;
6bd2c1 40 import java.util.Enumeration;
5bfd34 41 import java.util.Iterator;
7342b1 42 import java.util.List;
e5ff42 43 import java.util.logging.Level;
8e51b7 44 import java.util.logging.Logger;
af9930 45 import java.util.zip.Adler32;
U 46 import java.util.zip.CheckedOutputStream;
6bd2c1 47 import java.util.zip.ZipEntry;
U 48 import java.util.zip.ZipFile;
af9930 49 import java.util.zip.ZipOutputStream;
bb9f8c 50 import net.coobird.thumbnailator.Thumbnails;
5bfd34 51 import org.apache.commons.io.FileUtils;
c7c502 52
U 53 /**
fafe1b 54  * Methoden zur Verwaltung von Dateien
c7c502 55  */
8931b7 56 public class FileMgr extends Api {
8e51b7 57   private static final Logger logger = Logger.getLogger(FileMgr.class.getName());
c7c502 58   
972e94 59   
9e2964 60   public static final int OP_COPY = 1;
U 61   public static final int OP_MOVE = 2;
62   
ea7193 63   public String hallo() {
U 64     return "Hallo Welt!";
65   }
66   
1f550a 67   /**
U 68    * Inhalte der WebBox listen. Hier wird nur der relative Pfad 
69    * ausgehend von www oder home ausgegeben sowie zudem ausgehend 
70    * von $daten und $basis, sofern der Benutzer die Rolle wbxAdmin hat.
71    * 
72    * Andere Inhalte werden nicht ausgegeben.
73    * 
74    * @param relPath
75    * @return 
76    */
7342b1 77   public List<FileRef> list(String relPath) {
d14d78 78     return listInt(relPath, "name", AbstractComparator.ORDER_ASC);
U 79   }
80   
81   public List<FileRef> listOrdered(String relPath, String orderBy, String order) {
82     return listInt(relPath, orderBy, order);
83   }
84   
85   /**
86    * Inhalte der WebBox listen. Hier wird nur der relative Pfad 
87    * ausgehend von www oder home ausgegeben sowie zudem ausgehend 
88    * von $daten und $basis, sofern der Benutzer die Rolle wbxAdmin hat.
89    * 
90    * Andere Inhalte werden nicht ausgegeben.
91    * 
92    * @param relPath
93    * @param orderBy 'name'
94    * @param order AbstractComparator.ORDER_ASC oder AbstractComparator.ORDER_DESC
95    * @return 
96    */
97   private List<FileRef> listInt(String relPath, String orderBy, String order) {
f7d8bf 98     Bild bild = new Bild();
5dfab6 99     List<FileRef> files = new ArrayList();
ac72fe 100     if (!relPath.startsWith(".") && !relPath.contains("WEB-INF") && !relPath.contains("META-INF")) {
3d0c6d 101       if (relPath.length() == 0) {
U 102         FileRef namedPublicFolder = new FileRef(PUB_DIR_NAME, true);
103         logger.finer(namedPublicFolder.getAbsolutePath());
104         FileRef namedHomeFolder = new FileRef(HOME_DIR_NAME, true);
105         logger.finer(namedHomeFolder.getAbsolutePath());
106         FileRef namedDavFolder = new FileRef(DAV_DIR_NAME, true);
107         logger.finer(namedDavFolder.getAbsolutePath());
108         files = new ArrayList();
109         files.add(namedHomeFolder);
110         files.add(namedPublicFolder);
111         files.add(namedDavFolder);
112         if (getRequest().isUserInRole(WBX_ADMIN_ROLE)) {
113           FileRef namedBaseFolder = new FileRef(WBX_BASE, true);
114           FileRef namedDataFolder = new FileRef(WBX_DATA, true);
115           files.add(namedBaseFolder);
116           files.add(namedDataFolder);
d14d78 117         }
3d0c6d 118       } else {
U 119         String path = getTargetDir(relPath).getAbsolutePath();
120         logger.fine("listing path: " + path);
121         File dir = new File(path);
122         if (dir.exists()) {
123           File[] fileArray = dir.listFiles();
124           if (orderBy != null && orderBy.equalsIgnoreCase("name")) {
125             Arrays.sort(fileArray, new FileNameComparator(order));
126           } else {
127             Arrays.sort(fileArray, new FileNameComparator(AbstractComparator.ORDER_ASC));
5bfd34 128           }
3d0c6d 129           for (int i = 0; i < fileArray.length; i++) {
U 130             logger.fine(fileArray[i].toURI().toString());
131             String fname = fileArray[i].toURI().toString().replace("file:/", "");
132             if (fileArray[i].isDirectory()) {
133               fname = fname.substring(0, fname.length() - 1);
134             }
135             logger.fine(fname);
ac72fe 136             if(!fname.contains("WEB-INF") && !fname.contains("META-INF")) {
c5eaaa 137               long fLen = fileArray[i].length();
U 138               long lastMod = fileArray[i].lastModified();
139               FileRef ref = new FileRef(fname, fileArray[i].isDirectory(), fileArray[i].isHidden(), lastMod, fLen);
ac72fe 140               ref.setMimetype(bild.getMimeType(fileArray[i]));
U 141               files.add(ref);
142             }
3d0c6d 143           }
5bfd34 144         }
5dfab6 145       }
3d0c6d 146     }
7342b1 147     return files;
2121cc 148   }
e639c2 149  
U 150   /**
151    * Wie list nur mit drill down
152    * 
153    * TODO '/data' muss noch variabel gestaltet werden
154    * 
155    * @param relativePath
156    * @param maxTiefe
157    * @param maxAnzahl
158    * @return 
159    */
160   public List<Inhalt> collectFiles(String relativePath, int maxTiefe, int maxAnzahl) {
161     Bild bild = new Bild();
162     WbxUtils wu = new WbxUtils();
163     String basis = wu.getJNDIParameter(WBX_FILE_BASE, WbxUtils.EMPTY_STRING);
164     String pubDirName = wu.getJNDIParameter(WbxUtils.WBX_PUB_DIR_NAME, WbxUtils.WBX_DEFAULT_PUB_DIR_NAME);
165     String relPath = relativePath.replace("/data", pubDirName);
166     String absPath = basis + relPath;
167     
168     ArrayList beitraege = new ArrayList();
169     ArrayList<Inhalt> files = new ArrayList<>();
170     wu.collectFiles(new File(absPath), 0, beitraege, maxTiefe, maxAnzahl);
171
172     Iterator i = beitraege.iterator();
173     while(i.hasNext()) {
174       File beitrag = (File) i.next();
175       Inhalt cont = new Inhalt();
176       cont.setMimetype(bild.getMimeType(beitrag));
177       cont.setIsDirectory(beitrag.isDirectory());
178       cont.setIsHidden(beitrag.isHidden());
179       cont.setLastModified(beitrag.lastModified());
180       cont.setLength(beitrag.length());
181       
182       /*
183         den 'https://..'-Teil bis vor dem 
184         ContextPath ermitteln
185       */
186       StringBuffer requestUrl = getRequest().getRequestURL();
187       String contextPath = getRequest().getContextPath();
188       int pos = requestUrl.indexOf(contextPath);
189       
190       /*
191         den Teil des Pfades ermitteln, der zwischen dem 
192         ContextPath zum oeffentlichen Ordner und dem Dateiname 
193         steht
194       */
195       String absolutePath = beitrag.getAbsolutePath();
196       absolutePath = absolutePath.replace(beitrag.getName(), "");
197       absolutePath = absolutePath.replace(pubDirName, "");
198       String part = relativePath.replace("/data", "");
199       int pos2 = absolutePath.indexOf(part);
200       String mittelteil = absolutePath.substring(pos2);
201       mittelteil = mittelteil.replace(part, "");
202       cont.setBase(requestUrl.substring(0, pos));
203       
204       cont.setUrl(/*requestUrl.substring(0, pos) + "/data" + */ mittelteil + beitrag.getName());
205       files.add(cont);
206     }
207     return files;
208   } 
d14d78 209   
c509a0 210   public FileRef newFolder(String relPath, String folderName) {
eb2a2d 211     if (!relPath.startsWith(".")) {
U 212       logger.finer(relPath);
213       String targetPath = null;
214       if(relPath.startsWith(PUB_DIR_NAME)) {
215         targetPath = PUB_DIR_PATH + getUserName() + "/" + relPath.substring(PUB_DIR_NAME.length()) + "/" + folderName;
216       } else if(relPath.startsWith(HOME_DIR_NAME)) {
217         targetPath = HOME_DIR_PATH + getUserName() + "/" + relPath.substring(HOME_DIR_NAME.length()) + "/" + folderName;
218       } else {
219         // kann eigentlich nicht sein..
220       }
221       logger.finer(targetPath);
222       File targetDir = new File(getBase().getAbsolutePath(), targetPath);
223       targetDir.mkdirs();
224       return new FileRef(targetDir.getAbsolutePath(), true);
c509a0 225     } else {
eb2a2d 226       return null;
c509a0 227     }
5dfab6 228   }
U 229   
3ad4db 230   public String getCode(String relPath, String fileName) {
U 231     String code = null;
eb2a2d 232     if (!relPath.startsWith(".")) {
U 233       Object p = getRequest().getUserPrincipal();
234       if (p instanceof Principal) {
235         Reader reader = null;
3ad4db 236         try {
eb2a2d 237           File targetFile = new File(getTargetDir(relPath), fileName);
U 238
239           //reader = new InputStreamReader(new FileInputStream(targetFile), "UTF8");
240           reader = new FileReader(targetFile);
241           StringBuffer buf = new StringBuffer();
242           char[] readBuffer = new char[1024];
243           int charsRead = reader.read(readBuffer);
244           while (charsRead > -1) {
245             buf.append(readBuffer, 0, charsRead);
246             charsRead = reader.read(readBuffer);
247           }
248           code = buf.toString();
249         } catch (FileNotFoundException ex) {
250           Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
3ad4db 251         } catch (IOException ex) {
U 252           Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
eb2a2d 253         } finally {
U 254           try {
255             reader.close();
256           } catch (IOException ex) {
257             Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
258           }
3ad4db 259         }
eb2a2d 260
3ad4db 261       }
eb2a2d 262     }
3ad4db 263     return code;
U 264   }
265   
663ee9 266   public String renameFile(String relPath, String fname, String newName) {
eb2a2d 267     if (!relPath.startsWith(".")) {
U 268       File targetDir = getTargetDir(relPath);
269       File file = new File(targetDir, fname);
270       file.renameTo(new File(targetDir, newName));
271       return fname + " umbenannt zu " + newName;
272     } else {
273       return "Pfad nicht erlaubt.";
274     }
663ee9 275   }
U 276   
fc1897 277   public String deleteFiles(String relPath, List fileNames) {
U 278     String result = null;
279     try {
280       logger.fine(fileNames.toString());
eb2a2d 281       if (!relPath.startsWith(".")) {
U 282         File targetDir = getTargetDir(relPath);
283         for(int i=0; i < fileNames.size(); i++) {
284           Object o = fileNames.get(i);
285           if(o instanceof ArrayList) {
286             ArrayList al = (ArrayList) o;
287             logger.fine(al.get(0).toString());
288             File targetFile = new File(targetDir, al.get(0).toString());
289             logger.fine(targetFile.getAbsolutePath());
290             if(targetFile.isDirectory()) {
291               FileUtils.deleteDirectory(targetFile);
292             } else {
293               targetFile.delete();
294             }
5bfd34 295           }
fc1897 296         }
eb2a2d 297         result = "deleted";
fc1897 298       }
U 299     } catch (Throwable ex) {
300       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
301     }
302     return result;
303   }
304   
9e2964 305   public String copyFiles(String fromPath, String toPath, List fileNames) {
fab629 306     return copyOrMoveFiles(fromPath, toPath, fileNames, OP_COPY);
9e2964 307   }
U 308   
309   public String moveFiles(String fromPath, String toPath, List fileNames) {
fab629 310     return copyOrMoveFiles(fromPath, toPath, fileNames, OP_MOVE);
U 311   }
312   
313   private String copyOrMoveFiles(String fromPath, String toPath, List fileNames, int operation) {
5bfd34 314     String result = null;
U 315     try {
eb2a2d 316       if (!fromPath.startsWith(".")) {
U 317         File srcDir = getTargetDir(fromPath);
318         File targetDir = getTargetDir(toPath);
319         Iterator i = fileNames.iterator();
320         while(i.hasNext()) {
321           Object o = i.next();
322           if (o instanceof ArrayList) {
323             ArrayList al = (ArrayList) o;
324             File srcFile = new File(srcDir, al.get(0).toString());
325             if(srcFile.isDirectory()) {
326               if(operation == OP_MOVE) {
327                 FileUtils.moveDirectoryToDirectory(srcFile, targetDir, false);
328               } else {
329                 FileUtils.copyDirectoryToDirectory(srcFile, targetDir);
330               }
fab629 331             } else {
eb2a2d 332               if(operation == OP_MOVE) {
U 333                 FileUtils.moveFileToDirectory(srcFile, targetDir, false);
334               } else {
335                 FileUtils.copyFileToDirectory(srcFile, targetDir);              
336               }
fab629 337             }
5bfd34 338           }
U 339         }
340       }
341     } catch (IOException ex) {
342       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
343     }
344     return result;
9e2964 345   }
U 346   
47e9d4 347   public FileRef saveTextFileAs(String relPath, String fileName, String contents) {
U 348     FileRef savedFile = null;
349     logger.fine(relPath + " " + fileName);
eb2a2d 350     if (!relPath.startsWith(".")) {
U 351       //FileRef datenRef = getBase();
352       Object p = getRequest().getUserPrincipal();
353       if(p instanceof Principal) {
354         File targetFile = new File(getTargetDir(relPath), fileName);
355         if(targetFile.exists()) {
356           targetFile = getNewFileName(targetFile);
357         } else {
358           targetFile.getParentFile().mkdirs();
359         }
360         saveToFile(targetFile, contents);
47e9d4 361       }
U 362     }
363     return savedFile;
364   }
365   
366   private File getNewFileName(File file) {
367     File dir = file.getParentFile();
368     String targetName = file.getName();
369     logger.fine("targetName: " + targetName);
370     String ext = "";
371     int dotpos = targetName.indexOf(".");
372     if(dotpos > -1) {
373       ext = targetName.substring(dotpos);
374       targetName = targetName.substring(0, dotpos);
375     }
376     logger.fine("targetName: " + targetName + ", ext: " + ext);
377     int i = 1;
378     while(file.exists()) {
379       StringBuffer buf = new StringBuffer();
380       buf.append(targetName);
381       buf.append("-");
382       buf.append(i);
383       if(ext.length() > 0) {
384         buf.append(ext);
385       }
386       file = new File(dir, buf.toString());
387       i++;
388     }
389     logger.fine("new file: " + file.getName());
390     return file;
942d63 391   }  
47e9d4 392   
U 393   private FileRef saveToFile(File targetFile, String contents) {
ea7193 394     FileRef savedFile = null;
e5ff42 395     try {
47e9d4 396       targetFile.createNewFile();
U 397       FileWriter w = new FileWriter(targetFile);
942d63 398       //w.write(StringEscapeUtils.unescapeHtml(contents));
47e9d4 399       w.write(contents);
U 400       w.flush();
401       w.close();
402       savedFile = new FileRef(
403               targetFile.getAbsolutePath(),
404               targetFile.isDirectory(),
405               targetFile.isHidden(),
406               targetFile.lastModified(),
407               targetFile.length());
e5ff42 408     } catch (IOException ex) {
47e9d4 409       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
U 410     }
411     return savedFile;
412   }
413   
414   public FileRef saveTextFile(String relPath, String fileName, String contents) {
415     FileRef savedFile = null;
416     logger.fine(relPath + " " + fileName);
eb2a2d 417     if (!relPath.startsWith(".")) {    
U 418       //FileRef datenRef = getBase();
419       Object p = getRequest().getUserPrincipal();
420       if(p instanceof Principal) {
421         File targetFile = new File(getTargetDir(relPath), fileName);
422         if(targetFile.exists()) {
423           /*
424             muss delete() sein?
425             pruefen: ueberschreibt der FileWriter den alteen Inhalt oder 
426             entsteht eine unerwuenschte Mischung aus altem und neuem 
427             Inhalt?
428           */
429           targetFile.delete();
430         } else {
431           targetFile.getParentFile().mkdirs();
432         }
433         saveToFile(targetFile, contents);
47e9d4 434       }
e5ff42 435     }
ea7193 436     return savedFile;
U 437   }
438b16 438   
U 439   public String bildVerkleinern(String relPath, String bildName) {
eb2a2d 440     if (!relPath.startsWith(".")) {
U 441       File dir = getTargetDir(relPath);
442       File original = new File(dir, bildName);
443       Bild bild = new Bild();
444       //for (int i = 0; i < Bild.GR.length; i++) {
445
438b16 446       //int gr = bild.getVariantenGroesse(i);
U 447       String ext = "";
448       String nurname = bildName;
449       int dotpos = bildName.indexOf(".");
450       if (dotpos > -1) {
451         ext = bildName.substring(dotpos);
452         nurname = bildName.substring(0, dotpos);
453       }
eb2a2d 454
bb9f8c 455           // 120, 240, 500, 700, 1200
U 456
457       
458       for (int i = 0; i < Bild.GR.length; i++) {
459         StringBuffer buf = new StringBuffer();
460         buf.append(nurname);
461         buf.append(bild.getVariantenName(i));
462         buf.append(ext);
463         File newImgFile = new File(dir, buf.toString());
464         try {
465           Thumbnails.of(original)
466                   .size(bild.getVariantenGroesse(i), bild.getVariantenGroesse(i))
467                   .keepAspectRatio(true)
8a8152 468                   .outputQuality(0.7)
bb9f8c 469                   .toFile(newImgFile);
U 470         } catch (IOException ex) {
471           logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
472         }
473       }
eb2a2d 474       return "ok";
U 475     } else {
476       return "Pfad micht erlaubt.";
477     }
438b16 478   }
6bd2c1 479   
bb9f8c 480   public String bildRotieren(String relPath, String bildName) {
U 481     if (!relPath.startsWith(".")) {
482       File dir = getTargetDir(relPath);
483       File original = new File(dir, bildName);
484
485       String ext = "";
486       String nurname = bildName;
487       int dotpos = bildName.indexOf(".");
488       if (dotpos > -1) {
489         ext = bildName.substring(dotpos);
490         nurname = bildName.substring(0, dotpos);
491       }
492
493       StringBuffer buf = new StringBuffer();
494       buf.append(nurname);
495       buf.append("-rot");
496       buf.append(ext);
497       File newImgFile = new File(dir, buf.toString());
498       
499       logger.fine("original: " + original.getAbsolutePath() + " newImgFile: " + newImgFile.getAbsolutePath());
500
501       try {
502         Thumbnails.of(original)
503                 .scale(1)
504                 .rotate(90)
505                 .toFile(newImgFile);
506       } catch (IOException ex) {
507         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
508       }
509
510
511       return "ok";
512     } else {
513       return "Pfad micht erlaubt.";
514     }
515   }
af9930 516   
U 517   /* --------- ZIP entpacken ---------------- */
518   
6bd2c1 519   public String extractZipfile(String relPath, String filename) {
eb2a2d 520     String result = null;
U 521     if (!relPath.startsWith(".")) {    
522       try {
523         File targetDir = getTargetDir(relPath);
524         File archive = new File(targetDir, filename);
525         if(extract(archive)) {
526           result = "ok";
527         } else {
528           result = "error while extracting";
529         }
530       } catch(Exception ex) {
531         result = ex.getLocalizedMessage();
532         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
6bd2c1 533       }
U 534     }
535     return result;
536   }
537   
538   /**
539      * extract a given ZIP archive to the folder respective archive resides in
540      * @param archive  the archive to extract
541      * @throws Exception
542      */
543     private boolean extract(File archive) throws Exception {
544         ZipFile zipfile = new ZipFile(archive);
545         Enumeration en = zipfile.entries();
546         while(en.hasMoreElements()) {
547             ZipEntry zipentry = (ZipEntry) en.nextElement();
548             unzip(zipfile, zipentry, archive.getParent());
549         }
550         zipfile.close();
551         return true;
552     }
553
554     /**
555      * unzip a given entry of a given zip file to a given location
556      * @param zipfile  the zip file to read an entry from
557      * @param zipentry  the zip entry to read
558      * @param destPath  the path to the destination location for the extracted content
559      * @throws IOException
560      */
561     private void unzip(ZipFile zipfile, ZipEntry zipentry, String destPath) throws IOException {
562         byte buf[] = new byte[1024];
563         InputStream is = zipfile.getInputStream(zipentry);
564         String outFileName = destPath + File.separator + zipentry.getName();
565         File file = new File(outFileName);
566         if(!zipentry.isDirectory()) {
567             file.getParentFile().mkdirs();
568             if(!file.exists())
569                 file.createNewFile();
570             FileOutputStream fos = new FileOutputStream(file);
571             int i = is.read(buf, 0, 1024);
572             while(i > -1) {
573                 fos.write(buf, 0, i);
574                 i = is.read(buf, 0, 1024);
575             }
576             fos.close();
577             is.close();
578         } else {
579             file.mkdirs();
580         }
581     }
582
af9930 583   /* ------------- Ornder als ZIP packen --------------- */
U 584   
585   public String packFolder(String relPath) {
586     if (!relPath.startsWith(".")) {    
587       try {
588         File targetDir = getTargetDir(relPath);
589         File parentDir = targetDir.getParentFile();
590         StringBuffer fname = new StringBuffer();
591         fname.append(targetDir.getName());
592         fname.append(".zip");
593         File archiveFile = new File(parentDir, fname.toString());
594         FileRef folderToPack = new FileRef(targetDir.getAbsolutePath());
595         FileRef archive = new FileRef(archiveFile.getAbsolutePath());
596         pack(folderToPack, archive);
597         return "ok";
598       } catch(Exception ex) {
599         String result = ex.getLocalizedMessage();
600         logger.log(Level.SEVERE, result, ex);
601         return result;
602       }
603     } else {
604       return "Falsche relative Pfadangabe";
605     }
606   }
607   
608     /**
609      * pack the contents of a given folder into a new ZIP compressed archive
610      * @param folder  the folder to pack
611      * @param archive  the archive to create from the given files
612      * @throws Exception
613      */
614     private boolean pack(FileRef folder, FileRef archive) throws Exception {
615         File file = new File(archive.getAbsolutePath());
616         FileOutputStream fos = new FileOutputStream(file);
617         CheckedOutputStream checksum = new CheckedOutputStream(fos, new Adler32());
618         ZipOutputStream zos = new ZipOutputStream(checksum);
619         pack(zos, folder.getAbsolutePath(), "");
620         zos.flush();
621         zos.finish();
622         zos.close();
623         fos.flush();
624         fos.close();
625         return true;
626     }
627
628     /**
629      * go through the given file structure recursively
630      * @param zipFile  the ZIP file to write to
631      * @param srcDir  the directory to pack during this cycle
632      * @param subDir  the subdirectory to append to names of file entries inside the archive
633      * @throws IOException
634      */
635     private void pack(ZipOutputStream zipFile, String srcDir, String subDir) throws IOException {
636         File[] files = new File(srcDir).listFiles();
637         for(int i = 0; i < files.length; i++) {
638             if(files[i].isDirectory()) {
639                 pack(zipFile, files[i].getAbsolutePath(), subDir + File.separator + files[i].getName());
640             }
641             else {
642                 packFile(zipFile, subDir, files[i]);
643             }
644         }
645     }
646
647     /**
648      * pack a given file
649      * @param zipFile  the ZIP archive to pack to
650      * @param dir  the directory name to append to name of file entry inside archive
651      * @param file  the file to pack
652      * @throws IOException
653      */
654     private void packFile(ZipOutputStream zipFile, String dir, File file) throws IOException
655     {
656         FileInputStream fileinputstream = new FileInputStream(file);
657         byte buf[] = new byte[fileinputstream.available()];
658         fileinputstream.read(buf);
659         String dirWithSlashes = dir.replace('\\', '/');
660         //System.out.println("zipping " + dirWithSlashes + "/" + file.getName());
661         ZipEntry ze = new ZipEntry(dirWithSlashes + "/" + file.getName());
662         ze.setMethod(ZipEntry.DEFLATED);
663         zipFile.putNextEntry(ze);
664         zipFile.write(buf, 0, buf.length);
665         zipFile.closeEntry();
666         fileinputstream.close();
667     }
668
6bd2c1 669   
438b16 670
5efd94 671   /* ---- Hilfsfunktionen ---- */
ea7193 672   
547755 673 }