KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > methodhead > res > ResUtils


1 /*
2  * Copyright (C) 2006 Methodhead Software LLC. All rights reserved.
3  *
4  * This file is part of TransferCM.
5  *
6  * TransferCM is free software; you can redistribute it and/or modify it under the
7  * terms of the GNU General Public License as published by the Free Software
8  * Foundation; either version 2 of the License, or (at your option) any later
9  * version.
10  *
11  * TransferCM is distributed in the hope that it will be useful, but WITHOUT ANY
12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14  * details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * TransferCM; if not, write to the Free Software Foundation, Inc., 51 Franklin St,
18  * Fifth Floor, Boston, MA 02110-1301 USA
19  */

20
21 package com.methodhead.res;
22
23 import org.apache.commons.io.FileUtils;
24 import java.io.File JavaDoc;
25 import java.io.IOException JavaDoc;
26 import javax.servlet.http.HttpServlet JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import com.methodhead.tree.FoldingTreeNode;
30 import javax.servlet.http.HttpServletRequest JavaDoc;
31 import org.apache.struts.action.ActionMapping;
32
33 /**
34  * A collection of utility methods used in the
35  * <tt>com.methodhead.res</tt> package.
36  */

37 public class ResUtils {
38
39   // constructors /////////////////////////////////////////////////////////////
40

41   // constants ////////////////////////////////////////////////////////////////
42

43   // classes //////////////////////////////////////////////////////////////////
44

45   // methods //////////////////////////////////////////////////////////////////
46

47   /**
48    * Returns <tt>true</tt> if <tt>name</tt> has an unsafe file extension
49    * (<tt>.jsp</tt> to <tt>.do</tt>).
50    */

51   public static boolean isSafeFileName(
52     String JavaDoc name ) {
53
54     return
55       !name.toLowerCase().endsWith( ".jsp" ) &&
56       !name.toLowerCase().endsWith( ".do" );
57   }
58
59   /**
60    * Returns <tt>true</tt> if <tt>name</tt> doesn't contain any invalid
61    * characters (<tt>\</tt>, <tt>/</tt>).
62    */

63   public static boolean isValidFileName(
64     String JavaDoc name ) {
65
66     return
67       ( name.indexOf( '/' ) == -1 ) &&
68       ( name.indexOf( '\\' ) == -1 );
69   }
70
71   /**
72    * Returns <tt>true</tt> if <tt>path</tt> doesn't contain any invalid
73    * characters sequences (<tt>&#046;&#046;</tt>).
74    */

75   public static boolean isValidPath(
76     String JavaDoc path ) {
77
78     if ( path == null )
79       return false;
80
81     return path.indexOf( ".." ) == -1;
82   }
83
84   /**
85    * Replaces any consecutive file separators with a single file separator.
86    */

87   public static String JavaDoc cleanPath(
88     String JavaDoc path ) {
89     return path.replaceAll( "" + File.separator + "+", File.separator );
90   }
91
92   /**
93    * Trims any leading or trailing spaces and separator characters from
94    * <tt>path</tt>.
95    */

96   public static String JavaDoc trimPath(
97     String JavaDoc path ) {
98
99     path = path.trim();
100
101     if ( path.startsWith( "/" ) )
102       path = path.substring( 1 );
103
104     if ( path.endsWith( "/" ) )
105       path = path.substring( 0, path.length() - 1 );
106
107     return path;
108   }
109
110   /**
111    * Returns <tt>true</tt> if <tt>path</tt> is contained by <tt>parentPath</tt>
112    * at some level. If <tt>path</tt> equals <tt>parentPath</tt> this method
113    * will also return <tt>true</tt>. This method is strictly a string
114    * operation; no files are actually accessed. The path separator is always
115    * assumed to be a forward slash (<tt>/</tt>). Any leading or trailing
116    * spaces and separator characters are trimmed from both paths before any
117    * tests are performed.
118    */

119   public static boolean isPathDescendent(
120     String JavaDoc parentPath,
121     String JavaDoc path ) {
122
123     if ( ( parentPath == null ) || ( path == null ) )
124       return false;
125
126     parentPath = trimPath( parentPath );
127     path = trimPath( path );
128
129     if ( path.startsWith( parentPath ) )
130       return true;
131
132     return false;
133   }
134
135   /**
136    * Copies <tt>from</tt> to <tt>to</tt>; if <tt>from</tt> is a directory, it
137    * is recursively copied. If <tt>to</tt> is exists and is not a directory,
138    * it is overwritten. If <tt>to</tt> is exists and is a directory, the
139    * contents of <tt>from</tt> are copied over the contents of <tt>to</tt>. If
140    * <tt>to</tt> exists, but is a directory when <tt>from</tt> is not (or vice
141    * versa), an exception is thrown. NOT UNIT TESTED
142    */

143   public static void copyFile(
144     File JavaDoc from,
145     File JavaDoc to )
146   throws
147     ResException,
148     IOException JavaDoc {
149
150     if ( from.isDirectory() ) {
151       if ( to.exists() ) {
152         if ( !to.isDirectory() )
153           throw new ResException(
154             "Can't copy directory over non-directory: " +
155             to.getAbsolutePath() );
156       }
157       else {
158         to.mkdir();
159       }
160
161       //
162
// recurse into directory
163
//
164
File JavaDoc[] files = from.listFiles();
165
166       for ( int i = 0; i < files.length; i++ )
167         copyFile( files[ i ], new File JavaDoc( to, files[ i ].getName() ) );
168     }
169     else {
170       if ( to.exists() && to.isDirectory() )
171         throw new ResException(
172           "Can't copy non-directory over directory: " +
173           to.getAbsolutePath() );
174
175       FileUtils.copyFile( from, to );
176     }
177   }
178
179   /**
180    * Deletes <tt>file</tt>; if <tt>file</tt> is a directory, it is recursively
181    * deleted.
182    */

183   public static void deleteFile(
184     File JavaDoc file ) {
185
186     if ( file.isDirectory() ) {
187
188       File JavaDoc[] files = file.listFiles();
189       for ( int i = 0; i < files.length; i++ ) {
190         deleteFile( files[ i ] );
191       }
192     }
193
194     file.delete();
195   }
196
197   /**
198    * Returns a file by combining <tt>path</tt> and <tt>fileName</tt> and using
199    * it as a path relative to the webapp.
200    */

201   public static File JavaDoc getFile(
202     HttpServlet JavaDoc servlet,
203     String JavaDoc path,
204     String JavaDoc fileName ) {
205
206     return
207       new File JavaDoc(
208         servlet.getServletContext().getRealPath(
209           path + File.separator + fileName ) );
210   }
211
212   /**
213    * NOT UNIT TESTED Converts a list of <tt>FoldingTreeNode</tt>s (as created
214    * in {@link ResForm#reset ResForm.reset()}) to an array of filenames.
215    */

216   public static String JavaDoc[] nodesToFileNames (
217     List JavaDoc nodes ) {
218
219     String JavaDoc[] fileNames = new String JavaDoc[ nodes.size() ];
220     int i = 0;
221     for ( Iterator JavaDoc iter = nodes.iterator(); iter.hasNext(); )
222       fileNames[ i++ ] = ( ( FoldingTreeNode )iter.next() ).getLabel();
223
224     return fileNames;
225   }
226
227   /**
228    * NOT UNIT TESTED Returns the file manager in the request, creating and
229    * initializing one if necessary.
230    */

231   public static FileManager getFileManager(
232     ResPolicy policy,
233     HttpServletRequest JavaDoc request ) {
234
235     FileManager fileManager =
236       ( FileManager )request.getAttribute( ResGlobals.FILEMANAGER_KEY );
237
238     if ( fileManager == null ) {
239       fileManager = policy.newFileManager();
240       policy.initFileManager( request, fileManager );
241       request.setAttribute( ResGlobals.FILEMANAGER_KEY, fileManager );
242     }
243
244     return fileManager;
245   }
246
247   /**
248    * NOT UNIT TESTED Instantiates the <tt>ResPolicy</tt> for defined in
249    * <tt>mapping</tt>'s parameter.
250    */

251   public static ResPolicy getPolicy(
252     ActionMapping mapping ) {
253
254     try {
255       return
256         ( ResPolicy )Class.forName( mapping.getParameter() ).newInstance();
257     }
258     catch ( Exception JavaDoc e ) {
259       throw new ResException(
260         "Unexpected exception while instantiating \"" +
261         mapping.getParameter() +"\":" + e.toString() );
262     }
263   }
264
265   /**
266    * Returns the file tree from the session, creating and initializing it if
267    * necessary.
268    */

269   public static FileTree getFileTree(
270     ResPolicy policy,
271     HttpServletRequest JavaDoc request ) {
272
273     FileTree fileTree =
274       ( FileTree )request.getSession().getAttribute( ResGlobals.FILETREE_KEY );
275
276     if ( fileTree == null ) {
277       fileTree = policy.newFileTree();
278       fileTree.build( getFileManager( policy, request ) );
279
280       request.getSession().setAttribute( ResGlobals.FILETREE_KEY, fileTree );
281     }
282
283     return fileTree;
284   }
285
286   // properties ///////////////////////////////////////////////////////////////
287

288   // attributes ///////////////////////////////////////////////////////////////
289
}
290
Popular Tags