Dateiverwaltung für die WebBox
ulrich@undisclosed
2020-04-18 584d43273547cb99ff7e26867945323280442bc5
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) {
7b4480 357                 String fname = srcFile.getName().toLowerCase();                
U 358                 if(fname.endsWith(TNServlet.JPEG) || fname.endsWith(TNServlet.JPG) || fname.endsWith(TNServlet.PNG)) {
359                   moveImgFilesToDirectory(srcFile, srcDir, targetDir, false);
360                 } else {
361                   FileUtils.moveFileToDirectory(srcFile, targetDir, false);
362                 }
eb2a2d 363               } else {
U 364                 FileUtils.copyFileToDirectory(srcFile, targetDir);              
365               }
fab629 366             }
5bfd34 367           }
U 368         }
369       }
370     } catch (IOException ex) {
371       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
372     }
373     return result;
9e2964 374   }
U 375   
7b4480 376   private void moveImgFilesToDirectory(File srcFile, File srcDir, File targetDir, boolean createDestDir) throws IOException {
U 377     String fnameext = srcFile.getName();
378     int dotpos = fnameext.lastIndexOf(DOT);
379     String fname = fnameext.substring(0, dotpos);
380     String ext = fnameext.substring(dotpos);
381     logger.fine("fname: " + fname + ", ext: " + ext);
382     FileFilter fileFilter = new WildcardFileFilter(fname + "*" + ext);
383     File[] files = srcDir.listFiles(fileFilter);
384     for (int i = 0; i < files.length; i++) {
385       logger.fine(files[i].getName());
386       FileUtils.moveFileToDirectory(files[i], targetDir, createDestDir);
387     }      
388   }
389   
47e9d4 390   public FileRef saveTextFileAs(String relPath, String fileName, String contents) {
U 391     FileRef savedFile = null;
392     logger.fine(relPath + " " + fileName);
eb2a2d 393     if (!relPath.startsWith(".")) {
U 394       //FileRef datenRef = getBase();
395       Object p = getRequest().getUserPrincipal();
396       if(p instanceof Principal) {
397         File targetFile = new File(getTargetDir(relPath), fileName);
398         if(targetFile.exists()) {
399           targetFile = getNewFileName(targetFile);
400         } else {
401           targetFile.getParentFile().mkdirs();
402         }
403         saveToFile(targetFile, contents);
47e9d4 404       }
U 405     }
406     return savedFile;
407   }
408   
409   private File getNewFileName(File file) {
410     File dir = file.getParentFile();
411     String targetName = file.getName();
412     logger.fine("targetName: " + targetName);
413     String ext = "";
414     int dotpos = targetName.indexOf(".");
415     if(dotpos > -1) {
416       ext = targetName.substring(dotpos);
417       targetName = targetName.substring(0, dotpos);
418     }
419     logger.fine("targetName: " + targetName + ", ext: " + ext);
420     int i = 1;
421     while(file.exists()) {
422       StringBuffer buf = new StringBuffer();
423       buf.append(targetName);
424       buf.append("-");
425       buf.append(i);
426       if(ext.length() > 0) {
427         buf.append(ext);
428       }
429       file = new File(dir, buf.toString());
430       i++;
431     }
432     logger.fine("new file: " + file.getName());
433     return file;
942d63 434   }  
47e9d4 435   
U 436   private FileRef saveToFile(File targetFile, String contents) {
ea7193 437     FileRef savedFile = null;
e5ff42 438     try {
47e9d4 439       targetFile.createNewFile();
U 440       FileWriter w = new FileWriter(targetFile);
942d63 441       //w.write(StringEscapeUtils.unescapeHtml(contents));
47e9d4 442       w.write(contents);
U 443       w.flush();
444       w.close();
445       savedFile = new FileRef(
446               targetFile.getAbsolutePath(),
447               targetFile.isDirectory(),
448               targetFile.isHidden(),
449               targetFile.lastModified(),
450               targetFile.length());
e5ff42 451     } catch (IOException ex) {
47e9d4 452       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
U 453     }
454     return savedFile;
455   }
456   
457   public FileRef saveTextFile(String relPath, String fileName, String contents) {
458     FileRef savedFile = null;
459     logger.fine(relPath + " " + fileName);
eb2a2d 460     if (!relPath.startsWith(".")) {    
U 461       //FileRef datenRef = getBase();
462       Object p = getRequest().getUserPrincipal();
463       if(p instanceof Principal) {
464         File targetFile = new File(getTargetDir(relPath), fileName);
465         if(targetFile.exists()) {
466           /*
467             muss delete() sein?
468             pruefen: ueberschreibt der FileWriter den alteen Inhalt oder 
469             entsteht eine unerwuenschte Mischung aus altem und neuem 
470             Inhalt?
471           */
472           targetFile.delete();
473         } else {
474           targetFile.getParentFile().mkdirs();
475         }
476         saveToFile(targetFile, contents);
47e9d4 477       }
e5ff42 478     }
ea7193 479     return savedFile;
U 480   }
438b16 481   
U 482   public String bildVerkleinern(String relPath, String bildName) {
eb2a2d 483     if (!relPath.startsWith(".")) {
U 484       File dir = getTargetDir(relPath);
485       File original = new File(dir, bildName);
486       Bild bild = new Bild();
487       //for (int i = 0; i < Bild.GR.length; i++) {
488
438b16 489       //int gr = bild.getVariantenGroesse(i);
U 490       String ext = "";
491       String nurname = bildName;
492       int dotpos = bildName.indexOf(".");
493       if (dotpos > -1) {
494         ext = bildName.substring(dotpos);
495         nurname = bildName.substring(0, dotpos);
496       }
eb2a2d 497
bb9f8c 498           // 120, 240, 500, 700, 1200
U 499
500       
501       for (int i = 0; i < Bild.GR.length; i++) {
502         StringBuffer buf = new StringBuffer();
503         buf.append(nurname);
504         buf.append(bild.getVariantenName(i));
505         buf.append(ext);
506         File newImgFile = new File(dir, buf.toString());
507         try {
508           Thumbnails.of(original)
509                   .size(bild.getVariantenGroesse(i), bild.getVariantenGroesse(i))
510                   .keepAspectRatio(true)
8a8152 511                   .outputQuality(0.7)
bb9f8c 512                   .toFile(newImgFile);
U 513         } catch (IOException ex) {
514           logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
515         }
516       }
eb2a2d 517       return "ok";
U 518     } else {
519       return "Pfad micht erlaubt.";
520     }
438b16 521   }
6bd2c1 522   
bb9f8c 523   public String bildRotieren(String relPath, String bildName) {
U 524     if (!relPath.startsWith(".")) {
525       File dir = getTargetDir(relPath);
526       File original = new File(dir, bildName);
527
528       String ext = "";
529       String nurname = bildName;
530       int dotpos = bildName.indexOf(".");
531       if (dotpos > -1) {
532         ext = bildName.substring(dotpos);
533         nurname = bildName.substring(0, dotpos);
534       }
535
536       StringBuffer buf = new StringBuffer();
537       buf.append(nurname);
538       buf.append("-rot");
539       buf.append(ext);
540       File newImgFile = new File(dir, buf.toString());
541       
542       logger.fine("original: " + original.getAbsolutePath() + " newImgFile: " + newImgFile.getAbsolutePath());
543
544       try {
545         Thumbnails.of(original)
546                 .scale(1)
547                 .rotate(90)
548                 .toFile(newImgFile);
549       } catch (IOException ex) {
550         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
551       }
552
553
554       return "ok";
555     } else {
556       return "Pfad micht erlaubt.";
557     }
558   }
af9930 559   
U 560   /* --------- ZIP entpacken ---------------- */
561   
6bd2c1 562   public String extractZipfile(String relPath, String filename) {
eb2a2d 563     String result = null;
U 564     if (!relPath.startsWith(".")) {    
565       try {
566         File targetDir = getTargetDir(relPath);
567         File archive = new File(targetDir, filename);
568         if(extract(archive)) {
569           result = "ok";
570         } else {
571           result = "error while extracting";
572         }
573       } catch(Exception ex) {
574         result = ex.getLocalizedMessage();
575         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
6bd2c1 576       }
U 577     }
578     return result;
579   }
580   
581   /**
582      * extract a given ZIP archive to the folder respective archive resides in
583      * @param archive  the archive to extract
584      * @throws Exception
585      */
586     private boolean extract(File archive) throws Exception {
587         ZipFile zipfile = new ZipFile(archive);
588         Enumeration en = zipfile.entries();
589         while(en.hasMoreElements()) {
590             ZipEntry zipentry = (ZipEntry) en.nextElement();
591             unzip(zipfile, zipentry, archive.getParent());
592         }
593         zipfile.close();
594         return true;
595     }
596
597     /**
598      * unzip a given entry of a given zip file to a given location
599      * @param zipfile  the zip file to read an entry from
600      * @param zipentry  the zip entry to read
601      * @param destPath  the path to the destination location for the extracted content
602      * @throws IOException
603      */
604     private void unzip(ZipFile zipfile, ZipEntry zipentry, String destPath) throws IOException {
605         byte buf[] = new byte[1024];
606         InputStream is = zipfile.getInputStream(zipentry);
607         String outFileName = destPath + File.separator + zipentry.getName();
608         File file = new File(outFileName);
609         if(!zipentry.isDirectory()) {
610             file.getParentFile().mkdirs();
611             if(!file.exists())
612                 file.createNewFile();
613             FileOutputStream fos = new FileOutputStream(file);
614             int i = is.read(buf, 0, 1024);
615             while(i > -1) {
616                 fos.write(buf, 0, i);
617                 i = is.read(buf, 0, 1024);
618             }
619             fos.close();
620             is.close();
621         } else {
622             file.mkdirs();
623         }
624     }
625
af9930 626   /* ------------- Ornder als ZIP packen --------------- */
U 627   
628   public String packFolder(String relPath) {
629     if (!relPath.startsWith(".")) {    
630       try {
631         File targetDir = getTargetDir(relPath);
632         File parentDir = targetDir.getParentFile();
633         StringBuffer fname = new StringBuffer();
634         fname.append(targetDir.getName());
635         fname.append(".zip");
636         File archiveFile = new File(parentDir, fname.toString());
637         FileRef folderToPack = new FileRef(targetDir.getAbsolutePath());
638         FileRef archive = new FileRef(archiveFile.getAbsolutePath());
639         pack(folderToPack, archive);
640         return "ok";
641       } catch(Exception ex) {
642         String result = ex.getLocalizedMessage();
643         logger.log(Level.SEVERE, result, ex);
644         return result;
645       }
646     } else {
647       return "Falsche relative Pfadangabe";
648     }
649   }
650   
651     /**
652      * pack the contents of a given folder into a new ZIP compressed archive
653      * @param folder  the folder to pack
654      * @param archive  the archive to create from the given files
655      * @throws Exception
656      */
657     private boolean pack(FileRef folder, FileRef archive) throws Exception {
658         File file = new File(archive.getAbsolutePath());
659         FileOutputStream fos = new FileOutputStream(file);
660         CheckedOutputStream checksum = new CheckedOutputStream(fos, new Adler32());
661         ZipOutputStream zos = new ZipOutputStream(checksum);
662         pack(zos, folder.getAbsolutePath(), "");
663         zos.flush();
664         zos.finish();
665         zos.close();
666         fos.flush();
667         fos.close();
668         return true;
669     }
670
671     /**
672      * go through the given file structure recursively
673      * @param zipFile  the ZIP file to write to
674      * @param srcDir  the directory to pack during this cycle
675      * @param subDir  the subdirectory to append to names of file entries inside the archive
676      * @throws IOException
677      */
678     private void pack(ZipOutputStream zipFile, String srcDir, String subDir) throws IOException {
679         File[] files = new File(srcDir).listFiles();
680         for(int i = 0; i < files.length; i++) {
681             if(files[i].isDirectory()) {
682                 pack(zipFile, files[i].getAbsolutePath(), subDir + File.separator + files[i].getName());
683             }
684             else {
685                 packFile(zipFile, subDir, files[i]);
686             }
687         }
688     }
689
690     /**
691      * pack a given file
692      * @param zipFile  the ZIP archive to pack to
693      * @param dir  the directory name to append to name of file entry inside archive
694      * @param file  the file to pack
695      * @throws IOException
696      */
697     private void packFile(ZipOutputStream zipFile, String dir, File file) throws IOException
698     {
699         FileInputStream fileinputstream = new FileInputStream(file);
700         byte buf[] = new byte[fileinputstream.available()];
701         fileinputstream.read(buf);
702         String dirWithSlashes = dir.replace('\\', '/');
703         //System.out.println("zipping " + dirWithSlashes + "/" + file.getName());
704         ZipEntry ze = new ZipEntry(dirWithSlashes + "/" + file.getName());
705         ze.setMethod(ZipEntry.DEFLATED);
706         zipFile.putNextEntry(ze);
707         zipFile.write(buf, 0, buf.length);
708         zipFile.closeEntry();
709         fileinputstream.close();
710     }
711
6bd2c1 712   
438b16 713
5efd94 714   /* ---- Hilfsfunktionen ---- */
ea7193 715   
547755 716 }