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