001: package dinamica;
002:
003: import java.io.BufferedReader;
004: import java.io.File;
005: import java.io.FileOutputStream;
006: import java.io.IOException;
007: import java.io.InputStream;
008: import java.io.InputStreamReader;
009: import java.io.PrintWriter;
010: import java.text.DecimalFormat;
011: import java.text.NumberFormat;
012: import java.text.SimpleDateFormat;
013: import java.util.Locale;
014: import java.net.*;
015:
016: /**
017: * Core-level framework class: String and Date basic utility methods.
018: * <br><br>
019: * Encapsulates utility methods for everyday programming tasks
020: * with Strings, Dates and other common stuff.
021: * <br>
022: * Creation date: 18/09/2003<br>
023: * Last Update: 18/09/2003<br>
024: * (c) 2003 Martin Cordova<br>
025: * This code is released under the LGPL license<br>
026: * @author Martin Cordova (some code written by Carlos Pineda)
027: */
028: public class StringUtil {
029:
030: /**
031: * Replace ALL occurrences of [old value] with [new value]<br>
032: * This method was written by Carlos Pineda.
033: * @param source String to manipulate
034: * @param pattern Old value
035: * @param newText New value
036: * @return String with replaced text
037: */
038: public static String replace(String source, String pattern,
039: String newText) {
040:
041: if (pattern == null || pattern.length() == 0)
042: return source;
043:
044: StringBuffer buf = new StringBuffer(2 * source.length());
045:
046: int previndex = 0;
047: int index = 0;
048: int flen = pattern.length();
049: while (true) {
050: index = source.indexOf(pattern, previndex);
051: if (index == -1) {
052: buf.append(source.substring(previndex));
053: break;
054: }
055: buf.append(source.substring(previndex, index)).append(
056: newText);
057: previndex = index + flen;
058: }
059: return buf.toString();
060:
061: }
062:
063: /**
064: * Format date using a mask and the default locale
065: * @param d Date object
066: * @param format Date mask, like yyyy-MM-dd or any valid java format
067: * @return String representing the formatted string
068: * @throws Throwable
069: */
070: public static String formatDate(java.util.Date d, String format)
071: throws Throwable {
072: SimpleDateFormat f = new SimpleDateFormat();
073: f.applyPattern(format);
074: return f.format(d);
075: }
076:
077: /**
078: * Format date using a mask and locale
079: * @param d Date object
080: * @param format Date mask, like yyyy-MM-dd or any valid java format
081: * @param loc Custom Locale
082: * @return String representing the formatted string
083: * @throws Throwable
084: */
085: public static String formatDate(java.util.Date d, String format,
086: Locale loc) throws Throwable {
087: SimpleDateFormat f = new SimpleDateFormat(format, loc);
088: return f.format(d);
089: }
090:
091: /**
092: * Create a java.util.Date object from a String value and a format mask.<br>
093: * The java date formats are supported, for more information please consult the
094: * reference guide for the class <a href="http://java.sun.com/j2se/1.4.1/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat</a>.<br>
095: * <br>
096: * Sample code:<br>
097: * <pre>
098: * java.util.Date d = StringUtil.getDateObject("2003-12-07 17:00:00","yyyy-MM-dd HH:mm:ss");
099: * </pre>
100: * @param dateValue A String containg a valid date corresponding to dateFormat mask
101: * @param dateFormat The date format used to represent the date in dateValue
102: * @return A java.util.Date object representing the dateValue parameter
103: * @throws Throwable if dateValue is not represented in dateFormat
104: */
105: public static java.util.Date getDateObject(String dateValue,
106: String dateFormat) throws Throwable {
107: SimpleDateFormat x = new SimpleDateFormat(dateFormat);
108: x.setLenient(false);
109: return x.parse(dateValue);
110: }
111:
112: /**
113: * Format a number using a valid Java format mask and the default Locale
114: * @param value Double, Integer or another numeric value
115: * @param numberFormat Java numeric format mask like #,##0.00
116: * @return String representing a formatted number acording to the numberFormat
117: * @throws Throwable
118: */
119: public static String formatNumber(Object value, String numberFormat)
120: throws Throwable {
121: DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance();
122: fmt.applyPattern(numberFormat);
123: return fmt.format(value);
124: }
125:
126: /**
127: * Format a number using a valid Java format mask and a custom Locale
128: * @param value Double, Integer or another numeric value
129: * @param numberFormat Java numeric format mask like #,##0.00
130: * @param loc Custom Locale to use when formatting the number
131: * @return String representing a formatted number acording to the numberFormat
132: * @throws Throwable
133: */
134: public static String formatNumber(Object value,
135: String numberFormat, Locale loc) throws Throwable {
136: DecimalFormat fmt = (DecimalFormat) NumberFormat
137: .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[] split(String s, String separator) {
150: separator = "\\" + separator;
151: return s.split(separator);
152: }
153:
154: /**
155: * Loads a text resource stored into the Web Application context paths
156: * @param path Path to the resource
157: * @return String containing the resource contents
158: * @throws Exception
159: */
160: public static String getResource(javax.servlet.ServletContext ctx,
161: String path) throws Throwable {
162: return getResource(ctx, path, System.getProperty(
163: "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 path,
173: String message) {
174:
175: FileOutputStream fos = null;
176: PrintWriter pw = null;
177:
178: try {
179: fos = new FileOutputStream(new File(path), true);
180: pw = new PrintWriter(fos, false);
181: pw.println(message);
182: } catch (IOException e) {
183:
184: try {
185: String d = StringUtil.formatDate(new java.util.Date(),
186: "yyyy-MM-dd HH:mm:ss");
187: System.err
188: .println("ERROR [dinamica.StringUtil.saveMessage@"
189: + d + "]: " + e.getMessage());
190: } catch (Throwable e1) {
191: }
192: } finally {
193:
194: try {
195: if (pw != null)
196: pw.close();
197: if (fos != null)
198: fos.close();
199: } catch (IOException e) {
200: }
201:
202: }
203: }
204:
205: /**
206: * Retrieve a text-based document using HTTP GET method.<br>
207: * May be used to retrieve XML documents, news feeds, etc.
208: * @param url A valid URL
209: * @param logStdout if TRUE then this method will print
210: * a tracelog via STDOUT
211: * @return a String containing the whole document
212: * @throws Throwable
213: */
214: public static String httpGet(String url, boolean logStdout)
215: throws Throwable {
216:
217: final int bufferSize = 4096;
218: BufferedReader br = null;
219: HttpURLConnection urlc = null;
220: StringBuffer buffer = new StringBuffer();
221: URL page = new URL(url);
222:
223: try {
224:
225: if (logStdout)
226: System.err.println("Waiting for reply...:" + url);
227:
228: urlc = (HttpURLConnection) page.openConnection();
229: urlc.setUseCaches(false);
230:
231: if (logStdout) {
232: System.err.println("Content-type = "
233: + urlc.getContentType());
234: System.err.println("Content-length = "
235: + urlc.getContentLength());
236: System.err.println("Response-code = "
237: + urlc.getResponseCode());
238: System.err.println("Response-message = "
239: + urlc.getResponseMessage());
240: }
241:
242: int retCode = urlc.getResponseCode();
243: String retMsg = urlc.getResponseMessage();
244: if (retCode >= 400)
245: throw new Throwable("HTTP Error: " + retCode + " - "
246: + retMsg + " - URL:" + url);
247:
248: br = new BufferedReader(new InputStreamReader(urlc
249: .getInputStream()), bufferSize);
250: char buf[] = new char[bufferSize];
251: int bytesRead = 0;
252:
253: while (bytesRead != -1) {
254: bytesRead = br.read(buf);
255: if (bytesRead > 0)
256: buffer.append(buf, 0, bytesRead);
257: }
258:
259: if (logStdout) {
260: System.err.println("Document received.");
261: }
262:
263: return buffer.toString();
264: } catch (Throwable e) {
265: throw e;
266: } finally {
267: if (br != null)
268: br.close();
269:
270: if (urlc != null)
271: urlc.disconnect();
272: }
273:
274: }
275:
276: /**
277: * Loads a text resource stored into the Web Application context paths
278: * <br>
279: * PATCH 2005-02-17 (v2.0.3) - encoding support
280: * @param ctx Servlet context
281: * @param path Path to the resource
282: * @param encoding Canonical name of the encoding to be used to read the resource
283: * @return String containing the resource contents
284: * @throws Exception
285: */
286: public static String getResource(javax.servlet.ServletContext ctx,
287: String path, String encoding) throws Throwable {
288:
289: StringBuffer buf = new StringBuffer(5000);
290: byte[] data = new byte[5000];
291:
292: InputStream in = null;
293:
294: in = ctx.getResourceAsStream(path);
295:
296: try {
297: if (in != null) {
298: while (true) {
299: int len = in.read(data);
300: if (len != -1) {
301: buf.append(new String(data, 0, len, encoding));
302: } else {
303: break;
304: }
305: }
306:
307: return buf.toString();
308:
309: } else {
310: throw new Throwable("Invalid path to resource: " + path);
311: }
312:
313: } catch (Throwable e) {
314: throw e;
315: } finally {
316: if (in != null) {
317: try {
318: in.close();
319: } catch (Exception e) {
320: }
321: }
322: }
323:
324: }
325:
326: /**
327: * Rounds a double to a given number of decimals.<br>
328: * Example: double x = StringUtil.round(100.0500023, 4);<br>
329: * yields: x = 100.0500<nr>
330: * @param n Number
331: * @param decimals Number of decimals to use in the trim operation
332: * @return A double with trimmed decimals.
333: * @throws Throwable
334: */
335: public static double round(double n, int decimals) throws Throwable {
336:
337: String dec = "";
338: for (int i = 0; i < decimals; i++) {
339: dec = dec + "0";
340: }
341: String num = dinamica.StringUtil.formatNumber(new Double(n),
342: "#." + dec);
343: num = dinamica.StringUtil.replace(num, ",", ".");
344: return Double.parseDouble(num);
345: }
346:
347: }
|