KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > soto > util > Utils


1 package org.sapia.soto.util;
2
3 import org.sapia.util.text.TemplateContextIF;
4 import org.sapia.util.text.TemplateElementIF;
5 import org.sapia.util.text.TemplateException;
6 import org.sapia.util.text.TemplateFactory;
7
8 import java.io.BufferedReader JavaDoc;
9 import java.io.ByteArrayInputStream JavaDoc;
10 import java.io.File JavaDoc;
11 import java.io.IOException JavaDoc;
12 import java.io.InputStream JavaDoc;
13 import java.io.InputStreamReader JavaDoc;
14 import java.io.StringWriter JavaDoc;
15
16 import java.lang.reflect.Field JavaDoc;
17
18 import java.util.ArrayList JavaDoc;
19 import java.util.HashSet JavaDoc;
20 import java.util.List JavaDoc;
21 import java.util.Set JavaDoc;
22
23
24 /**
25  * This class holds various utility methods.
26  *
27  * @author Yanick Duchesne
28  * <dl>
29  * <dt><b>Copyright:</b><dd>Copyright &#169; 2002-2003 <a HREF="http://www.sapia-oss.org">Sapia Open Source Software</a>. All Rights Reserved.</dd></dt>
30  * <dt><b>License:</b><dd>Read the license.txt file of the jar or visit the
31  * <a HREF="http://www.sapia-oss.org/license.html">license page</a> at the Sapia OSS web site</dd></dt>
32  * </dl>
33  */

34 public class Utils {
35   /**
36    * Splits the given string into parts delimited by the given "split" character.
37    *
38    * @param toSplit the <code>String</code> to split.
39    * @param splitChar the delimiting character.
40    * @param trim if <code>true</code>, the tokens resulting from the split will be trimed.
41    * @return an array of <code>String</code>s corresponding to the tokens that resulted from
42    * the split.
43    */

44   public static String JavaDoc[] split(String JavaDoc toSplit, char splitChar, boolean trim) {
45     List JavaDoc tokens = new ArrayList JavaDoc();
46
47     StringBuffer JavaDoc token = new StringBuffer JavaDoc();
48
49     for (int i = 0; i < toSplit.length(); i++) {
50       if (toSplit.charAt(i) == splitChar) {
51         if (trim) {
52           tokens.add(token.toString().trim());
53         } else {
54           tokens.add(token.toString());
55         }
56
57         token.delete(0, token.length());
58       } else {
59         token.append(toSplit.charAt(i));
60       }
61     }
62
63     if (token.length() > 0) {
64       if (trim) {
65         tokens.add(token.toString().trim());
66       } else {
67         tokens.add(token.toString());
68       }
69     }
70
71     return (String JavaDoc[]) tokens.toArray(new String JavaDoc[tokens.size()]);
72   }
73
74   /**
75    * This method uses Java's introspection features to copy the fields of a source
76    * object to a target object.
77    *
78    * @param src the source object.
79    * @param trg the target object.
80    *
81    * @throws Exception if a problem occurs performing this operation, especially if security
82    * credentials are violated.
83    */

84   public static void copyFields(Object JavaDoc src, Object JavaDoc trg)
85     throws Exception JavaDoc {
86     copyFields(src.getClass(), src, trg);
87   }
88
89   /**
90    * Returns whether the given path is relative or not.
91    * @param path a path.
92    * @return returns <code>true</code> if the given path is relative.
93    */

94   public static boolean isRelativePath(String JavaDoc path) {
95     path = path.trim();
96
97     if (path.length() > 0) {
98       return !hasScheme(path) &&
99       ((path.charAt(0) != '/') && (path.charAt(0) != '\\') &&
100       (path.charAt(0) != '.'));
101     }
102
103     return false;
104   }
105
106   /**
107    * Tests if the given path has a protocol/scheme.
108    *
109    * @param path the path on which to perform the test.
110    * @return <code>true</code> if path has a scheme.
111    */

112   public static boolean hasScheme(String JavaDoc path) {
113     if (path == null) {
114       return false;
115     }
116
117     return path.indexOf(":/") >= 0;
118   }
119
120   /**
121    * Chops the scheme/protocol from the given URL path and returns the path
122    * without the scheme.
123    *
124    * @param path a URL path.
125    * @return the path without the scheme, or the given path, if it has no scheme.
126    */

127   public static String JavaDoc chopScheme(String JavaDoc path) {
128     int idx = path.indexOf(":/");
129
130     if (idx >= 0) {
131       String JavaDoc toReturn = path.substring(idx + 2);
132
133       if (File.separator.equals("/") && (toReturn.charAt(0) != '/')) {
134         return File.separator + toReturn;
135       } else {
136         return toReturn;
137       }
138     }
139
140     return path;
141   }
142
143   /**
144    * Returns the scheme of the given URL path.
145    * @param path a URL path.
146    * @return the scheme of the given URL path, or <code>null</code> if
147    * URL is not valid (i.e.: does not have a scheme/protocol).
148    */

149   public static String JavaDoc getScheme(String JavaDoc path) {
150     int idx = path.indexOf(":/");
151
152     if (idx >= 0) {
153       return path.substring(0, idx);
154     } else {
155       return null;
156     }
157   }
158
159   /**
160    * Performs variable interpolation on a passed in stream, and returns the
161    * resulting stream.
162    *
163    * @param ctx a <code>TemplateContextIF</code>.
164    * @param is an <code>InputStream</code>.
165    * @param resourceName the "name" of the passed in stream - used if an error is
166    * generated.
167    *
168    * @return the interpolated <code>InputStream</code>.
169    * @throws IOException if a problem occus.
170    */

171   public static InputStream JavaDoc replaceVars(TemplateContextIF ctx, InputStream JavaDoc is,
172     String JavaDoc resourceName) throws IOException JavaDoc {
173     String JavaDoc txt = textStreamToString(is);
174
175     try {
176       TemplateFactory fac = new TemplateFactory();
177       TemplateElementIF elem = fac.parse(txt);
178
179       return new ByteArrayInputStream JavaDoc(elem.render(ctx).getBytes());
180     } catch (TemplateException e) {
181       e.printStackTrace();
182       throw new IOException JavaDoc("Could not replace variables in content: " +
183         resourceName + " - " + e.getMessage());
184     } finally {
185       is.close();
186     }
187   }
188
189   /**
190    * Returns the data of the given text stream as a string.
191    * <p>
192    * IMPORTANT: the input stream is not closed by this method.
193    *
194    * @param is an <code>InputStream</code> of character data.
195    * @return the data of the given test stream.
196    * @throws IOException if a problem occurs.
197    */

198   public static String JavaDoc textStreamToString(InputStream JavaDoc is)
199     throws IOException JavaDoc {
200     BufferedReader JavaDoc reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is), 1024);
201     String JavaDoc line;
202     StringWriter JavaDoc writer = new StringWriter JavaDoc();
203
204     while ((line = reader.readLine()) != null) {
205       writer.write(line);
206       writer.write(System.getProperty("line.separator"));
207     }
208
209     return writer.getBuffer().toString();
210   }
211
212   /**
213    * Returns the path corresponding to the given base path, and the
214    * given relative path - results in "concatenation" of both, sort of.
215    * <pre>
216    * // will print: /opt/some/path/relative/path
217    * System.out.println("/opt/some/path", "relative/path", false);
218    *
219    * // will print: /opt/some/relative/path
220    * System.out.println("/opt/some/file.txt", "relative/path", true);
221    * </pre>
222    *
223    * @param base a base path.
224    * @param relative the path to evaluate relatively to the given path.
225    * @param isBaseFile if <code>true</code>, indicates that the base path
226    * corresponds to a file.
227    * @return the evaluated path.
228    */

