001: /**********************************************************************
002: Copyright (c) 2003 Andy Jefferson and others. All rights reserved.
003: Licensed under the Apache License, Version 2.0 (the "License");
004: you may not use this file except in compliance with the License.
005: You may obtain a copy of the License at
006:
007: http://www.apache.org/licenses/LICENSE-2.0
008:
009: Unless required by applicable law or agreed to in writing, software
010: distributed under the License is distributed on an "AS IS" BASIS,
011: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012: See the License for the specific language governing permissions and
013: limitations under the License.
014:
015:
016: Contributors:
017: 2003 Erik Bengtson - moved replaceAll from Column class to here
018: 2004 Andy Jefferson - moved intArrayToString, booleanArrayToString from SM
019: 2007 Xuan Baldauf - toJVMIDString hex fix
020: ...
021: **********************************************************************/package org.jpox.util;
022:
023: import java.io.File;
024: import java.io.IOException;
025: import java.io.PrintWriter;
026: import java.io.StringWriter;
027: import java.net.URLDecoder;
028: import java.util.Collection;
029: import java.util.Iterator;
030: import java.util.Properties;
031: import java.util.StringTokenizer;
032: import java.util.jar.JarFile;
033:
034: /**
035: * Utilities for String manipulation.
036: *
037: * @version $Revision: 1.23 $
038: **/
039: public class StringUtils {
040: /**
041: * Convert an exception to a String with full stack trace
042: * @param ex the exception
043: * @return a String with the full stacktrace error text
044: */
045: public static String getStringFromStackTrace(Throwable ex) {
046: if (ex == null) {
047: return "";
048: }
049: StringWriter str = new StringWriter();
050: PrintWriter writer = new PrintWriter(str);
051: try {
052: ex.printStackTrace(writer);
053: return str.getBuffer().toString();
054: } finally {
055: try {
056: str.close();
057: writer.close();
058: } catch (IOException e) {
059: //ignore
060: }
061: }
062: }
063:
064: /**
065: * Convenience method to get a File for the specified filename.
066: * Caters for URL-encoded characters in the filename (treatment of spaces on Windows etc)
067: * @param filename Name of file
068: * @return The File
069: */
070: public static File getFileForFilename(String filename) {
071: return new File(getDecodedStringFromURLString(filename));
072: }
073:
074: /**
075: * Convenience method to get a JarFile for the specified filename.
076: * Caters for URL-encoded characters in the filename (treatment of spaces on Windows etc)
077: * @param filename Name of file
078: * @return The JarFile
079: */
080: public static JarFile getJarFileForFilename(String filename)
081: throws IOException {
082: return new JarFile(getDecodedStringFromURLString(filename));
083: }
084:
085: /**
086: * Convenience method to decode a URL string for use (so spaces are allowed)
087: * @param urlString The URL string
088: * @return The string
089: */
090: public static String getDecodedStringFromURLString(String urlString) {
091: return URLDecoder.decode(urlString);
092: }
093:
094: /**
095: * Replaces each substring of this string that matches toReplace.
096: * Used to replace replaceAll when using J2SDK 1.3.1.
097: * This method is available at String.replaceAll in J2SDK 1.4
098: * @param theString The string to use
099: * @param toReplace The string to replace.
100: * @param replacement The replacement string.
101: * @return The updated string after replacing.
102: */
103: public static String replaceAll(String theString, String toReplace,
104: String replacement) {
105: if (theString == null) {
106: return null;
107: }
108: if (theString.indexOf(toReplace) == -1) {
109: return theString;
110: }
111:
112: StringBuffer stringBuffer = new StringBuffer(theString);
113: int index = theString.length();
114: int offset = toReplace.length();
115: while ((index = theString.lastIndexOf(toReplace, index - 1)) > -1) {
116: stringBuffer.replace(index, index + offset, replacement);
117: }
118:
119: return stringBuffer.toString();
120: }
121:
122: /**
123: * Utility to check if a string is whitespace.
124: * If the string is null, returns true also.
125: * @param str The string to check
126: * @return Whether the string is just whitespace
127: */
128: public static boolean isWhitespace(String str) {
129: return str == null || (str.trim().length() == 0);
130: }
131:
132: /**
133: * Utility to tell if two strings are the same. Extends the basic
134: * String 'equals' method by allowing for nulls.
135: * @param str1 The first string
136: * @param str2 The second string
137: * @return Whether the strings are equal.
138: */
139: public static boolean areStringsEqual(String str1, String str2) {
140: if (str1 == null && str2 == null) {
141: return true;
142: } else if (str1 == null && str2 != null) {
143: return false;
144: } else if (str1 != null && str2 == null) {
145: return false;
146: } else {
147: return str1.equals(str2);
148: }
149: }
150:
151: /** Utility to return a left-aligned version of a string padded to the
152: * number of characters specified.
153: * @param input The input string
154: * @param length The length desired
155: * @return The updated string
156: **/
157: public static String leftAlignedPaddedString(String input,
158: int length) {
159: if (length <= 0) {
160: return null;
161: }
162:
163: StringBuffer output = new StringBuffer();
164: char space = ' ';
165:
166: if (input != null) {
167: if (input.length() < length) {
168: output.append(input);
169: for (int i = input.length(); i < length; i++) {
170: output.append(space);
171: }
172: } else {
173: output.append(input.substring(0, length));
174: }
175: } else {
176: for (int i = 0; i < length; i++) {
177: output.append(space);
178: }
179: }
180:
181: return output.toString();
182: }
183:
184: /** Utility to return a right-aligned version of a string padded to the
185: * number of characters specified.
186: * @param input The input string
187: * @param length The length desired
188: * @return The updated string
189: **/
190: public static String rightAlignedPaddedString(String input,
191: int length) {
192: if (length <= 0) {
193: return null;
194: }
195:
196: StringBuffer output = new StringBuffer();
197: char space = ' ';
198:
199: if (input != null) {
200: if (input.length() < length) {
201: for (int i = input.length(); i < length; i++) {
202: output.append(space);
203: }
204: output.append(input);
205: } else {
206: output.append(input.substring(0, length));
207: }
208: } else {
209: for (int i = 0; i < length; i++) {
210: output.append(space);
211: }
212: }
213:
214: return output.toString();
215: }
216:
217: /**
218: * Splits a list of values separated by a token
219: * @param valuesString the text to be splited
220: * @param token the token
221: * @return an array with all values
222: */
223: public static String[] split(String valuesString, String token) {
224: String[] values;
225: if (valuesString != null) {
226: StringTokenizer tokenizer = new StringTokenizer(
227: valuesString, token);
228:
229: values = new String[tokenizer.countTokens()];
230: int count = 0;
231: while (tokenizer.hasMoreTokens()) {
232: values[count++] = tokenizer.nextToken();
233: }
234: } else {
235: values = null;
236: }
237: return values;
238: }
239:
240: /**
241: * Utility to convert an object to a JVM type string.
242: * Returns the same as would have been output from Object.toString() if the class hadn't overridden it.
243: * @param obj The object
244: * @return The String version
245: **/
246: public static String toJVMIDString(Object obj) {
247: if (obj == null) {
248: return "null";
249: } else {
250: return obj.getClass().getName() + '@'
251: + Integer.toHexString(System.identityHashCode(obj)); // we should align to the Java VM way of printing identity hash codes, that means: hexadecimal
252: }
253: }
254:
255: /**
256: * Utility to convert a boolean[] to a String.
257: * @param ba The boolean[]
258: * @return String version
259: **/
260: public static String booleanArrayToString(boolean[] ba) {
261: if (ba == null) {
262: return "null";
263: }
264:
265: StringBuffer sb = new StringBuffer("[");
266: for (int i = 0; i < ba.length; ++i) {
267: sb.append(ba[i] ? 'Y' : 'N');
268: }
269: sb.append(']');
270:
271: return sb.toString();
272: }
273:
274: /**
275: * Utility to convert an int[] to a String.
276: * @param ia The int[]
277: * @return String version
278: **/
279: public static String intArrayToString(int[] ia) {
280: if (ia == null) {
281: return "null";
282: }
283:
284: StringBuffer sb = new StringBuffer("[");
285: for (int i = 0; i < ia.length; ++i) {
286: if (i > 0) {
287: sb.append(", ");
288: }
289:
290: sb.append(ia[i]);
291: }
292: sb.append(']');
293:
294: return sb.toString();
295: }
296:
297: /**
298: * Utility to convert an Object[] to a String.
299: * @param arr The Object[]
300: * @return String version
301: **/
302: public static String objectArrayToString(Object[] arr) {
303: if (arr == null) {
304: return "null";
305: }
306:
307: StringBuffer sb = new StringBuffer("[");
308: for (int i = 0; i < arr.length; ++i) {
309: if (i > 0) {
310: sb.append(", ");
311: }
312: sb.append(arr[i]);
313: }
314: sb.append(']');
315:
316: return sb.toString();
317: }
318:
319: /**
320: * Converts the given collection of objects to string as a comma-separated
321: * list. If the list is empty the string "<none>" is returned.
322: *
323: * @param coll collection of objects to be converted
324: * @return A string containing each object in the given collection,
325: * converted toString() and separated by commas.
326: */
327: public static String collectionToString(Collection coll) {
328: if (coll.isEmpty()) {
329: return "<none>";
330: } else {
331: StringBuffer s = new StringBuffer();
332: Iterator iter = coll.iterator();
333: while (iter.hasNext()) {
334: if (s.length() > 0) {
335: s.append(", ");
336: }
337:
338: s.append(iter.next());
339: }
340:
341: return s.toString();
342: }
343: }
344:
345: /**
346: * Utility to check if a name is a valid Java identifier.
347: * Used by JDOQL in validating the names of parameters/variables.
348: * @param s The name
349: * @return Whether it is a valid identifier in Java.
350: **/
351: public static boolean isValidJavaIdentifierForJDOQL(String s) {
352: int len = s.length();
353:
354: if (len < 1) {
355: return false;
356: }
357:
358: if (s.equals("this")) {
359: // Use of "this" is restricted in JDOQL
360: return false;
361: }
362:
363: char[] c = new char[len];
364: s.getChars(0, len, c, 0);
365:
366: if (!Character.isJavaIdentifierStart(c[0])) {
367: return false;
368: }
369:
370: for (int i = 1; i < len; ++i) {
371: if (!Character.isJavaIdentifierPart(c[i])) {
372: return false;
373: }
374: }
375:
376: return true;
377: }
378:
379: /**
380: * Convenience method to extract an integer property value from a Properties file.
381: * @param props The Properties
382: * @param propName Name of the property
383: * @param defaultValue The default value to use (in case not specified)
384: * @return The value
385: */
386: public static int getIntValueForProperty(Properties props,
387: String propName, int defaultValue) {
388: int value = defaultValue;
389: if (props != null && props.containsKey(propName)) {
390: try {
391: value = (new Integer(props.getProperty(propName)))
392: .intValue();
393: } catch (NumberFormatException nfe) {
394: // Do nothing
395: }
396: }
397: return value;
398: }
399:
400: /**
401: * check string is null or length is 0.
402: * @param s check string
403: * @return return true if string is null or length is 0. return false other case.
404: */
405: public static boolean isEmpty(String s) {
406: return ((s == null) || (s.length() == 0));
407: }
408:
409: /**
410: * check string isnot null and length > 0.
411: * @param s check string
412: * @return return true if string isnot null and length greater than 0. return false other case.
413: */
414: public static boolean notEmpty(String s) {
415: return ((s != null) && (s.length() > 0));
416: }
417: }
|