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