Dateiverwaltung für die WebBox
ulrich
2018-04-04 4e2a82fb9cdfec92b29065555c9d8ce77f705887
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;
bb9f8c 24 import de.uhilger.wbx.Bild;
e639c2 25 import de.uhilger.wbx.WbxUtils;
4e2a82 26 import de.uhilger.wbx.data.Inhalt;
8e51b7 27 import java.io.File;
af9930 28 import java.io.FileInputStream;
3ad4db 29 import java.io.FileNotFoundException;
6bd2c1 30 import java.io.FileOutputStream;
3ad4db 31 import java.io.FileReader;
e5ff42 32 import java.io.FileWriter;
U 33 import java.io.IOException;
6bd2c1 34 import java.io.InputStream;
fab80c 35 import java.io.Reader;
e5ff42 36 import java.security.Principal;
7342b1 37 import java.util.ArrayList;
d14d78 38 import java.util.Arrays;
6bd2c1 39 import java.util.Enumeration;
5bfd34 40 import java.util.Iterator;
7342b1 41 import java.util.List;
e5ff42 42 import java.util.logging.Level;
8e51b7 43 import java.util.logging.Logger;
af9930 44 import java.util.zip.Adler32;
U 45 import java.util.zip.CheckedOutputStream;
6bd2c1 46 import java.util.zip.ZipEntry;
U 47 import java.util.zip.ZipFile;
af9930 48 import java.util.zip.ZipOutputStream;
4e2a82 49 import javax.servlet.http.HttpServletRequest;
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   }
4e2a82 149
U 150   public List<Inhalt> collectFiles(String relativePath, int maxTiefe, int maxAnzahl) {
151     WbxUtils wu = new WbxUtils();
152     HttpServletRequest req = getRequest();
153     String requestUrl = req.getRequestURL().toString();
154     String contextPath = req.getContextPath();
155     return wu.collectFiles(requestUrl, contextPath, relativePath, maxTiefe, maxAnzahl);
156   }
157
e639c2 158   /**
U 159    * Wie list nur mit drill down
160    * 
161    * TODO '/data' muss noch variabel gestaltet werden
162    * 
163    * @param relativePath
164    * @param maxTiefe
165    * @param maxAnzahl
166    * @return 
167    */
e2f0bb 168   /*
U 169     Beispiel
170     http://localhost:8097/file-cms/svc?c=de.uhilger.filecms.api.FileMgr&m=collectFiles&p=/data/admin/journal/&p=2&p=200&f=JSONNICE
171   */
4e2a82 172   public List<Inhalt> collectFilesAlt(String relativePath, int maxTiefe, int maxAnzahl) {
e639c2 173     Bild bild = new Bild();
U 174     WbxUtils wu = new WbxUtils();
4e2a82 175     String basis = wu.getJNDIParameter(WbxUtils.WBX_FILE_BASE, WbxUtils.EMPTY_STRING);
e639c2 176     String pubDirName = wu.getJNDIParameter(WbxUtils.WBX_PUB_DIR_NAME, WbxUtils.WBX_DEFAULT_PUB_DIR_NAME);
U 177     String relPath = relativePath.replace("/data", pubDirName);
178     String absPath = basis + relPath;
179     
180     ArrayList beitraege = new ArrayList();
181     ArrayList<Inhalt> files = new ArrayList<>();
182     wu.collectFiles(new File(absPath), 0, beitraege, maxTiefe, maxAnzahl);
183
184     Iterator i = beitraege.iterator();
185     while(i.hasNext()) {
186       File beitrag = (File) i.next();
187       Inhalt cont = new Inhalt();
188       cont.setMimetype(bild.getMimeType(beitrag));
189       cont.setIsDirectory(beitrag.isDirectory());
190       cont.setIsHidden(beitrag.isHidden());
191       cont.setLastModified(beitrag.lastModified());
192       cont.setLength(beitrag.length());
193       
194       /*
195         den 'https://..'-Teil bis vor dem 
196         ContextPath ermitteln
197       */
198       StringBuffer requestUrl = getRequest().getRequestURL();
199       String contextPath = getRequest().getContextPath();
200       int pos = requestUrl.indexOf(contextPath);
201       
202       /*
203         den Teil des Pfades ermitteln, der zwischen dem 
204         ContextPath zum oeffentlichen Ordner und dem Dateiname 
205         steht
206       */
207       String absolutePath = beitrag.getAbsolutePath();
208       absolutePath = absolutePath.replace(beitrag.getName(), "");
209       absolutePath = absolutePath.replace(pubDirName, "");
210       String part = relativePath.replace("/data", "");
211       int pos2 = absolutePath.indexOf(part);
212       String mittelteil = absolutePath.substring(pos2);
213       mittelteil = mittelteil.replace(part, "");
214       cont.setBase(requestUrl.substring(0, pos));
215       
216       cont.setUrl(/*requestUrl.substring(0, pos) + "/data" + */ mittelteil + beitrag.getName());
217       files.add(cont);
218     }
219     return files;
220   } 
d14d78 221   
c509a0 222   public FileRef newFolder(String relPath, String folderName) {
eb2a2d 223     if (!relPath.startsWith(".")) {
U 224       logger.finer(relPath);
225       String targetPath = null;
226       if(relPath.startsWith(PUB_DIR_NAME)) {
227         targetPath = PUB_DIR_PATH + getUserName() + "/" + relPath.substring(PUB_DIR_NAME.length()) + "/" + folderName;
228       } else if(relPath.startsWith(HOME_DIR_NAME)) {
229         targetPath = HOME_DIR_PATH + getUserName() + "/" + relPath.substring(HOME_DIR_NAME.length()) + "/" + folderName;
230       } else {
231         // kann eigentlich nicht sein..
232       }
233       logger.finer(targetPath);
234       File targetDir = new File(getBase().getAbsolutePath(), targetPath);
235       targetDir.mkdirs();
236       return new FileRef(targetDir.getAbsolutePath(), true);
c509a0 237     } else {
eb2a2d 238       return null;
c509a0 239     }
5dfab6 240   }
U 241   
3ad4db 242   public String getCode(String relPath, String fileName) {
U 243     String code = null;
eb2a2d 244     if (!relPath.startsWith(".")) {
U 245       Object p = getRequest().getUserPrincipal();
246       if (p instanceof Principal) {
247         Reader reader = null;
3ad4db 248         try {
eb2a2d 249           File targetFile = new File(getTargetDir(relPath), fileName);
U 250
251           //reader = new InputStreamReader(new FileInputStream(targetFile), "UTF8");
252           reader = new FileReader(targetFile);
253           StringBuffer buf = new StringBuffer();
254           char[] readBuffer = new char[1024];
255           int charsRead = reader.read(readBuffer);
256           while (charsRead > -1) {
257             buf.append(readBuffer, 0, charsRead);
258             charsRead = reader.read(readBuffer);
259           }
260           code = buf.toString();
261         } catch (FileNotFoundException ex) {
262           Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
3ad4db 263         } catch (IOException ex) {
U 264           Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
eb2a2d 265         } finally {
U 266           try {
267             reader.close();
268           } catch (IOException ex) {
269             Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
270           }
3ad4db 271         }
eb2a2d 272
3ad4db 273       }
eb2a2d 274     }
3ad4db 275     return code;
U 276   }
277   
663ee9 278   public String renameFile(String relPath, String fname, String newName) {
eb2a2d 279     if (!relPath.startsWith(".")) {
U 280       File targetDir = getTargetDir(relPath);
281       File file = new File(targetDir, fname);
282       file.renameTo(new File(targetDir, newName));
283       return fname + " umbenannt zu " + newName;
284     } else {
285       return "Pfad nicht erlaubt.";
286     }
663ee9 287   }
U 288   
fc1897 289   public String deleteFiles(String relPath, List fileNames) {
U 290     String result = null;
291     try {
292       logger.fine(fileNames.toString());
eb2a2d 293       if (!relPath.startsWith(".")) {
U 294         File targetDir = getTargetDir(relPath);
295         for(int i=0; i < fileNames.size(); i++) {
296           Object o = fileNames.get(i);
297           if(o instanceof ArrayList) {
298             ArrayList al = (ArrayList) o;
299             logger.fine(al.get(0).toString());
300             File targetFile = new File(targetDir, al.get(0).toString());
301             logger.fine(targetFile.getAbsolutePath());
302             if(targetFile.isDirectory()) {
303               FileUtils.deleteDirectory(targetFile);
304             } else {
305               targetFile.delete();
306             }
5bfd34 307           }
fc1897 308         }
eb2a2d 309         result = "deleted";
fc1897 310       }
U 311     } catch (Throwable ex) {
312       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
313     }
314     return result;
315   }
316   
9e2964 317   public String copyFiles(String fromPath, String toPath, List fileNames) {
fab629 318     return copyOrMoveFiles(fromPath, toPath, fileNames, OP_COPY);
9e2964 319   }
U 320   
321   public String moveFiles(String fromPath, String toPath, List fileNames) {
fab629 322     return copyOrMoveFiles(fromPath, toPath, fileNames, OP_MOVE);
U 323   }
324   
325   private String copyOrMoveFiles(String fromPath, String toPath, List fileNames, int operation) {
5bfd34 326     String result = null;
U 327     try {
eb2a2d 328       if (!fromPath.startsWith(".")) {
U 329         File srcDir = getTargetDir(fromPath);
330         File targetDir = getTargetDir(toPath);
331         Iterator i = fileNames.iterator();
332         while(i.hasNext()) {
333           Object o = i.next();
334           if (o instanceof ArrayList) {
335             ArrayList al = (ArrayList) o;
336             File srcFile = new File(srcDir, al.get(0).toString());
337             if(srcFile.isDirectory()) {
338               if(operation == OP_MOVE) {
339                 FileUtils.moveDirectoryToDirectory(srcFile, targetDir, false);
340               } else {
341                 FileUtils.copyDirectoryToDirectory(srcFile, targetDir);
342               }
fab629 343             } else {
eb2a2d 344               if(operation == OP_MOVE) {
U 345                 FileUtils.moveFileToDirectory(srcFile, targetDir, false);
346               } else {
347                 FileUtils.copyFileToDirectory(srcFile, targetDir);              
348               }
fab629 349             }
5bfd34 350           }
U 351         }
352       }
353     } catch (IOException ex) {
354       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
355     }
356     return result;
9e2964 357   }
U 358   
47e9d4 359   public FileRef saveTextFileAs(String relPath, String fileName, String contents) {
U 360     FileRef savedFile = null;
361     logger.fine(relPath + " " + fileName);
eb2a2d 362     if (!relPath.startsWith(".")) {
U 363       //FileRef datenRef = getBase();
364       Object p = getRequest().getUserPrincipal();
365       if(p instanceof Principal) {
366         File targetFile = new File(getTargetDir(relPath), fileName);
367         if(targetFile.exists()) {
368           targetFile = getNewFileName(targetFile);
369         } else {
370           targetFile.getParentFile().mkdirs();
371         }
372         saveToFile(targetFile, contents);
47e9d4 373       }
U 374     }
375     return savedFile;
376   }
377   
378   private File getNewFileName(File file) {
379     File dir = file.getParentFile();
380     String targetName = file.getName();
381     logger.fine("targetName: " + targetName);
382     String ext = "";
383     int dotpos = targetName.indexOf(".");
384     if(dotpos > -1) {
385       ext = targetName.substring(dotpos);
386       targetName = targetName.substring(0, dotpos);
387     }
388     logger.fine("targetName: " + targetName + ", ext: " + ext);
389     int i = 1;
390     while(file.exists()) {
391       StringBuffer buf = new StringBuffer();
392       buf.append(targetName);
393       buf.append("-");
394       buf.append(i);
395       if(ext.length() > 0) {
396         buf.append(ext);
397       }
398       file = new File(dir, buf.toString());
399       i++;
400     }
401     logger.fine("new file: " + file.getName());
402     return file;
942d63 403   }  
47e9d4 404   
U 405   private FileRef saveToFile(File targetFile, String contents) {
ea7193 406     FileRef savedFile = null;
e5ff42 407     try {
47e9d4 408       targetFile.createNewFile();
U 409       FileWriter w = new FileWriter(targetFile);
942d63 410       //w.write(StringEscapeUtils.unescapeHtml(contents));
47e9d4 411       w.write(contents);
U 412       w.flush();
413       w.close();
414       savedFile = new FileRef(
415               targetFile.getAbsolutePath(),
416               targetFile.isDirectory(),
417               targetFile.isHidden(),
418               targetFile.lastModified(),
419               targetFile.length());
e5ff42 420     } catch (IOException ex) {
47e9d4 421       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
U 422     }
423     return savedFile;
424   }
425   
426   public FileRef saveTextFile(String relPath, String fileName, String contents) {
427     FileRef savedFile = null;
428     logger.fine(relPath + " " + fileName);
eb2a2d 429     if (!relPath.startsWith(".")) {    
U 430       //FileRef datenRef = getBase();
431       Object p = getRequest().getUserPrincipal();
432       if(p instanceof Principal) {
433         File targetFile = new File(getTargetDir(relPath), fileName);
434         if(targetFile.exists()) {
435           /*
436             muss delete() sein?
437             pruefen: ueberschreibt der FileWriter den alteen Inhalt oder 
438             entsteht eine unerwuenschte Mischung aus altem und neuem 
439             Inhalt?
440           */
441           targetFile.delete();
442         } else {
443           targetFile.getParentFile().mkdirs();
444         }
445         saveToFile(targetFile, contents);
47e9d4 446       }
e5ff42 447     }
ea7193 448     return savedFile;
U 449   }
438b16 450   
U 451   public String bildVerkleinern(String relPath, String bildName) {
eb2a2d 452     if (!relPath.startsWith(".")) {
U 453       File dir = getTargetDir(relPath);
454       File original = new File(dir, bildName);
455       Bild bild = new Bild();
456       //for (int i = 0; i < Bild.GR.length; i++) {
457
438b16 458       //int gr = bild.getVariantenGroesse(i);
U 459       String ext = "";
460       String nurname = bildName;
461       int dotpos = bildName.indexOf(".");
462       if (dotpos > -1) {
463         ext = bildName.substring(dotpos);
464         nurname = bildName.substring(0, dotpos);
465       }
eb2a2d 466
bb9f8c 467           // 120, 240, 500, 700, 1200
U 468
469       
470       for (int i = 0; i < Bild.GR.length; i++) {
471         StringBuffer buf = new StringBuffer();
472         buf.append(nurname);
473         buf.append(bild.getVariantenName(i));
474         buf.append(ext);
475         File newImgFile = new File(dir, buf.toString());
476         try {
477           Thumbnails.of(original)
478                   .size(bild.getVariantenGroesse(i), bild.getVariantenGroesse(i))
479                   .keepAspectRatio(true)
8a8152 480                   .outputQuality(0.7)
bb9f8c 481                   .toFile(newImgFile);
U 482         } catch (IOException ex) {
483           logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
484         }
485       }
eb2a2d 486       return "ok";
U 487     } else {
488       return "Pfad micht erlaubt.";
489     }
438b16 490   }
6bd2c1 491   
bb9f8c 492   public String bildRotieren(String relPath, String bildName) {
U 493     if (!relPath.startsWith(".")) {
494       File dir = getTargetDir(relPath);
495       File original = new File(dir, bildName);
496
497       String ext = "";
498       String nurname = bildName;
499       int dotpos = bildName.indexOf(".");
500       if (dotpos > -1) {
501         ext = bildName.substring(dotpos);
502         nurname = bildName.substring(0, dotpos);
503       }
504
505       StringBuffer buf = new StringBuffer();
506       buf.append(nurname);
507       buf.append("-rot");
508       buf.append(ext);
509       File newImgFile = new File(dir, buf.toString());
510       
511       logger.fine("original: " + original.getAbsolutePath() + " newImgFile: " + newImgFile.getAbsolutePath());
512
513       try {
514         Thumbnails.of(original)
515                 .scale(1)
516                 .rotate(90)
517                 .toFile(newImgFile);
518       } catch (IOException ex) {
519         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
520       }
521
522
523       return "ok";
524     } else {
525       return "Pfad micht erlaubt.";
526     }
527   }
af9930 528   
U 529   /* --------- ZIP entpacken ---------------- */
530   
6bd2c1 531   public String extractZipfile(String relPath, String filename) {
eb2a2d 532     String result = null;
U 533     if (!relPath.startsWith(".")) {    
534       try {
535         File targetDir = getTargetDir(relPath);
536         File archive = new File(targetDir, filename);
537         if(extract(archive)) {
538           result = "ok";
539         } else {
540           result = "error while extracting";
541         }
542       } catch(Exception ex) {
543         result = ex.getLocalizedMessage();
544         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
6bd2c1 545       }
U 546     }
547     return result;
548   }
549   
550   /**
551      * extract a given ZIP archive to the folder respective archive resides in
552      * @param archive  the archive to extract
553      * @throws Exception
554      */
555     private boolean extract(File archive) throws Exception {
556         ZipFile zipfile = new ZipFile(archive);
557         Enumeration en = zipfile.entries();
558         while(en.hasMoreElements()) {
559             ZipEntry zipentry = (ZipEntry) en.nextElement();
560             unzip(zipfile, zipentry, archive.getParent());
561         }
562         zipfile.close();
563         return true;
564     }
565
566     /**
567      * unzip a given entry of a given zip file to a given location
568      * @param zipfile  the zip file to read an entry from
569      * @param zipentry  the zip entry to read
570      * @param destPath  the path to the destination location for the extracted content
571      * @throws IOException
572      */
573     private void unzip(ZipFile zipfile, ZipEntry zipentry, String destPath) throws IOException {
574         byte buf[] = new byte[1024];
575         InputStream is = zipfile.getInputStream(zipentry);
576         String outFileName = destPath + File.separator + zipentry.getName();
577         File file = new File(outFileName);
578         if(!zipentry.isDirectory()) {
579             file.getParentFile().mkdirs();
580             if(!file.exists())
581                 file.createNewFile();
582             FileOutputStream fos = new FileOutputStream(file);
583             int i = is.read(buf, 0, 1024);
584             while(i > -1) {
585                 fos.write(buf, 0, i);
586                 i = is.read(buf, 0, 1024);
587             }
588             fos.close();
589             is.close();
590         } else {
591             file.mkdirs();
592         }
593     }
594
af9930 595   /* ------------- Ornder als ZIP packen --------------- */
U 596   
597   public String packFolder(String relPath) {
598     if (!relPath.startsWith(".")) {    
599       try {
600         File targetDir = getTargetDir(relPath);
601         File parentDir = targetDir.getParentFile();
602         StringBuffer fname = new StringBuffer();
603         fname.append(targetDir.getName());
604         fname.append(".zip");
605         File archiveFile = new File(parentDir, fname.toString());
606         FileRef folderToPack = new FileRef(targetDir.getAbsolutePath());
607         FileRef archive = new FileRef(archiveFile.getAbsolutePath());
608         pack(folderToPack, archive);
609         return "ok";
610       } catch(Exception ex) {
611         String result = ex.getLocalizedMessage();
612         logger.log(Level.SEVERE, result, ex);
613         return result;
614       }
615     } else {
616       return "Falsche relative Pfadangabe";
617     }
618   }
619   
620     /**
621      * pack the contents of a given folder into a new ZIP compressed archive
622      * @param folder  the folder to pack
623      * @param archive  the archive to create from the given files
624      * @throws Exception
625      */
626     private boolean pack(FileRef folder, FileRef archive) throws Exception {
627         File file = new File(archive.getAbsolutePath());
628         FileOutputStream fos = new FileOutputStream(file);
629         CheckedOutputStream checksum = new CheckedOutputStream(fos, new Adler32());
630         ZipOutputStream zos = new ZipOutputStream(checksum);
631         pack(zos, folder.getAbsolutePath(), "");
632         zos.flush();
633         zos.finish();
634         zos.close();
635         fos.flush();
636         fos.close();
637         return true;
638     }
639
640     /**
641      * go through the given file structure recursively
642      * @param zipFile  the ZIP file to write to
643      * @param srcDir  the directory to pack during this cycle
644      * @param subDir  the subdirectory to append to names of file entries inside the archive
645      * @throws IOException
646      */
647     private void pack(ZipOutputStream zipFile, String srcDir, String subDir) throws IOException {
648         File[] files = new File(srcDir).listFiles();
649         for(int i = 0; i < files.length; i++) {
650             if(files[i].isDirectory()) {
651                 pack(zipFile, files[i].getAbsolutePath(), subDir + File.separator + files[i].getName());
652             }
653             else {
654                 packFile(zipFile, subDir, files[i]);
655             }
656         }
657     }
658
659     /**
660      * pack a given file
661      * @param zipFile  the ZIP archive to pack to
662      * @param dir  the directory name to append to name of file entry inside archive
663      * @param file  the file to pack
664      * @throws IOException
665      */
666     private void packFile(ZipOutputStream zipFile, String dir, File file) throws IOException
667     {
668         FileInputStream fileinputstream = new FileInputStream(file);
669         byte buf[] = new byte[fileinputstream.available()];
670         fileinputstream.read(buf);
671         String dirWithSlashes = dir.replace('\\', '/');
672         //System.out.println("zipping " + dirWithSlashes + "/" + file.getName());
673         ZipEntry ze = new ZipEntry(dirWithSlashes + "/" + file.getName());
674         ze.setMethod(ZipEntry.DEFLATED);
675         zipFile.putNextEntry(ze);
676         zipFile.write(buf, 0, buf.length);
677         zipFile.closeEntry();
678         fileinputstream.close();
679     }
680
6bd2c1 681   
438b16 682
5efd94 683   /* ---- Hilfsfunktionen ---- */
ea7193 684   
547755 685 }