KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > de > jwi > jfm > Folder


1 package de.jwi.jfm;
2
3 /*
4  * jFM - Java Web File Manager
5  *
6  * Copyright (C) 2004 Juergen Weber
7  *
8  * This file is part of jFM.
9  *
10  * jFM is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * jFM is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with jFM; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston
23  */

24
25 import java.io.File JavaDoc;
26 import java.io.FileInputStream JavaDoc;
27 import java.io.FileNotFoundException JavaDoc;
28 import java.io.FileOutputStream JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.io.OutputStream JavaDoc;
32 import java.io.UnsupportedEncodingException JavaDoc;
33 import java.net.MalformedURLException JavaDoc;
34 import java.net.URL JavaDoc;
35 import java.net.URLDecoder JavaDoc;
36 import java.util.ArrayList JavaDoc;
37 import java.util.Arrays JavaDoc;
38 import java.util.Collection JavaDoc;
39 import java.util.Comparator JavaDoc;
40 import java.util.HashMap JavaDoc;
41 import java.util.List JavaDoc;
42 import java.util.Map JavaDoc;
43 import java.util.zip.ZipOutputStream JavaDoc;
44
45 import org.apache.commons.fileupload.FileItem;
46 import org.apache.commons.io.FileUtils;
47 import org.apache.commons.io.filefilter.TrueFileFilter;
48
49 import de.jwi.ftp.FTPUploader;
50 import de.jwi.jfm.servlets.Controller;
51 import de.jwi.servletutil.RealPath;
52 import de.jwi.zip.Unzipper;
53 import de.jwi.zip.Zipper;
54
55 /**
56  * @author Jürgen Weber
57  * Source file created on 27.03.2004
58  */

