Dateiverwaltung für die WebBox
ulrich
2017-03-02 663ee9d3828b536f857f54ab1fc66c6f28095027
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;
5bfd34 23 //import de.uhilger.filesystem.FileRef;
U 24 //import de.uhilger.filesystem.FileSystem;
25 //import de.uhilger.filesystem.LocalFileSystem;
8e51b7 26 import java.io.File;
3ad4db 27 import java.io.FileNotFoundException;
U 28 import java.io.FileReader;
e5ff42 29 import java.io.FileWriter;
U 30 import java.io.IOException;
31 import java.security.Principal;
7342b1 32 import java.util.ArrayList;
5bfd34 33 import java.util.Iterator;
7342b1 34 import java.util.List;
e5ff42 35 import java.util.logging.Level;
8e51b7 36 import java.util.logging.Logger;
5bfd34 37 import org.apache.commons.io.FileUtils;
c7c502 38
U 39 /**
40  *
41  * @author ulrich
42  */
8931b7 43 public class FileMgr extends Api {
8e51b7 44   private static final Logger logger = Logger.getLogger(FileMgr.class.getName());
c7c502 45   
7342b1 46   public static final String PUB_DIR_PATH = "www/";
U 47   public static final String HOME_DIR_PATH = "home/";
48   public static final String PUB_DIR_NAME = "Oeffentlich";
49   public static final String HOME_DIR_NAME = "Persoenlicher Ordner";
c7c502 50   
9e2964 51   public static final int OP_COPY = 1;
U 52   public static final int OP_MOVE = 2;
53   
ea7193 54   public String hallo() {
U 55     return "Hallo Welt!";
56   }
57   
7342b1 58   public List<FileRef> list(String relPath) {
5dfab6 59     List<FileRef> files = new ArrayList();
7342b1 60     if(relPath.length() == 0) {
2121cc 61       FileRef namedPublicFolder = new FileRef(PUB_DIR_NAME, true);
5dfab6 62       logger.finer(namedPublicFolder.getAbsolutePath());
2121cc 63       FileRef namedHomeFolder = new FileRef(HOME_DIR_NAME, true);
5dfab6 64       logger.finer(namedHomeFolder.getAbsolutePath());
2121cc 65       files = new ArrayList();
7342b1 66       files.add(namedHomeFolder);
U 67       files.add(namedPublicFolder);
ea7193 68     } else {
2121cc 69       String path = getTargetDir(relPath).getAbsolutePath();
5bfd34 70       logger.fine("listing path: " + path);
U 71       //LocalFileSystem fs = new LocalFileSystem();
72       //logger.fine("listing " + getTargetDir(relPath).getAbsolutePath());
73       File dir = new File(path);
74       if(dir.exists()) {
75         File[] fileArray = dir.listFiles();
76
77         //FileRef[] fileRefs = fs.list(new FileRef(getTargetDir(relPath).getAbsolutePath(), true));
78         for(int i = 0; i < fileArray.length; i++) {
79           logger.fine(fileArray[i].toURI().toString());
80           String fname = fileArray[i].toURI().toString().replace("file:/", "");
81           if(fileArray[i].isDirectory()) {
82             fname = fname.substring(0, fname.length() - 1);
83           }
84           logger.fine(fname);
85           files.add(new FileRef(fname, fileArray[i].isDirectory()));
86         }
5dfab6 87       }
c509a0 88     }    
7342b1 89     return files;
2121cc 90   }
U 91   
c509a0 92   public FileRef newFolder(String relPath, String folderName) {
U 93     logger.finer(relPath);
94     String targetPath = null;
95     if(relPath.startsWith(PUB_DIR_NAME)) {
96       targetPath = PUB_DIR_PATH + getUserName() + "/" + relPath.substring(PUB_DIR_NAME.length()) + "/" + folderName;
97     } else if(relPath.startsWith(HOME_DIR_NAME)) {
98       targetPath = HOME_DIR_PATH + getUserName() + "/" + relPath.substring(HOME_DIR_NAME.length()) + "/" + folderName;
99     } else {
100       // kann eigentlich nicht sein..
101     }
102     logger.finer(targetPath);
103     File targetDir = new File(getBase().getAbsolutePath(), targetPath);
104     targetDir.mkdirs();
105     return new FileRef(targetDir.getAbsolutePath(), true);
5dfab6 106   }
U 107   
3ad4db 108   public String getCode(String relPath, String fileName) {
U 109     String code = null;
110     
111     Object p = getRequest().getUserPrincipal();
112     if(p instanceof Principal) {
113       FileReader reader = null;
114       try {
115         File targetFile = new File(getTargetDir(relPath), fileName);
116         reader = new FileReader(targetFile);
117         StringBuffer buf = new StringBuffer();
118         char[] readBuffer = new char[1024];
119         int charsRead = reader.read(readBuffer);
120         while(charsRead > -1) {
121           buf.append(readBuffer, 0, charsRead);
122           charsRead = reader.read(readBuffer);
123         }
124         code = buf.toString();
125       } catch (FileNotFoundException ex) {
126         Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
127       } catch (IOException ex) {
128         Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
129       } finally {
130         try {
131           reader.close();
132         } catch (IOException ex) {
133           Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
134         }
135       }
136       
137     }    
138     
139     return code;
140   }
141   
663ee9 142   public String renameFile(String relPath, String fname, String newName) {
U 143     File targetDir = getTargetDir(relPath);
144     File file = new File(targetDir, fname);
145     file.renameTo(new File(targetDir, newName));
146     return fname + " umbenannt zu " + newName;
147   }
148   
fc1897 149   public String deleteFiles(String relPath, List fileNames) {
U 150     String result = null;
151     try {
152       logger.fine(fileNames.toString());
153       File targetDir = getTargetDir(relPath);
154       for(int i=0; i < fileNames.size(); i++) {
155         Object o = fileNames.get(i);
156         if(o instanceof ArrayList) {
157           ArrayList al = (ArrayList) o;
158           logger.fine(al.get(0).toString());
159           File targetFile = new File(targetDir, al.get(0).toString());
160           logger.fine(targetFile.getAbsolutePath());
5bfd34 161           if(targetFile.isDirectory()) {
U 162             FileUtils.deleteDirectory(targetFile);
163           } else {
164             targetFile.delete();
165           }
fc1897 166         }
U 167       }
168       result = "deleted";
169     } catch (Throwable ex) {
170       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
171     }
172     return result;
173   }
174   
9e2964 175   public String copyFiles(String fromPath, String toPath, List fileNames) {
5bfd34 176     String result = null;
U 177     try {
178       File srcDir = getTargetDir(fromPath);
179       File targetDir = getTargetDir(toPath);
180       Iterator i = fileNames.iterator();
181       while(i.hasNext()) {
182         Object o = i.next();
183         if (o instanceof ArrayList) {
184           ArrayList al = (ArrayList) o;
185           File srcFile = new File(srcDir, al.get(0).toString());
186           if(srcFile.isDirectory()) {
187             logger.fine("copy dir " + srcFile.getAbsolutePath() + " to dir " + targetDir.getAbsolutePath());
188             FileUtils.copyDirectoryToDirectory(srcFile, targetDir);
189           } else {
190             logger.fine("copy srcFile " + srcFile.getAbsolutePath() + " to dir " + targetDir.getAbsolutePath());
191             FileUtils.copyFileToDirectory(srcFile, targetDir);
192           }
193         }
194       }
195     } catch (IOException ex) {
196       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
197     }
198     return result;
9e2964 199   }
U 200   
201   public String moveFiles(String fromPath, String toPath, List fileNames) {
5bfd34 202     String result = null;
U 203     try {
204       File srcDir = getTargetDir(fromPath);
205       File targetDir = getTargetDir(toPath);
206       Iterator i = fileNames.iterator();
207       while(i.hasNext()) {
208         Object o = i.next();
209         if (o instanceof ArrayList) {
210           ArrayList al = (ArrayList) o;
211           File srcFile = new File(srcDir, al.get(0).toString());
212           if(srcFile.isDirectory()) {
213             FileUtils.moveDirectoryToDirectory(srcFile, targetDir, false);
214           } else {
215             FileUtils.moveFileToDirectory(srcFile, targetDir, false);
216           }
217         }
218       }
219     } catch (IOException ex) {
220       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
221     }
222     return result;
223     //return copyOrMoveFiles(fromPath, toPath, fileNames, OP_MOVE);
9e2964 224   }
U 225   
226   /**
227    * Dateien kopieren
228    * 
229    * @param fromPath der relative Pfad, aus dem die Dateien stammen, die kopiert werden sollen
230    * @param toPath der relative Pfad, an den die Dateien kopiert werden sollen
231    * @param fileNames  Liste mit Namen der Dateien, die kopiert werden sollen
232    * @param operation OP_COPY oder OP_MOVE
233    * @return null bei Fehler oder Quittungstext, wenn erfolgreich
234    */
5bfd34 235   /*
9e2964 236   private String copyOrMoveFiles(String fromPath, String toPath, List fileNames, int operation) {
U 237     String result = null;
238     try {
239       FileRef[] files = new FileRef[fileNames.size()];
240       logger.fine(fileNames.toString());
241       File srcDir = getTargetDir(fromPath);
242       for(int i=0; i < fileNames.size(); i++) {
243         Object o = fileNames.get(i);
244         if(o instanceof ArrayList) {
245           ArrayList al = (ArrayList) o;
246           logger.fine(al.get(0).toString());
247           File srcFile = new File(srcDir, al.get(0).toString());
248           logger.fine(srcFile.getAbsolutePath());
249           files[i] = new FileRef(srcFile.getAbsolutePath(), srcFile.isDirectory());
250         }
251       }
252       File targetDir = getTargetDir(toPath);
253       FileSystem fs = new LocalFileSystem();
254       switch(operation) {
255         case OP_COPY:
256           fs.copy(files, new FileRef(targetDir.getAbsolutePath(), true));
5bfd34 257           FileUtils.copy
9e2964 258           break;
U 259         case OP_MOVE:
260           fs.move(files, new FileRef(targetDir.getAbsolutePath(), true));
261           break;
262       }
263       result = "kopiert";
264     } catch (Throwable ex) {
265       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
266     }
267     return result;
268   }
5bfd34 269   */
9e2964 270   
ea7193 271   public FileRef saveTextFile(String relPath, String fileName, String contents) {
U 272     FileRef savedFile = null;
e5ff42 273     try {
U 274       FileRef datenRef = getBase();
3ad4db 275       //File daten = new File(datenRef.getAbsolutePath());
e5ff42 276       Object p = getRequest().getUserPrincipal();
U 277       if(p instanceof Principal) {
2121cc 278         File targetFile = new File(getTargetDir(relPath), fileName);
7342b1 279         if(targetFile.exists()) {
U 280           /*
281             muss delete() sein?
282             pruefen: ueberschreibt der FileWriter den alteen Inhalt oder 
283             entsteht eine unerwuenschte Mischung aus altem und neuem 
284             Inhalt?
285           */
286           targetFile.delete();
287         } else {
915927 288           targetFile.getParentFile().mkdirs();
e5ff42 289         }
7342b1 290         targetFile.createNewFile();
U 291         FileWriter w = new FileWriter(targetFile);
292         w.write(contents);
293         w.flush();
294         w.close();
295         savedFile = new FileRef(
296                 targetFile.getAbsolutePath(), 
297                 targetFile.isDirectory(), 
298                 targetFile.isHidden(), 
299                 targetFile.lastModified(), 
300                 targetFile.length());
e5ff42 301       }
U 302     } catch (IOException ex) {
303       logger.log(Level.SEVERE, null, ex);
304     }
ea7193 305     return savedFile;
U 306   }
5efd94 307     
U 308   /* ---- Hilfsfunktionen ---- */
ea7193 309   
5efd94 310   private File getTargetDir(String relPath) {
3c4b10 311     logger.fine(relPath);
5efd94 312     String targetPath = null;
U 313     if(relPath.startsWith(PUB_DIR_NAME)) {
9e2964 314       targetPath = PUB_DIR_PATH + getUserName() + relPath.substring(PUB_DIR_NAME.length());
5efd94 315     } else if(relPath.startsWith(HOME_DIR_NAME)) {
9e2964 316       targetPath = HOME_DIR_PATH + getUserName() + relPath.substring(HOME_DIR_NAME.length());
5efd94 317     } else {
U 318       // kann eigentlich nicht sein..
319     }
3c4b10 320     logger.fine(targetPath);
5efd94 321     File targetDir = new File(getBase().getAbsolutePath(), targetPath);
U 322     return targetDir;
323   }
9e2964 324   
5efd94 325   private FileRef getBase() {
U 326     FileRef base = null;
327     Object o = getServletContext().getAttribute(Initialiser.FILE_BASE);
3c4b10 328     if(o instanceof String) {
U 329       String baseStr = (String) o;
330       logger.fine(baseStr);
331       File file = new File(baseStr);
332       base = new FileRef(file.getAbsolutePath(), file.isDirectory());
5efd94 333     }
U 334     return base;
335   }
336   
337   private String getUserName() {
338     String userName = null;
339     Object p = getRequest().getUserPrincipal();
340     if(p instanceof Principal) {
341       userName = ((Principal) p).getName();
342     }
343     return userName;
344   }
345   
346   /*
8e51b7 347   private File getWebappsDir() {
8931b7 348     File cfile = new File(this.getClass().getResource(
U 349             this.getClass().getSimpleName() + ".class").getFile());
8e51b7 350     String path = cfile.getAbsolutePath();
8931b7 351     return new File(path.substring(0, path.indexOf(getRequest().getContextPath())));
c7c502 352   }
5efd94 353   */
7342b1 354     
c7c502 355 }
8a09f4 356
U 357
358 /*
359   https://stackoverflow.com/questions/300559/move-copy-file-operations-in-java
360
361
362
363 Try to use org.apache.commons.io.FileUtils (General file manipulation utilities). Facilities are provided in the following methods:
364
365     (1) FileUtils.moveDirectory(File srcDir, File destDir) => Moves a directory.
366
367     (2) FileUtils.moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) => Moves a directory to another directory.
368
369     (3) FileUtils.moveFile(File srcFile, File destFile) => Moves a file.
370
371     (4) FileUtils.moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) => Moves a file to a directory.
372
373     (5) FileUtils.moveToDirectory(File src, File destDir, boolean createDestDir) => Moves a file or directory to the destination directory.
374
375 It's simple, easy and fast.
376   
377
378   https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html
379
380 */