Dateiverwaltung für die WebBox
ulrich
2017-03-15 972e946a9836c2909a8318587beeb9bee6631573
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
5bfd34 21 import de.uhilger.filecms.data.FileRef;
7342b1 22 import de.uhilger.filecms.web.Initialiser;
438b16 23 import de.uhilger.wbx.Bild;
U 24 import java.awt.Container;
25 import java.awt.Image;
26 import java.awt.MediaTracker;
27 import java.awt.Toolkit;
8e51b7 28 import java.io.File;
3ad4db 29 import java.io.FileNotFoundException;
U 30 import java.io.FileReader;
e5ff42 31 import java.io.FileWriter;
U 32 import java.io.IOException;
fab80c 33 import java.io.Reader;
e5ff42 34 import java.security.Principal;
7342b1 35 import java.util.ArrayList;
5bfd34 36 import java.util.Iterator;
7342b1 37 import java.util.List;
e5ff42 38 import java.util.logging.Level;
8e51b7 39 import java.util.logging.Logger;
5bfd34 40 import org.apache.commons.io.FileUtils;
c7c502 41
U 42 /**
43  *
44  * @author ulrich
45  */
8931b7 46 public class FileMgr extends Api {
8e51b7 47   private static final Logger logger = Logger.getLogger(FileMgr.class.getName());
c7c502 48   
7342b1 49   public static final String PUB_DIR_PATH = "www/";
U 50   public static final String HOME_DIR_PATH = "home/";
51   public static final String PUB_DIR_NAME = "Oeffentlich";
cccd2b 52   //public static final String HOME_DIR_NAME = "Persoenlicher Ordner";
U 53   public static final String HOME_DIR_NAME = "Persoenlich";
c7c502 54   
972e94 55   public static final String CATALINA_BASE_FOLDER = "base";
U 56   
9e2964 57   public static final int OP_COPY = 1;
U 58   public static final int OP_MOVE = 2;
59   
ea7193 60   public String hallo() {
U 61     return "Hallo Welt!";
62   }
63   
7342b1 64   public List<FileRef> list(String relPath) {
f7d8bf 65     Bild bild = new Bild();
5dfab6 66     List<FileRef> files = new ArrayList();
7342b1 67     if(relPath.length() == 0) {
2121cc 68       FileRef namedPublicFolder = new FileRef(PUB_DIR_NAME, true);
5dfab6 69       logger.finer(namedPublicFolder.getAbsolutePath());
2121cc 70       FileRef namedHomeFolder = new FileRef(HOME_DIR_NAME, true);
5dfab6 71       logger.finer(namedHomeFolder.getAbsolutePath());
972e94 72       FileRef namedBaseFolder = new FileRef(CATALINA_BASE_FOLDER, true);
2121cc 73       files = new ArrayList();
7342b1 74       files.add(namedHomeFolder);
U 75       files.add(namedPublicFolder);
972e94 76       files.add(namedBaseFolder);
ea7193 77     } else {
2121cc 78       String path = getTargetDir(relPath).getAbsolutePath();
5bfd34 79       logger.fine("listing path: " + path);
U 80       File dir = new File(path);
81       if(dir.exists()) {
82         File[] fileArray = dir.listFiles();
83         for(int i = 0; i < fileArray.length; i++) {
84           logger.fine(fileArray[i].toURI().toString());
85           String fname = fileArray[i].toURI().toString().replace("file:/", "");
86           if(fileArray[i].isDirectory()) {
87             fname = fname.substring(0, fname.length() - 1);
88           }
89           logger.fine(fname);
f7d8bf 90           FileRef ref = new FileRef(fname, fileArray[i].isDirectory());
U 91           ref.setMimetype(bild.getMimeType(fileArray[i]));
92           files.add(ref);
5bfd34 93         }
5dfab6 94       }
c509a0 95     }    
7342b1 96     return files;
2121cc 97   }
U 98   
c509a0 99   public FileRef newFolder(String relPath, String folderName) {
U 100     logger.finer(relPath);
101     String targetPath = null;
102     if(relPath.startsWith(PUB_DIR_NAME)) {
103       targetPath = PUB_DIR_PATH + getUserName() + "/" + relPath.substring(PUB_DIR_NAME.length()) + "/" + folderName;
104     } else if(relPath.startsWith(HOME_DIR_NAME)) {
105       targetPath = HOME_DIR_PATH + getUserName() + "/" + relPath.substring(HOME_DIR_NAME.length()) + "/" + folderName;
106     } else {
107       // kann eigentlich nicht sein..
108     }
109     logger.finer(targetPath);
110     File targetDir = new File(getBase().getAbsolutePath(), targetPath);
111     targetDir.mkdirs();
112     return new FileRef(targetDir.getAbsolutePath(), true);
5dfab6 113   }
U 114   
3ad4db 115   public String getCode(String relPath, String fileName) {
U 116     String code = null;
117     
118     Object p = getRequest().getUserPrincipal();
119     if(p instanceof Principal) {
fab80c 120       Reader reader = null;
3ad4db 121       try {
U 122         File targetFile = new File(getTargetDir(relPath), fileName);
fab80c 123         
U 124         //reader = new InputStreamReader(new FileInputStream(targetFile), "UTF8");
125         
3ad4db 126         reader = new FileReader(targetFile);
U 127         StringBuffer buf = new StringBuffer();
128         char[] readBuffer = new char[1024];
129         int charsRead = reader.read(readBuffer);
130         while(charsRead > -1) {
131           buf.append(readBuffer, 0, charsRead);
132           charsRead = reader.read(readBuffer);
133         }
134         code = buf.toString();
135       } catch (FileNotFoundException ex) {
136         Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
137       } catch (IOException ex) {
138         Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
139       } finally {
140         try {
141           reader.close();
142         } catch (IOException ex) {
143           Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
144         }
145       }
146       
147     }    
148     
149     return code;
150   }
151   
663ee9 152   public String renameFile(String relPath, String fname, String newName) {
U 153     File targetDir = getTargetDir(relPath);
154     File file = new File(targetDir, fname);
155     file.renameTo(new File(targetDir, newName));
156     return fname + " umbenannt zu " + newName;
157   }
158   
fc1897 159   public String deleteFiles(String relPath, List fileNames) {
U 160     String result = null;
161     try {
162       logger.fine(fileNames.toString());
163       File targetDir = getTargetDir(relPath);
164       for(int i=0; i < fileNames.size(); i++) {
165         Object o = fileNames.get(i);
166         if(o instanceof ArrayList) {
167           ArrayList al = (ArrayList) o;
168           logger.fine(al.get(0).toString());
169           File targetFile = new File(targetDir, al.get(0).toString());
170           logger.fine(targetFile.getAbsolutePath());
5bfd34 171           if(targetFile.isDirectory()) {
U 172             FileUtils.deleteDirectory(targetFile);
173           } else {
174             targetFile.delete();
175           }
fc1897 176         }
U 177       }
178       result = "deleted";
179     } catch (Throwable ex) {
180       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
181     }
182     return result;
183   }
184   
9e2964 185   public String copyFiles(String fromPath, String toPath, List fileNames) {
fab629 186     return copyOrMoveFiles(fromPath, toPath, fileNames, OP_COPY);
9e2964 187   }
U 188   
189   public String moveFiles(String fromPath, String toPath, List fileNames) {
fab629 190     return copyOrMoveFiles(fromPath, toPath, fileNames, OP_MOVE);
U 191   }
192   
193   private String copyOrMoveFiles(String fromPath, String toPath, List fileNames, int operation) {
5bfd34 194     String result = null;
U 195     try {
196       File srcDir = getTargetDir(fromPath);
197       File targetDir = getTargetDir(toPath);
198       Iterator i = fileNames.iterator();
199       while(i.hasNext()) {
200         Object o = i.next();
201         if (o instanceof ArrayList) {
202           ArrayList al = (ArrayList) o;
203           File srcFile = new File(srcDir, al.get(0).toString());
204           if(srcFile.isDirectory()) {
fab629 205             if(operation == OP_MOVE) {
U 206               FileUtils.moveDirectoryToDirectory(srcFile, targetDir, false);
207             } else {
208               FileUtils.copyDirectoryToDirectory(srcFile, targetDir);
209             }
5bfd34 210           } else {
fab629 211             if(operation == OP_MOVE) {
U 212               FileUtils.moveFileToDirectory(srcFile, targetDir, false);
213             } else {
214               FileUtils.copyFileToDirectory(srcFile, targetDir);              
215             }
5bfd34 216           }
U 217         }
218       }
219     } catch (IOException ex) {
220       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
221     }
222     return result;
9e2964 223   }
U 224   
47e9d4 225   public FileRef saveTextFileAs(String relPath, String fileName, String contents) {
U 226     FileRef savedFile = null;
227     logger.fine(relPath + " " + fileName);
228     //FileRef datenRef = getBase();
229     Object p = getRequest().getUserPrincipal();
230     if(p instanceof Principal) {
231       File targetFile = new File(getTargetDir(relPath), fileName);
232       if(targetFile.exists()) {
233         targetFile = getNewFileName(targetFile);
234       } else {
235         targetFile.getParentFile().mkdirs();
236       }
237       saveToFile(targetFile, contents);
238     }
239     return savedFile;
240   }
241   
242   private File getNewFileName(File file) {
243     File dir = file.getParentFile();
244     String targetName = file.getName();
245     logger.fine("targetName: " + targetName);
246     String ext = "";
247     int dotpos = targetName.indexOf(".");
248     if(dotpos > -1) {
249       ext = targetName.substring(dotpos);
250       targetName = targetName.substring(0, dotpos);
251     }
252     logger.fine("targetName: " + targetName + ", ext: " + ext);
253     int i = 1;
254     while(file.exists()) {
255       StringBuffer buf = new StringBuffer();
256       buf.append(targetName);
257       buf.append("-");
258       buf.append(i);
259       if(ext.length() > 0) {
260         buf.append(ext);
261       }
262       file = new File(dir, buf.toString());
263       i++;
264     }
265     logger.fine("new file: " + file.getName());
266     return file;
942d63 267   }  
47e9d4 268   
U 269   private FileRef saveToFile(File targetFile, String contents) {
ea7193 270     FileRef savedFile = null;
e5ff42 271     try {
47e9d4 272       targetFile.createNewFile();
U 273       FileWriter w = new FileWriter(targetFile);
942d63 274       //w.write(StringEscapeUtils.unescapeHtml(contents));
47e9d4 275       w.write(contents);
U 276       w.flush();
277       w.close();
278       savedFile = new FileRef(
279               targetFile.getAbsolutePath(),
280               targetFile.isDirectory(),
281               targetFile.isHidden(),
282               targetFile.lastModified(),
283               targetFile.length());
e5ff42 284     } catch (IOException ex) {
47e9d4 285       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
U 286     }
287     return savedFile;
288   }
289   
290   public FileRef saveTextFile(String relPath, String fileName, String contents) {
291     FileRef savedFile = null;
292     logger.fine(relPath + " " + fileName);
293     //FileRef datenRef = getBase();
294     Object p = getRequest().getUserPrincipal();
295     if(p instanceof Principal) {
296       File targetFile = new File(getTargetDir(relPath), fileName);
297       if(targetFile.exists()) {
298         /*
299           muss delete() sein?
300           pruefen: ueberschreibt der FileWriter den alteen Inhalt oder 
301           entsteht eine unerwuenschte Mischung aus altem und neuem 
302           Inhalt?
303         */
304         targetFile.delete();
305       } else {
306         targetFile.getParentFile().mkdirs();
307       }
308       saveToFile(targetFile, contents);
e5ff42 309     }
ea7193 310     return savedFile;
U 311   }
438b16 312   
U 313   public String bildVerkleinern(String relPath, String bildName) {
314     File dir = getTargetDir(relPath);
315     File original = new File(dir, bildName);
316     Bild bild = new Bild();
317     //for (int i = 0; i < Bild.GR.length; i++) {
5efd94 318     
438b16 319       //int gr = bild.getVariantenGroesse(i);
U 320       
321       String ext = "";
322       String nurname = bildName;
323       int dotpos = bildName.indexOf(".");
324       if (dotpos > -1) {
325         ext = bildName.substring(dotpos);
326         nurname = bildName.substring(0, dotpos);
327       }
328         
329       Image image = Toolkit.getDefaultToolkit().getImage(original.getAbsolutePath());
330       MediaTracker mediaTracker = new MediaTracker(new Container());
331       mediaTracker.addImage(image, 0);
332       try {
333         mediaTracker.waitForID(0);
334
335         if(!mediaTracker.isErrorAny()) {
336           for(int i = 0; i < Bild.GR.length; i++) {
337             StringBuffer buf = new StringBuffer();
338             buf.append(nurname);
339             buf.append(bild.getVariantenName(i));
340             buf.append(ext);
341             File newImgFile = new File(dir, buf.toString());
342             if(!newImgFile.exists()) {
343               logger.fine(original.getAbsolutePath() + " " + newImgFile.getAbsolutePath());
a44b26 344               bild.writeImageFile(image, bild.getVariantenGroesse(i), bild.getMimeType(original), newImgFile.getAbsolutePath());
438b16 345               //bild.writeImageFile(image, photo.getVariantenGroesse(i), photo.getMimetype(), photo.getAbsolutePath(basisPfad), photo.getVariantenName(basisPfad, i));
U 346             }
347           }
348         }
349       } catch(IOException | InterruptedException ex) {
350         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
351       }
352
353     return "ok";
354   }
355
5efd94 356   /* ---- Hilfsfunktionen ---- */
ea7193 357   
5efd94 358   private File getTargetDir(String relPath) {
3c4b10 359     logger.fine(relPath);
972e94 360     File targetDir;
5efd94 361     String targetPath = null;
U 362     if(relPath.startsWith(PUB_DIR_NAME)) {
9e2964 363       targetPath = PUB_DIR_PATH + getUserName() + relPath.substring(PUB_DIR_NAME.length());
972e94 364       targetDir = new File(getBase().getAbsolutePath(), targetPath);
5efd94 365     } else if(relPath.startsWith(HOME_DIR_NAME)) {
9e2964 366       targetPath = HOME_DIR_PATH + getUserName() + relPath.substring(HOME_DIR_NAME.length());
972e94 367       targetDir = new File(getBase().getAbsolutePath(), targetPath);
U 368     } else if(relPath.startsWith(CATALINA_BASE_FOLDER)) {
369       targetPath = getCatalinaBase();
370       targetDir = new File(targetPath, relPath.substring(CATALINA_BASE_FOLDER.length()));
5efd94 371     } else {
U 372       // kann eigentlich nicht sein..
972e94 373       targetPath = PUB_DIR_PATH + getUserName() + relPath.substring(PUB_DIR_NAME.length());
U 374       targetDir = new File(getBase().getAbsolutePath(), targetPath);
5efd94 375     }
3c4b10 376     logger.fine(targetPath);
972e94 377     //File targetDir = new File(getBase().getAbsolutePath(), targetPath);
5efd94 378     return targetDir;
U 379   }
9e2964 380   
5efd94 381   private FileRef getBase() {
U 382     FileRef base = null;
383     Object o = getServletContext().getAttribute(Initialiser.FILE_BASE);
3c4b10 384     if(o instanceof String) {
U 385       String baseStr = (String) o;
386       logger.fine(baseStr);
387       File file = new File(baseStr);
388       base = new FileRef(file.getAbsolutePath(), file.isDirectory());
5efd94 389     }
U 390     return base;
391   }
392   
393   private String getUserName() {
394     String userName = null;
395     Object p = getRequest().getUserPrincipal();
396     if(p instanceof Principal) {
397       userName = ((Principal) p).getName();
398     }
399     return userName;
547755 400   }    
972e94 401   
U 402   private String getCatalinaBase() {
403     String path = getServletContext().getRealPath("/");
404     logger.fine("getRealPath: " + path); // file-cms in webapps
405     File file = new File(path);
406     file = file.getParentFile().getParentFile();
407     return file.getAbsolutePath();
408   }
547755 409 }