KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > dinamica > StringUtil


1 package dinamica;
2
3 import java.io.BufferedReader JavaDoc;
4 import java.io.File JavaDoc;
5 import java.io.FileOutputStream JavaDoc;
6 import java.io.IOException JavaDoc;
7 import java.io.InputStream JavaDoc;
8 import java.io.InputStreamReader JavaDoc;
9 import java.io.PrintWriter JavaDoc;
10 import java.text.DecimalFormat JavaDoc;
11 import java.text.NumberFormat JavaDoc;
12 import java.text.SimpleDateFormat JavaDoc;
13 import java.util.Locale JavaDoc;
14 import java.net.*;
15
16
17 /**
18  * Core-level framework class: String and Date basic utility methods.
19  * <br><br>
20  * Encapsulates utility methods for everyday programming tasks
21  * with Strings, Dates and other common stuff.
22  * <br>
23  * Creation date: 18/09/2003<br>
24  * Last Update: 18/09/2003<br>
25  * (c) 2003 Martin Cordova<br>
26  * This code is released under the LGPL license<br>
27  * @author Martin Cordova (some code written by Carlos Pineda)
28  */

29 public class StringUtil
30 {
31
32     /**
33      * Replace ALL occurrences of [old value] with [new value]<br>
34      * This method was written by Carlos Pineda.
35      * @param source String to manipulate
36      * @param pattern Old value
37      * @param newText New value
38      * @return String with replaced text
39      */

40     public static String JavaDoc replace(String JavaDoc source, String JavaDoc pattern, String JavaDoc newText)
41     {
42
43         if (pattern == null || pattern.length() == 0 )
44             return source;
45
46         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(2*source.length());
47
48         int previndex=0;
49         int index=0;
50         int flen = pattern.length();
51         while (true) {
52             index = source.indexOf(pattern, previndex);
53             if (index == -1) {
54                 buf.append(source.substring(previndex));
55                 break;
56             }
57             buf.append( source.substring(previndex, index)).append( newText );
58             previndex = index + flen;
59         }
60         return buf.toString();
61         
62     }
63     
64     /**
65      * Format date using a mask and the default locale
66      * @param d Date object
67      * @param format Date mask, like yyyy-MM-dd or any valid java format
68      * @return String representing the formatted string
69      * @throws Throwable
70      */

71     public static String JavaDoc formatDate(java.util.Date JavaDoc d, String JavaDoc format) throws Throwable JavaDoc
72     {
73         SimpleDateFormat JavaDoc f = new SimpleDateFormat JavaDoc();
74         f.applyPattern(format);
75         return f.format(d);
76     }
77     
78     /**
79      * Format date using a mask and locale
80      * @param d Date object
81      * @param format Date mask, like yyyy-MM-dd or any valid java format
82      * @param loc Custom Locale
83      * @return String representing the formatted string
84      * @throws Throwable
85      */

86     public static String JavaDoc formatDate(java.util.Date JavaDoc d, String JavaDoc format, Locale JavaDoc loc) throws Throwable JavaDoc
87     {
88         SimpleDateFormat JavaDoc f = new SimpleDateFormat JavaDoc(format, loc);
89         return f.format(d);
90     }
91
92     /**
93      * Create a java.util.Date object from a String value and a format mask.<br>
94      * The java date formats are supported, for more information please consult the
95      * reference guide for the class <a HREF="http://java.sun.com/j2se/1.4.1/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat</a>.<br>
96      * <br>
97      * Sample code:<br>
98      * <pre>
99      * java.util.Date d = StringUtil.getDateObject("2003-12-07 17:00:00","yyyy-MM-dd HH:mm:ss");
100      * </pre>
101      * @param dateValue A String containg a valid date corresponding to dateFormat mask
102      * @param dateFormat The date format used to represent the date in dateValue
103      * @return A java.util.Date object representing the dateValue parameter
104      * @throws Throwable if dateValue is not represented in dateFormat
105      */

106     public static java.util.Date JavaDoc getDateObject(String JavaDoc dateValue, String JavaDoc dateFormat) throws Throwable JavaDoc
107     {
108         SimpleDateFormat JavaDoc x = new SimpleDateFormat JavaDoc(dateFormat);
109         x.setLenient(false);
110         return x.parse(dateValue);
111     }
112
113     /**
114      * Format a number using a valid Java format mask and the default Locale
115      * @param value Double, Integer or another numeric value
116      * @param numberFormat Java numeric format mask like #,##0.00
117      * @return String representing a formatted number acording to the numberFormat
118      * @throws Throwable
119      */

120     public static String JavaDoc formatNumber(Object JavaDoc value, String JavaDoc numberFormat) throws Throwable JavaDoc
121     {
122         DecimalFormat JavaDoc fmt = (DecimalFormat JavaDoc) NumberFormat.getInstance();
123         fmt.applyPattern(numberFormat);
124         return fmt.format(value);
125     }
126
127     /**
128      * Format a number using a valid Java format mask and a custom Locale
129      * @param value Double, Integer or another numeric value
130      * @param numberFormat Java numeric format mask like #,##0.00
131      * @param loc Custom Locale to use when formatting the number
132      * @return String representing a formatted number acording to the numberFormat
133      * @throws Throwable
134      */

135     public static String JavaDoc formatNumber(Object JavaDoc value, String JavaDoc numberFormat, Locale JavaDoc loc) throws Throwable JavaDoc
136     {
137         DecimalFormat JavaDoc fmt = (DecimalFormat JavaDoc) NumberFormat.getInstance(loc);
138         fmt.applyPattern(numberFormat);
139         return fmt.format(value);
140     }
141
142     /**
143      * Create an array of items from a string with delimiters to separate the items.
144      * This is a very simple wrapper around the native String.split method
145      * @param s String to split or separate in its parts
146      * @param separator Delimiter string, like a pipe or a tabulator
147      * @return Array of strings containing the separated items
148      */

149     public static String JavaDoc[] split(String JavaDoc s, String JavaDoc separator)
150     {
151         separator = "\\" + separator;
152         return s.split(separator);
153     }
154
155     /**
156      * Loads a text resource stored into the Web Application context paths
157      * @param path Path to the resource
158      * @return String containing the resource contents
159      * @throws Exception
160      */

161     public static String JavaDoc getResource(javax.servlet.ServletContext JavaDoc ctx, String JavaDoc path) throws Throwable JavaDoc
162     {
163         return getResource(ctx, path, System.getProperty("file.encoding", "ISO8859_1"));
164     }
165
166     /**
167      * Append message to file, this method is usually
168      * used to save log messages
169      * @param path File name
170      * @param message String to append to file
171      */

172     public static synchronized void saveMessage(String JavaDoc path, String JavaDoc message)
173     {
174
175         FileOutputStream JavaDoc fos = null;
176         PrintWriter JavaDoc pw = null;
177
178         try {
179             fos = new FileOutputStream JavaDoc(new File JavaDoc(path), true);
180             pw = new PrintWriter JavaDoc(fos, false);
181             pw.println(message);
182         }
183         catch (IOException JavaDoc e) {
184             
185             try
186             {
187                 String JavaDoc d = StringUtil.formatDate(new java.util.Date JavaDoc(), "yyyy-MM-dd HH:mm:ss");
188                 System.err.println("ERROR [dinamica.StringUtil.saveMessage@" + d + "]: " + e.getMessage());
189             }
190             catch (Throwable JavaDoc e1)
191             {
192             }
193         }
194         finally {
195             
196             try {
197                 if (pw != null)
198                     pw.close();
199                 if (fos != null)
200                     fos.close();
201             }
202             catch (IOException JavaDoc e) {
203             }
204             
205         }
206     }
207
208     /**
209      * Retrieve a text-based document using HTTP GET method.<br>
210      * May be used to retrieve XML documents, news feeds, etc.
211      * @param url A valid URL
212      * @param logStdout if TRUE then this method will print
213      * a tracelog via STDOUT
214      * @return a String containing the whole document
215      * @throws Throwable
216      */

217     public static String JavaDoc httpGet(String JavaDoc url, boolean logStdout) throws Throwable JavaDoc
218     {
219
220         final int bufferSize = 4096;
221         BufferedReader JavaDoc br = null;
222         HttpURLConnection urlc = null;
223         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
224         URL page = new URL(url);
225             
226         try
227         {
228             
229             if (logStdout)
230                 System.err.println("Waiting for reply...:" + url);
231             
232             urlc = (HttpURLConnection)page.openConnection();
233             urlc.setUseCaches(false);
234             
235             if (logStdout)
236             {
237                 System.err.println("Content-type = " + urlc.getContentType());
238                 System.err.println("Content-length = " + urlc.getContentLength());
239                 System.err.println("Response-code = " + urlc.getResponseCode());
240                 System.err.println("Response-message = " + urlc.getResponseMessage());
241             }
242             
243             int retCode = urlc.getResponseCode();
244             String JavaDoc retMsg = urlc.getResponseMessage();
245             if (retCode>=400)
246                 throw new Throwable JavaDoc("HTTP Error: " + retCode + " - " + retMsg + " - URL:" + url);
247                                                                                                    
248             br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(urlc.getInputStream()), bufferSize);
249             char buf[] = new char[bufferSize];
250             int bytesRead = 0;
251             
252             while (bytesRead!=-1)
253             {
254                 bytesRead = br.read(buf);
255                 if (bytesRead>0)
256                     buffer.append(buf,0,bytesRead);
257             }
258             
259             if (logStdout)
260             {
261                 System.err.println("Document received.");
262             }
263             
264             return buffer.toString();
265         }
266         catch (Throwable JavaDoc e)
267         {
268             throw e;
269         }
270         finally
271         {
272             if (br != null)
273                 br.close();
274             
275             if (urlc!=null)
276                 urlc.disconnect();
277         }
278
279     }
280
281     /**
282      * Loads a text resource stored into the Web Application context paths
283      * <br>
284      * PATCH 2005-02-17 (v2.0.3) - encoding support
285      * @param ctx Servlet context
286      * @param path Path to the resource
287      * @param encoding Canonical name of the encoding to be used to read the resource
288      * @return String containing the resource contents
289      * @throws Exception
290      */

291     public static String JavaDoc getResource(javax.servlet.ServletContext JavaDoc ctx, String JavaDoc path, String JavaDoc encoding) throws Throwable JavaDoc
292     {
293         
294         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(5000);
295         byte[] data = new byte[5000];
296
297         InputStream JavaDoc in = null;
298         
299         in = ctx.getResourceAsStream(path);
300         
301         try
302         {
303             if (in!=null)
304             {
305                 while (true)
306                 {
307                     int len = in.read(data);
308                     if (len!=-1)
309                     {
310                         buf.append( new String JavaDoc(data, 0, len, encoding) );
311                     }
312                     else
313                     {
314                         break;
315                     }
316                 }
317
318                 return buf.toString();
319
320             }
321             else
322             {
323                 throw new Throwable JavaDoc("Invalid path to resource: " + path);
324             }
325             
326         }
327         catch (Throwable JavaDoc e)
328         {
329             throw e;
330         }
331         finally
332         {
333             if (in!=null)
334             {
335                 try{
336                     in.close();
337                 } catch (Exception JavaDoc e){}
338             }
339         }
340         
341     }
342
343 }
344
Popular Tags