KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > de > jwi > jfm > servlets > Controller


1 package de.jwi.jfm.servlets;
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.IOException JavaDoc;
28 import java.io.InputStream JavaDoc;
29 import java.io.OutputStream JavaDoc;
30 import java.io.PrintWriter JavaDoc;
31 import java.security.Principal JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.List JavaDoc;
34 import java.util.Properties JavaDoc;
35 import java.util.StringTokenizer JavaDoc;
36
37 import javax.servlet.RequestDispatcher JavaDoc;
38 import javax.servlet.ServletException JavaDoc;
39 import javax.servlet.http.HttpServlet JavaDoc;
40 import javax.servlet.http.HttpServletRequest JavaDoc;
41 import javax.servlet.http.HttpServletResponse JavaDoc;
42
43 import org.apache.commons.fileupload.DiskFileUpload;
44 import org.apache.commons.fileupload.FileItem;
45 import org.apache.commons.fileupload.FileUpload;
46
47 import de.jwi.jfm.FileComparator;
48 import de.jwi.jfm.Folder;
49 import de.jwi.jfm.OutOfSyncException;
50 import de.jwi.servletutil.PathHelper;
51 import de.jwi.servletutil.RealPath;
52
53 /**
54  * @author Jürgen Weber
55  * Source file created on 26.03.2004
56  *
57  */