59 public class Folder
60 {
61
62     private RealPath realPath;
63
64     private boolean isNotInContext;
65
66     private String JavaDoc path;
67
68     private String JavaDoc url;
69
70     private String JavaDoc fileViewUrl;
71
72     private File JavaDoc myFile;
73
74     private File JavaDoc[] children;
75
76     private FileWrapper[] wrappers;
77
78     private Map JavaDoc nameToFile;
79
80     private List JavaDoc files;
81
82     private List JavaDoc parents;
83
84     private boolean calcRecursiveFolderSize = false;
85
86     public boolean isCalcRecursiveFolderSize()
87     {
88         return calcRecursiveFolderSize;
89     }
90
91     public List JavaDoc getParents()
92     {
93         return parents;
94     }
95
96     private Folder()
97     {
98         // NOP
99
}
100
101     public Folder(RealPath realPath, String JavaDoc path, String JavaDoc url, String JavaDoc fileViewUrl)
102             throws IOException JavaDoc
103     {
104         this.realPath = realPath;
105         this.path = path;
106         this.url = url;
107         this.fileViewUrl = fileViewUrl;
108
109         myFile = new File JavaDoc(realPath.getRealPath());
110
111         if (!myFile.exists()) { throw new IOException JavaDoc(path + " does not exist."); }
112     }
113
114     public void load()
115     {
116
117         children = myFile.listFiles();
118
119         wrappers = new FileWrapper[children.length];
120
121         nameToFile = new HashMap JavaDoc(children.length);
122
123         for (int i = 0; i < children.length; i++)
124         {
125             String JavaDoc name = children[i].getName();
126
127             String JavaDoc u = children[i].isDirectory() ? url : fileViewUrl;
128
129             wrappers[i] = new FileWrapper(this, children[i], u + name, path
130                     + name);
131
132             nameToFile.put(name, children[i]);
133         }
134
135         files = Arrays.asList(wrappers);
136
137         String JavaDoc[] pp = path.split("/");
138
139         if ("/".equals(path))
140         {
141             pp = new String JavaDoc[1];
142         }
143
144         pp[0] = "/";
145
146         HRef[] parentLinks = new HRef[pp.length];
147         String JavaDoc s;
148         int p = 0;
149         for (int i = 0; i < pp.length - 1; i++)
150         {
151             s = path.substring(0, 1 + path.indexOf("/", p));
152             p = s.length();
153             parentLinks[i] = new HRef(pp[i], s);
154         }
155         parentLinks[pp.length - 1] = new HRef(pp[pp.length - 1], null);
156
157         parents = Arrays.asList(parentLinks);
158     }
159
160     public List JavaDoc getFiles()
161     {
162         return files;
163     }
164
165     private boolean checkFileName(String JavaDoc name)
166     {
167         if (name.indexOf("..") > -1) { return false; }
168         return true;
169     }
170
171     private String JavaDoc rename(String JavaDoc[] selectedIDs, String JavaDoc target)
172             throws OutOfSyncException
173     {
174         if (selectedIDs.length > 1) { return "More than 1 file selected"; }
175
176         if (!checkFileName(target)) { return "Illegal target name"; }
177
178         File JavaDoc f = checkAndGet(selectedIDs[0]);
179
180         if (null == f) { throw new OutOfSyncException(); }
181
182         File JavaDoc f1 = new File JavaDoc(f.getParent(), target);
183
184         if (f1.exists()) { return target + " allready exists"; }
185
186         if (!f.renameTo(f1)) { return "failed to rename " + f.getName(); }
187
188         return "";
189     }
190
191     private File JavaDoc getTargetFile(String JavaDoc target) throws IOException JavaDoc
192     {
193         File JavaDoc f = new File JavaDoc(myFile,target);
194         
195         f = f.getCanonicalFile();
196         
197         return f;
198     }
199
200     private File JavaDoc checkAndGet(String JavaDoc id)
201     {
202         String JavaDoc s = null;
203         try
204         {
205             s = URLDecoder.decode(id, "UTF-8");
206         }
207         catch (UnsupportedEncodingException JavaDoc e)
208         {
209             // NOP
210
}
211
212         String JavaDoc s1 = s.substring(0, s.lastIndexOf('.'));
213         String JavaDoc s2 = s.substring(s.lastIndexOf('.') + 1);
214
215         File JavaDoc f = (File JavaDoc) nameToFile.get(s1);
216
217         if (null == f) { return null; // File not found
218
}
219
220         long l = f.lastModified();
221
222         if (!(Long.toString(l).equals(s2))) { return null; // File modification changed
223
}
224
225         return f;
226
227     }
228
229     private void fileCopy(File JavaDoc source, File JavaDoc target) throws IOException JavaDoc
230     {
231         FileInputStream JavaDoc in = new FileInputStream JavaDoc(source);
232         FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(target);
233         int c;
234
235         try
236         {
237             while ((c = in.read()) != -1)
238             {
239                 out.write(c);
240             }
241             target.setLastModified(source.lastModified());
242         }
243         catch (IOException JavaDoc e)
244         {
245             throw e;
246         }
247
248         finally
249         {
250             out.close();
251             in.close();
252         }
253     }
254
255     public void sum()
256     {
257         calcRecursiveFolderSize = true;
258     }
259
260     public void sort(int mode)
261     {
262         Comparator JavaDoc c = null;
263
264         switch (mode)
265         {
266         case FileComparator.SORT_NAME_UP:
267             c = FileComparator.nameUpInstance;
268             break;
269         case FileComparator.SORT_NAME_DOWN:
270             c = FileComparator.nameDownInstance;
271             break;
272         case FileComparator.SORT_SIZE_UP:
273             c = FileComparator.sizeUpInstance;
274             break;
275         case FileComparator.SORT_SIZE_DOWN:
276             c = FileComparator.sizeDownInstance;
277             break;
278         case FileComparator.SORT_DATE_UP:
279             c = FileComparator.dateUpInstance;
280             break;
281         case FileComparator.SORT_DATE_DOWN:
282             c = FileComparator.dateDownInstance;
283             break;
284         }
285
286         Arrays.sort(wrappers, c);
287     }
288
289     private String JavaDoc copyOrMove(boolean move, String JavaDoc[] selectedIDs, String JavaDoc target)
290             throws IOException JavaDoc, OutOfSyncException
291     {
292         if ((selectedIDs==null) || (selectedIDs.length == 0)) { return "No file selected"; }
293         
294         File JavaDoc f1 = getTargetFile(target);
295         
296         if ((null == f1)
297                 || (myFile.getCanonicalFile().equals(f1.getCanonicalFile()))) { return "illegal target file"; }
298
299         if ((!f1.isDirectory()) && (selectedIDs.length > 1)) { return "target is not a directory"; }
300
301         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
302
303         File JavaDoc fx = null;
304
305         for (int i = 0; i < selectedIDs.length; i++)
306         {
307             File JavaDoc f = checkAndGet(selectedIDs[i]);
308
309             if (null == f) { throw new OutOfSyncException(); }
310
311             if (!f1.isDirectory())
312             {
313                 fx = f1;
314             }
315             else
316             {
317                 fx = new File JavaDoc(f1, f.getName());
318             }
319
320             if (move)
321             {
322                 if (!f.renameTo(fx))
323                 {
324                     sb.append(f.getName()).append(" ");
325                 }
326             }
327             else
328             {
329                 try
330                 {
331                     FileUtils.copyFile(f, fx, true);
332                     //fileCopy(f, fx);
333
}
334                 catch (IOException JavaDoc e)
335                 {
336                     sb.append(f.getName()).append(" ");
337                 }
338             }
339         }
340
341         String JavaDoc s = sb.toString();
342
343         if (!"".equals(s))
344         {
345             String JavaDoc op = move ? "move" : "copy";
346             return "failed to " + op + " " + s + " to " + f1.toString();
347         }
348
349         return "";
350     }
351
352     private String JavaDoc delete(String JavaDoc[] selectedIDs, String JavaDoc target)
353             throws OutOfSyncException
354     {
355         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
356
357         for (int i = 0; i < selectedIDs.length; i++)
358         {
359             File JavaDoc f = checkAndGet(selectedIDs[i]);
360
361             if (null == f) { throw new OutOfSyncException(); }
362
363             if (!f.delete())
364             {
365                 sb.append(f.getName());
366             }
367         }
368
369         String JavaDoc s = sb.toString();
370
371         if (!"".equals(s)) { return "failed to delete " + s; }
372
373         return "";
374     }
375
376     private String JavaDoc deleteRecursive(String JavaDoc[] selectedIDs, String JavaDoc target)
377             throws OutOfSyncException
378     {
379         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
380
381         if (!"YES".equals(target)) { return "Please confirm with YES"; }
382
383         for (int i = 0; i < selectedIDs.length; i++)
384         {
385             File JavaDoc f = checkAndGet(selectedIDs[i]);
386
387             if (null == f) { throw new OutOfSyncException(); }
388
389             try
390             {
391                 FileUtils.deleteDirectory(f);
392             }
393             catch (IOException JavaDoc e)
394             {
395                 sb.append(f.getName());
396             }
397         }
398
399         String JavaDoc s = sb.toString();
400
401         if (!"".equals(s)) { return "failed to delete " + s; }
402
403         return "";
404     }
405
406     private String JavaDoc ftpToURL(String JavaDoc[] selectedIDs, String JavaDoc target)
407             throws OutOfSyncException
408     {
409         URL JavaDoc url = null;
410         String JavaDoc s = "";
411
412         try
413         {
414             url = new URL JavaDoc("ftp://" + target);
415         }
416         catch (MalformedURLException JavaDoc e)
417         {
418             return "Malformed URL";
419         }
420
421         ArrayList JavaDoc l = new ArrayList JavaDoc();
422
423         for (int i = 0; i < selectedIDs.length; i++)
424         {
425             File JavaDoc f = checkAndGet(selectedIDs[i]);
426
427             if (null == f) { throw new OutOfSyncException(); }
428
429             l.add(f);
430         }
431
432         if (selectedIDs.length > 0)
433         {
434             s = FTPUploader.upload(url, l);
435         }
436
437         return s;
438     }
439
440     private String JavaDoc mkdir(String JavaDoc target) throws IOException JavaDoc
441     {
442         File JavaDoc f = getTargetFile(target);
443
444         if (!f.mkdir()) { return "could not mkdir " + target; }
445
446         return "";
447     }
448
449     private String JavaDoc getURL(String JavaDoc url)
450     {
451         URL JavaDoc remote;
452         try
453         {
454             remote = new URL JavaDoc(url);
455         }
456         catch (MalformedURLException JavaDoc e1)
457         {
458             return url + "is not a valid URL";
459         }
460         String JavaDoc s = remote.getFile();
461         int p = s.lastIndexOf('/');
462         if (p > -1)
463         {
464             s = s.substring(p);
465         }
466         File JavaDoc f = new File JavaDoc(myFile, s);
467
468         try
469         {
470             FileUtils.copyURLToFile(remote, f);
471         }
472         catch (IOException JavaDoc e)
473         {
474             return "could not get " + remote.toString();
475         }
476
477         return "";
478     }
479
480     private String JavaDoc join(String JavaDoc[] selectedIDs) throws OutOfSyncException, IOException JavaDoc
481     {
482         Arrays.sort(selectedIDs,new Comparator JavaDoc() {
483             public int compare(Object JavaDoc o1,
484                     Object JavaDoc o2)
485             {
486                 return ((String JavaDoc)o1).compareTo(o2);
487             }
488         });
489         
490         File JavaDoc target = checkAndGet(selectedIDs[0]);
491
492         if (null == target) { throw new OutOfSyncException(); }
493         
494         byte[] b = new byte[512];
495         int n;
496         
497         for (int i = 1; i < selectedIDs.length; i++)
498         {
499             File JavaDoc f = checkAndGet(selectedIDs[i]);
500
501             if (null == f) { throw new OutOfSyncException(); }
502
503             FileInputStream JavaDoc fi = null;
504             FileOutputStream JavaDoc fo = null;
505             
506             try
507             {
508                 fi = new FileInputStream JavaDoc(f);
509                 
510                 fo = new FileOutputStream JavaDoc(target, true);
511
512                 while ((n=fi.read(b))>0)
513                 {
514                     fo.write(b, 0, n);
515                 }
516             }
517             finally
518             {
519                 if (null != fo)
520                 {
521                 fo.close();
522                 }
523                 if (null != fo)
524                 {
525                     fi.close();
526                 }
527             }
528         }
529
530         return "";
531     }
532     
533     
534     private String JavaDoc unzip(String JavaDoc[] selectedIDs) throws OutOfSyncException
535     {
536         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
537         boolean done;
538
539         for (int i = 0; i < selectedIDs.length; i++)
540         {
541             File JavaDoc f = checkAndGet(selectedIDs[i]);
542
543             if (null == f) { throw new OutOfSyncException(); }
544
545             FileInputStream JavaDoc is = null;
546             try
547             {
548                 is = new FileInputStream JavaDoc(f);
549                 Unzipper.unzip(is, myFile);
550                 done = true;
551             }
552             catch (FileNotFoundException JavaDoc e)
553             {
554                 done = false;
555             }
556             catch (IOException JavaDoc e)
557             {
558                 done = false;
559             }
560             finally
561             {
562                 if (null != is)
563                 {
564                     try
565                     {
566                         is.close();
567                     }
568                     catch (IOException JavaDoc e)
569                     {
570                         // NOP
571
}
572                 }
573             }
574             if (!done)
575             {
576                 sb.append(f.getName());
577             }
578         }
579
580         String JavaDoc s = sb.toString();
581
582         if (!"".equals(s)) { return "failed to unzip " + s; }
583
584         return "";
585     }
586
587     private String JavaDoc zip(OutputStream JavaDoc out, String JavaDoc[] selectedIDs)
588             throws IOException JavaDoc, OutOfSyncException
589     {
590
591         Collection JavaDoc c = null;
592
593         List JavaDoc l = new ArrayList JavaDoc();
594
595         for (int i = 0; i < selectedIDs.length; i++)
596         {
597             File JavaDoc f = checkAndGet(selectedIDs[i]);
598
599             if (null == f) { throw new OutOfSyncException(); }
600
601             if (f.isDirectory())
602             {
603                 c = FileUtils.listFiles(f, TrueFileFilter.INSTANCE,
604                         TrueFileFilter.INSTANCE);
605                 l.addAll(c);
606             }
607             else
608             {
609                 l.add(f);
610             }
611         }
612
613         ZipOutputStream JavaDoc z = new ZipOutputStream JavaDoc(out);
614         try
615         {
616             new Zipper().zip(z, l, myFile);
617         }
618         finally
619         {
620             z.close();
621         }
622
623         return null;
624     }
625
626     // caller must have called load() before
627

628     public String JavaDoc action(int action, OutputStream JavaDoc out, String JavaDoc[] selectedIDs,
629             String JavaDoc target) throws IOException JavaDoc, OutOfSyncException
630     {
631         String JavaDoc res = null;
632
633         switch (action)
634         {
635         case Controller.RENAME_ACTION:
636             res = rename(selectedIDs, target);
637             break;
638         case Controller.COPY_ACTION:
639             res = copyOrMove(false, selectedIDs, target);
640             break;
641         case Controller.MOVE_ACTION:
642             res = copyOrMove(true, selectedIDs, target);
643             break;
644         case Controller.DELETE_ACTION:
645             res = delete(selectedIDs, target);
646             break;
647         case Controller.DELETE_RECURSIVE_ACTION:
648             res = deleteRecursive(selectedIDs, target);
649             break;
650         case Controller.UNZIP_ACTION:
651             res = unzip(selectedIDs);
652             break;
653         case Controller.ZIP_ACTION:
654             res = zip(out, selectedIDs);
655             break;
656         case Controller.MKDIR_ACTION:
657             res = mkdir(target);
658             break;
659         case Controller.GETURL_ACTION:
660             res = getURL(target);
661             break;
662         case Controller.FTPUP_ACTION:
663             res = ftpToURL(selectedIDs, target);
664             break;
665         case Controller.JOIN_ACTION:
666             res = join(selectedIDs);
667             break;
668         }
669
670         if ("".equals(res)) // no error, action succeded.
671
{
672             load();
673         }
674
675         return res;
676     }
677
678     public void upload(FileItem item, boolean unzip) throws Exception JavaDoc
679     {
680         String JavaDoc name = item.getName();
681
682         name = name.replaceAll("\\\\", "/");
683         int p = name.lastIndexOf('/');
684         if (p > -1)
685         {
686             name = name.substring(p);
687         }
688         if (unzip)
689         {
690             InputStream JavaDoc is = item.getInputStream();
691             Unzipper.unzip(is, myFile);
692         }
693         else
694         {
695             File JavaDoc f = new File JavaDoc(myFile, name);
696             item.write(f);
697         }
698     }
699 }
Popular Tags