229   public static String JavaDoc getRelativePath(String JavaDoc base, String JavaDoc relative,
230     boolean isBaseFile) {
231     String JavaDoc toReturn;
232     String JavaDoc compared = base.replace('\\', '/');
233
234     if (isBaseFile) {
235       int idx;
236
237       if ((idx = compared.lastIndexOf('/')) >= 0) {
238         toReturn = base.substring(0, idx) + File.separator + relative;
239       } else {
240         toReturn = base + File.separator + relative;
241       }
242     } else {
243       if (compared.endsWith("//")) {
244         toReturn = base + relative;
245       } else {
246         toReturn = base + File.separator + relative;
247       }
248     }
249
250     return toReturn;
251   }
252
253   /**
254    * Returns the classes that the given object is an instance of.
255    *
256    * @param src the "source" object.
257    * @return the array of <code>Class</code> objects of which the given object is an instance.
258    */

259   public static Class JavaDoc[] getClasses(Object JavaDoc src) {
260     Set JavaDoc classes = new HashSet JavaDoc();
261     getClasses(classes, src.getClass());
262
263     return (Class JavaDoc[]) classes.toArray(new Class JavaDoc[classes.size()]);
264   }
265
266   private static void getClasses(Set JavaDoc classes, Class JavaDoc current) {
267     Class JavaDoc[] classArr = current.getInterfaces();
268
269     for (int i = 0; i < classArr.length; i++) {
270       classes.add(classArr[i]);
271       getClasses(classes, classArr[i]);
272     }
273
274     current = current.getSuperclass();
275
276     if (current != null) {
277       getClasses(classes, current);
278     }
279   }
280
281   private static void copyFields(Class JavaDoc current, Object JavaDoc src, Object JavaDoc trg)
282     throws Exception JavaDoc {
283     Field JavaDoc[] fields = current.getDeclaredFields();
284     Object JavaDoc value;
285
286     for (int i = 0; i < fields.length; i++) {
287       if (!fields[i].isAccessible()) {
288         fields[i].setAccessible(true);
289       }
290
291       value = fields[i].get(src);
292       fields[i].set(trg, value);
293     }
294
295     current = current.getSuperclass();
296
297     if (current != null) {
298       copyFields(current, src, trg);
299     }
300   }
301 }
302
Popular Tags