58 public class Controller extends HttpServlet JavaDoc
59 {
60
61     private static final String JavaDoc PATH_URL_SERVLET = "/path";
62
63     private static final String JavaDoc CTX_DOWNLOAD_SERVLET = "/dlx";
64
65     private static final String JavaDoc FILE_DOWNLOAD_SERVLET = "/dlf";
66
67     private static String JavaDoc version = "unknown";
68
69     private static final String JavaDoc VERSIONCONFIGFILE = "version.properties";
70
71     public static final int NOP_ACTION = 0;
72
73     public static final int RENAME_ACTION = 1;
74
75     public static final int COPY_ACTION = 2;
76
77     public static final int MOVE_ACTION = 3;
78
79     public static final int DELETE_ACTION = 4;
80
81     public static final int DELETE_RECURSIVE_ACTION = 5;
82
83     public static final int MKDIR_ACTION = 6;
84
85     public static final int UNZIP_ACTION = 7;
86
87     public static final int ZIP_ACTION = 8;
88
89     public static final int GETURL_ACTION = 9;
90
91     public static final int FTPUP_ACTION = 10;
92     
93     public static final int JOIN_ACTION = 11;
94
95     private Properties JavaDoc dirmapping = null;
96
97     private File JavaDoc tempDir = null;
98
99     private String JavaDoc filebase = null;
100
101     public void init() throws ServletException JavaDoc
102     {
103         tempDir = (File JavaDoc) getServletContext().getAttribute(
104                 "javax.servlet.context.tempdir");
105
106         filebase = getServletContext().getInitParameter("filebase");
107
108         String JavaDoc s = getServletContext().getInitParameter("dirmappings");
109
110         dirmapping = new Properties JavaDoc();
111
112         if (null != s)
113         {
114             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(s, ",");
115             while (st.hasMoreTokens())
116             {
117                 String JavaDoc s1 = st.nextToken();
118                 int p = s1.indexOf('=');
119                 if (p > -1)
120                 {
121                     String JavaDoc key = s1.substring(0, p);
122                     String JavaDoc val = s1.substring(p + 1);
123                     dirmapping.setProperty(key, val);
124                 }
125             }
126         }
127
128         try
129         {
130             InputStream JavaDoc is = getServletContext().getResourceAsStream(
131                     "/WEB-INF/" + VERSIONCONFIGFILE);
132
133             Properties JavaDoc versionProperties = new Properties JavaDoc();
134             versionProperties.load(is);
135
136             s = versionProperties.getProperty("version");
137             if (null != s)
138             {
139                 version = s;
140             }
141         }
142         catch (Exception JavaDoc e)
143         {
144             e.printStackTrace(System.err);
145         }
146
147     }
148
149     public void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
150             throws IOException JavaDoc, ServletException JavaDoc
151     {
152         doPost(request, response);
153     }
154
155     public void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
156             throws IOException JavaDoc, ServletException JavaDoc
157     {
158         String JavaDoc self = null;
159         String JavaDoc contextPath = null;
160         String JavaDoc pathInfo = null;
161         Folder folder = null;
162         try
163         {
164             contextPath = request.getContextPath();
165             String JavaDoc servletPath = request.getServletPath();
166
167             pathInfo = request.getPathInfo();
168
169             if (null == pathInfo)
170             {
171
172                 PrintWriter JavaDoc writer = response.getWriter();
173                 writer.print(contextPath + servletPath + " is alive.");
174
175                 return;
176             }
177
178             if (CTX_DOWNLOAD_SERVLET.equals(servletPath)
179                     || FILE_DOWNLOAD_SERVLET.equals(servletPath))
180             {
181                 doDownload(request, response);
182                 return;
183             }
184
185             boolean isFileSystemPath = PATH_URL_SERVLET.equals(servletPath);
186
187             if (!pathInfo.endsWith("/"))
188             {
189                 response.sendRedirect(request.getRequestURL() + "/");
190                 return;
191             }
192
193             String JavaDoc queryString = request.getQueryString();
194
195             String JavaDoc pathTranslated = request.getPathTranslated();
196             String JavaDoc requestURI = request.getRequestURI();
197             String JavaDoc requestURL = request.getRequestURL().toString();
198
199             self = contextPath + servletPath;
200
201             RealPath theRealPath;
202
203             theRealPath = isFileSystemPath ? PathHelper.getFileRealPath(
204                     filebase, pathInfo) : PathHelper.getHttpRealPath(
205                     getServletContext(), pathInfo, dirmapping);
206
207             if (null == theRealPath)
208             {
209                 response.sendError(HttpServletResponse.SC_NOT_FOUND, request
210                         .getRequestURI());
211                 return;
212             }
213
214             String JavaDoc realPath = theRealPath.getRealPath();
215
216             String JavaDoc fileURL = requestURI.replaceFirst(contextPath, "");
217             fileURL = fileURL.replaceFirst(servletPath, "");
218
219             String JavaDoc fileViewUrl;
220
221             if (theRealPath.isHttpPath())
222             {
223                 if (pathInfo.startsWith(theRealPath.getContext() + "/WEB-INF"))
224                 {
225                     fileViewUrl = request.getContextPath()
226                             + CTX_DOWNLOAD_SERVLET + pathInfo;
227                 }
228                 else
229                 {
230                     fileViewUrl = fileURL;
231                 }
232             }
233             else
234             {
235                 fileViewUrl = request.getContextPath() + FILE_DOWNLOAD_SERVLET
236                         + pathInfo;
237             }
238
239             folder = new Folder(theRealPath, pathInfo, fileURL, fileViewUrl);
240
241             folder.load();
242
243             String JavaDoc actionresult = "";
244
245             if (FileUpload.isMultipartContent(request))
246             {
247                 try
248                 {
249                     actionresult = handleUpload(request, folder);
250                     folder.load();
251                 }
252                 catch (Exception JavaDoc e)
253                 {
254                     throw new ServletException JavaDoc(e.getMessage(), e);
255                 }
256             }
257             else if (null != queryString)
258             {
259                 try
260                 {
261                     actionresult = handleQuery(request, response, folder);
262                 }
263                 catch (OutOfSyncException e)
264                 {
265                     actionresult = e.getMessage();
266                 }
267                 if (null == actionresult) { return; }
268             }
269
270             request.setAttribute("actionresult", actionresult);
271         }
272         catch (SecurityException JavaDoc e)
273         {
274             request.setAttribute("actionresult", e.getClass().getName() + " "
275                     + e.getMessage());
276             request.setAttribute("fatalerror", new Boolean JavaDoc(true));
277
278         }
279
280         String JavaDoc s = request.getRemoteUser();
281         
282         Principal JavaDoc principal = request.getUserPrincipal();
283         
284         if (principal != null)
285         {
286             request.setAttribute("principal", principal.getName());
287         }
288         
289         request.setAttribute("self", self);
290
291         request.setAttribute("version", version);
292
293         request.setAttribute("serverInfo", getServletContext().getServerInfo());
294
295         request.setAttribute("url", contextPath);
296
297         request.setAttribute("path", pathInfo);
298
299         request.setAttribute("folder", folder);
300
301         String JavaDoc forward = "/WEB-INF/fm.jsp";
302
303         RequestDispatcher JavaDoc requestDispatcher = getServletContext()
304                 .getRequestDispatcher(forward);
305
306         requestDispatcher.forward(request, response);
307     }
308
309     private String JavaDoc handleQuery(HttpServletRequest JavaDoc request,
310             HttpServletResponse JavaDoc response, Folder folder)
311             throws OutOfSyncException, IOException JavaDoc
312     {
313         String JavaDoc rc = "";
314
315         String JavaDoc target = null;
316         int action = NOP_ACTION;
317         String JavaDoc[] selectedfiles = request.getParameterValues("index");
318
319         String JavaDoc logout = request.getParameter("logout");
320         if ("t".equals(logout))
321         {
322             request.getSession().invalidate();
323             return "";
324         }
325         
326         String JavaDoc sum = request.getParameter("sum");
327         if ("t".equals(sum))
328         {
329             folder.sum();
330             return "";
331         }
332         String JavaDoc sort = request.getParameter("sort");
333         if ("nd".equals(sort))
334         {
335             folder.sort(FileComparator.SORT_NAME_DOWN);
336             return "";
337         }
338         else if ("nu".equals(sort))
339         {
340             folder.sort(FileComparator.SORT_NAME_UP);
341             return "";
342         }
343         else if ("su".equals(sort))
344         {
345             folder.sort(FileComparator.SORT_SIZE_UP);
346             return "";
347         }
348         else if ("sd".equals(sort))
349         {
350             folder.sort(FileComparator.SORT_SIZE_DOWN);
351             return "";
352         }
353
354         else if ("du".equals(sort))
355         {
356             folder.sort(FileComparator.SORT_DATE_UP);
357             return "";
358         }
359         else if ("dd".equals(sort))
360         {
361             folder.sort(FileComparator.SORT_DATE_DOWN);
362             return "";
363         }
364
365         OutputStream JavaDoc out = null;
366
367         String JavaDoc command = request.getParameter("command");
368         if ("Mkdir".equals(command))
369         {
370             target = request.getParameter("newdir");
371             action = MKDIR_ACTION;
372         }
373         if ("GetURL".equals(command))
374         {
375             target = request.getParameter("url");
376             action = GETURL_ACTION;
377         }
378         else if ("Delete".equals(command))
379         {
380             action = DELETE_ACTION;
381         }
382         else if ("Rename".equals(command))
383         {
384             target = request.getParameter("renameto");
385             action = RENAME_ACTION;
386         }
387         else if ("Unzip".equals(command))
388         {
389             action = UNZIP_ACTION;
390         }
391         else if ("ZipDownload".equals(command))
392         {
393             action = ZIP_ACTION;
394             response.setContentType("application/zip");
395
396             response.setHeader("Content-Disposition",
397                     "inline; filename=\"jFMdownload.zip\"");
398
399             out = response.getOutputStream();
400         }
401         else if ("Copy".equals(command))
402         {
403             target = request.getParameter("copyto");
404             action = COPY_ACTION;
405         }
406         else if ("Move".equals(command))
407         {
408             target = request.getParameter("moveto");
409             action = MOVE_ACTION;
410         }
411         else if ("DeleteRecursively".equals(command))
412         {
413             target = request.getParameter("confirm");
414             action = DELETE_RECURSIVE_ACTION;
415         }
416         else if ("FtpUpload".equals(command))
417         {
418             target = request.getParameter("ftpto");
419             action = FTPUP_ACTION;
420         }
421         else if ("Join".equals(command))
422         {
423             action = JOIN_ACTION;
424         }
425         if (NOP_ACTION == action) { return ""; }
426
427         try
428         {
429             rc = folder.action(action, out, selectedfiles, target);
430         }
431         catch (SecurityException JavaDoc e)
432         {
433             rc = "SecurityException: " + e.getMessage();
434             return rc;
435         }
436
437         folder.load();
438
439         return rc;
440     }
441
442     private String JavaDoc handleUpload(HttpServletRequest JavaDoc request, Folder folder)
443             throws Exception JavaDoc
444     {
445         DiskFileUpload upload = new DiskFileUpload();
446         upload.setRepositoryPath(tempDir.toString());
447         System.out.println(upload.getSizeMax());
448
449         // parse this request by the handler
450
// this gives us a list of items from the request
451
List JavaDoc items = upload.parseRequest(request);
452
453         Iterator JavaDoc itr = items.iterator();
454
455         boolean unzip = false;
456
457         while (itr.hasNext())
458         {
459             FileItem item = (FileItem) itr.next();
460
461             // check if the current item is a form field or an uploaded file
462
if (item.isFormField())
463             {
464                 String JavaDoc name = item.getFieldName();
465                 String JavaDoc value = item.getString();
466                 if ("command".equals(name) && "unzip".equals(value))
467                 {
468                     unzip = true;
469                 }
470             }
471             else
472             {
473                 String JavaDoc name = item.getFieldName();
474                 unzip = "unzip".equals(name);
475
476                 if (!"".equals(item.getName()))
477                 {
478                     folder.upload(item, unzip);
479                 }
480                 // the item must be an uploaded file save it to disk. Note that there
481
// seems to be a bug in item.getName() as it returns the full path on
482
// the client's machine for the uploaded file name, instead of the file
483
// name only. To overcome that, I have used a workaround using
484
// fullFile.getName().
485
/*
486                  * File fullFile = new File(item.getName()); File savedFile = new
487                  * File(getServletContext().getRealPath("/"),
488                  */

489                 //item.write(savedFile);
490
}
491         }
492         return "";
493     }
494
495     public void doDownload(HttpServletRequest JavaDoc request,
496             HttpServletResponse JavaDoc response) throws IOException JavaDoc
497     {
498         String JavaDoc servletPath = request.getServletPath();
499
500         String JavaDoc pathInfo = request.getPathInfo();
501
502         RealPath realPath = null;
503
504         if (CTX_DOWNLOAD_SERVLET.equals(servletPath))
505         {
506             realPath = PathHelper.getHttpRealPath(getServletContext(),
507                     pathInfo, dirmapping);
508         }
509         else
510         {
511             realPath = PathHelper.getFileRealPath(filebase, pathInfo);
512         }
513
514         File JavaDoc f = new File JavaDoc(realPath.getRealPath());
515         String JavaDoc name = f.getName();
516
517         String JavaDoc mimeType = getServletContext().getMimeType(name);
518         
519         response.setContentType(mimeType);
520
521         response.setHeader("Content-Disposition", "inline; filename=\"" + name
522                 + "\"");
523
524         OutputStream JavaDoc out = response.getOutputStream();
525
526         FileInputStream JavaDoc in = new FileInputStream JavaDoc(f);
527
528         byte[] buf = new byte[512];
529         int l;
530
531         try
532         {
533             while ((l = in.read(buf)) > 0)
534             {
535                 out.write(buf, 0, l);
536             }
537         }
538         catch (IOException JavaDoc e)
539         {
540             throw e;
541         }
542         finally
543         {
544             in.close();
545         }
546
547     }
548 }
Popular Tags