Author: jverhaeg(a)redhat.com
Date: 2008-05-07 12:25:17 -0400 (Wed, 07 May 2008)
New Revision: 120
Modified:
trunk/dna-common/src/main/java/org/jboss/dna/common/i18n/I18n.java
trunk/dna-common/src/main/java/org/jboss/dna/common/util/Logger.java
trunk/dna-common/src/main/java/org/jboss/dna/common/util/StringUtil.java
trunk/dna-common/src/test/java/org/jboss/dna/common/i18n/I18nTest.java
trunk/dna-common/src/test/java/org/jboss/dna/common/util/StringUtilTest.java
Log:
DNA-59: Removed I18n.replaceParameters methods and replaced all usages with
StringUtil.createString, which now contains the same logic sans i18n stuff. The I18n
usage of createString modifies any thrown exception to include information identifying
where the exception occurred. Also added some test cases for createString to
StringUtilTest.
Modified: trunk/dna-common/src/main/java/org/jboss/dna/common/i18n/I18n.java
===================================================================
--- trunk/dna-common/src/main/java/org/jboss/dna/common/i18n/I18n.java 2008-05-07 13:37:37
UTC (rev 119)
+++ trunk/dna-common/src/main/java/org/jboss/dna/common/i18n/I18n.java 2008-05-07 16:25:17
UTC (rev 120)
@@ -36,13 +36,12 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
import net.jcip.annotations.ThreadSafe;
import org.jboss.dna.common.CommonI18n;
import org.jboss.dna.common.SystemFailureException;
import org.jboss.dna.common.util.ArgCheck;
import org.jboss.dna.common.util.ClassUtil;
+import org.jboss.dna.common.util.StringUtil;
/**
* Manages the initialization of internationalization (i18n) files, substitution of
values within i18n message placeholders, and
@@ -54,8 +53,6 @@
@ThreadSafe
public final class I18n {
- private static final Pattern PARAMETER_COUNT_PATTERN =
Pattern.compile("\\{(\\d+)\\}");
- private static final Object[] EMPTY_ARGUMENTS = new Object[] {};
private static final LocalizationRepository DEFAULT_LOCALIZATION_REPOSITORY = new
ClasspathLocalizationRepository();
/**
@@ -309,86 +306,6 @@
}
}
- /**
- * Substitute the arguments into the message, ensuring that the number of arguments
matches the number of parameters in the
- * text.
- *
- * @param id the id of the internationalization object
- * @param text
- * @param arguments
- * @return the text with parameters replaced
- */
- protected static String replaceParameters( String id,
- String text,
- Object... arguments ) {
- if (arguments == null) arguments = EMPTY_ARGUMENTS;
- Matcher matcher = PARAMETER_COUNT_PATTERN.matcher(text);
- StringBuffer newText = new StringBuffer();
- int argCount = 0;
- boolean err = false;
- while (matcher.find()) {
- int ndx = Integer.valueOf(matcher.group(1));
- if (argCount <= ndx) {
- argCount = ndx + 1;
- }
- if (ndx >= arguments.length) {
- err = true;
- matcher.appendReplacement(newText, matcher.group());
- } else {
- Object arg = arguments[ndx];
- if (arg != null) {
- matcher.appendReplacement(newText, Matcher.quoteReplacement(arg.toString()));
- } else {
- matcher.appendReplacement(newText, Matcher.quoteReplacement("null"));
- }
- }
- }
- if (err || argCount < arguments.length) {
- String msg = null;
- if (id != null) {
- if (arguments.length == 1) {
- msg = CommonI18n.i18nArgumentMismatchedParameters.text(id, argCount, text,
newText.toString());
- } else if (argCount == 1) {
- msg = CommonI18n.i18nArgumentsMismatchedParameter.text(arguments.length, id, text,
newText.toString());
- } else {
- msg = CommonI18n.i18nArgumentsMismatchedParameters.text(arguments.length,
- id,
- argCount,
- text,
- newText.toString());
- }
- throw new IllegalArgumentException(msg);
- }
- if (arguments.length == 1) {
- msg = CommonI18n.i18nReplaceArgumentMismatchedParameters.text(argCount, text,
newText.toString());
- } else if (argCount == 1) {
- msg = CommonI18n.i18nReplaceArgumentsMismatchedParameter.text(arguments.length, text,
newText.toString());
- } else {
- msg = CommonI18n.i18nReplaceArgumentsMismatchedParameters.text(arguments.length,
- argCount,
- text,
- newText.toString());
- }
- throw new IllegalArgumentException(msg);
- }
- matcher.appendTail(newText);
-
- return newText.toString();
- }
-
- /**
- * Substitute the arguments into the message, ensuring that the number of arguments
matches the number of parameters in the
- * text.
- *
- * @param text
- * @param arguments
- * @return the text with parameters replaced
- */
- public static String replaceParameters( String text,
- Object... arguments ) {
- return replaceParameters(null, text, arguments);
- }
-
private final String id;
private final Class i18nClass;
final ConcurrentHashMap<Locale, String> localeToTextMap = new
ConcurrentHashMap<Locale, String>();
@@ -495,7 +412,11 @@
Object... arguments ) {
try {
String rawText = rawText(locale == null ? Locale.getDefault() : locale);
- return replaceParameters(id, rawText, arguments);
+ return StringUtil.createString(rawText, arguments);
+ } catch (IllegalArgumentException err) {
+ throw new
IllegalArgumentException(CommonI18n.i18nRequiredToSuppliedParameterMismatch.text(id,
+
i18nClass,
+
err.getMessage()));
} catch (SystemFailureException err) {
return '<' + err.getMessage() + '>';
}
Modified: trunk/dna-common/src/main/java/org/jboss/dna/common/util/Logger.java
===================================================================
--- trunk/dna-common/src/main/java/org/jboss/dna/common/util/Logger.java 2008-05-07
13:37:37 UTC (rev 119)
+++ trunk/dna-common/src/main/java/org/jboss/dna/common/util/Logger.java 2008-05-07
16:25:17 UTC (rev 120)
@@ -2,7 +2,7 @@
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
+ * distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
@@ -36,348 +36,391 @@
@ThreadSafe
public final class Logger {
- public enum Level {
- OFF,
- ERROR,
- WARNING,
- INFO,
- DEBUG,
- TRACE;
- }
+ public enum Level {
+ OFF,
+ ERROR,
+ WARNING,
+ INFO,
+ DEBUG,
+ TRACE;
+ }
- private static final AtomicReference<Locale> LOGGING_LOCALE = new
AtomicReference<Locale>(null);
+ private static final AtomicReference<Locale> LOGGING_LOCALE = new
AtomicReference<Locale>(null);
- /**
- * Get the locale used for the logs. If null, the {@link Locale#getDefault() default
locale} is used.
- * @return the current locale used for logging, or null if the system locale is used
- * @see #setLoggingLocale(Locale)
- */
- public static Locale getLoggingLocale() {
- return LOGGING_LOCALE.get();
- }
+ /**
+ * Get the locale used for the logs. If null, the {@link Locale#getDefault() default
locale} is used.
+ *
+ * @return the current locale used for logging, or null if the system locale is used
+ * @see #setLoggingLocale(Locale)
+ */
+ public static Locale getLoggingLocale() {
+ return LOGGING_LOCALE.get();
+ }
- /**
- * Set the locale used for the logs. This should be used when the logs are to be
written is a specific locale, independent of
- * the {@link Locale#getDefault() default locale}. To use the default locale, call
this method with a null value.
- * @param locale the desired locale to use for the logs, or null if the system locale
should be used
- * @return the previous locale
- * @see #getLoggingLocale()
- */
- public static Locale setLoggingLocale( Locale locale ) {
- return LOGGING_LOCALE.getAndSet(locale != null ? locale : Locale.getDefault());
- }
+ /**
+ * Set the locale used for the logs. This should be used when the logs are to be written
is a specific locale, independent of
+ * the {@link Locale#getDefault() default locale}. To use the default locale, call this
method with a null value.
+ *
+ * @param locale the desired locale to use for the logs, or null if the system locale
should be used
+ * @return the previous locale
+ * @see #getLoggingLocale()
+ */
+ public static Locale setLoggingLocale( Locale locale ) {
+ return LOGGING_LOCALE.getAndSet(locale != null ? locale : Locale.getDefault());
+ }
- /**
- * Return a logger named corresponding to the class passed as parameter, using the
statically bound {@link ILoggerFactory}
- * instance.
- * @param clazz the returned logger will be named after clazz
- * @return logger
- */
- public static Logger getLogger( Class clazz ) {
- return new Logger(LoggerFactory.getLogger(clazz));
- }
+ /**
+ * Return a logger named corresponding to the class passed as parameter, using the
statically bound {@link ILoggerFactory}
+ * instance.
+ *
+ * @param clazz the returned logger will be named after clazz
+ * @return logger
+ */
+ public static Logger getLogger( Class clazz ) {
+ return new Logger(LoggerFactory.getLogger(clazz));
+ }
- /**
- * Return a logger named according to the name parameter using the statically bound
{@link ILoggerFactory} instance.
- * @param name The name of the logger.
- * @return logger
- */
- public static Logger getLogger( String name ) {
- return new Logger(LoggerFactory.getLogger(name));
- }
+ /**
+ * Return a logger named according to the name parameter using the statically bound
{@link ILoggerFactory} instance.
+ *
+ * @param name The name of the logger.
+ * @return logger
+ */
+ public static Logger getLogger( String name ) {
+ return new Logger(LoggerFactory.getLogger(name));
+ }
- private final org.slf4j.Logger delegate;
+ private final org.slf4j.Logger delegate;
- private Logger( org.slf4j.Logger delegate ) {
- this.delegate = delegate;
- }
+ private Logger( org.slf4j.Logger delegate ) {
+ this.delegate = delegate;
+ }
- /**
- * Return the name of this logger instance.
- * @return the logger's name
- */
- public String getName() {
- return this.delegate.getName();
- }
+ /**
+ * Return the name of this logger instance.
+ *
+ * @return the logger's name
+ */
+ public String getName() {
+ return this.delegate.getName();
+ }
- /**
- * Log a message at the suplied level according to the specified format and
(optional) parameters. The message should contain
- * a pair of empty curly braces for each of the parameter, which should be passed in
the correct order. This method is
- * efficient and avoids superfluous object creation when the logger is disabled for
the desired level.
- * @param level the level at which to log
- * @param message the (localized) message string
- * @param params the parameter values that are to replace the variables in the format
string
- */
- public void log( Level level, I18n message, Object... params ) {
- if (message == null) return;
- switch (level) {
- case DEBUG:
- debug(message.text(LOGGING_LOCALE.get(), params));
- break;
- case ERROR:
- error(message, params);
- break;
- case INFO:
- info(message, params);
- break;
- case TRACE:
- trace(message.text(LOGGING_LOCALE.get(), params));
- break;
- case WARNING:
- warn(message, params);
- break;
- case OFF:
- break;
- }
- }
+ /**
+ * Log a message at the suplied level according to the specified format and (optional)
parameters. The message should contain
+ * a pair of empty curly braces for each of the parameter, which should be passed in the
correct order. This method is
+ * efficient and avoids superfluous object creation when the logger is disabled for the
desired level.
+ *
+ * @param level the level at which to log
+ * @param message the (localized) message string
+ * @param params the parameter values that are to replace the variables in the format
string
+ */
+ public void log( Level level,
+ I18n message,
+ Object... params ) {
+ if (message == null) return;
+ switch (level) {
+ case DEBUG:
+ debug(message.text(LOGGING_LOCALE.get(), params));
+ break;
+ case ERROR:
+ error(message, params);
+ break;
+ case INFO:
+ info(message, params);
+ break;
+ case TRACE:
+ trace(message.text(LOGGING_LOCALE.get(), params));
+ break;
+ case WARNING:
+ warn(message, params);
+ break;
+ case OFF:
+ break;
+ }
+ }
- /**
- * Log an exception (throwable) at the supplied level with an accompanying message.
If the exception is null, then this method
- * calls {@link #debug(String, Object...)}.
- * @param level the level at which to log
- * @param t the exception (throwable) to log
- * @param message the message accompanying the exception
- * @param params the parameter values that are to replace the variables in the format
string
- */
- public void log( Level level, Throwable t, I18n message, Object... params ) {
- if (message == null) return;
- switch (level) {
- case DEBUG:
- debug(t, message.text(LOGGING_LOCALE.get(), params));
- break;
- case ERROR:
- error(t, message, params);
- break;
- case INFO:
- info(t, message, params);
- break;
- case TRACE:
- trace(t, message.text(LOGGING_LOCALE.get(), params));
- break;
- case WARNING:
- warn(t, message, params);
- break;
- case OFF:
- break;
- }
- }
+ /**
+ * Log an exception (throwable) at the supplied level with an accompanying message. If
the exception is null, then this method
+ * calls {@link #debug(String, Object...)}.
+ *
+ * @param level the level at which to log
+ * @param t the exception (throwable) to log
+ * @param message the message accompanying the exception
+ * @param params the parameter values that are to replace the variables in the format
string
+ */
+ public void log( Level level,
+ Throwable t,
+ I18n message,
+ Object... params ) {
+ if (message == null) return;
+ switch (level) {
+ case DEBUG:
+ debug(t, message.text(LOGGING_LOCALE.get(), params));
+ break;
+ case ERROR:
+ error(t, message, params);
+ break;
+ case INFO:
+ info(t, message, params);
+ break;
+ case TRACE:
+ trace(t, message.text(LOGGING_LOCALE.get(), params));
+ break;
+ case WARNING:
+ warn(t, message, params);
+ break;
+ case OFF:
+ break;
+ }
+ }
- /**
- * Log a message at the DEBUG level according to the specified format and (optional)
parameters. The message should contain a
- * pair of empty curly braces for each of the parameter, which should be passed in
the correct order. This method is efficient
- * and avoids superfluous object creation when the logger is disabled for the DEBUG
level.
- * @param message the message string
- * @param params the parameter values that are to replace the variables in the format
string
- */
- public void debug( String message, Object... params ) {
- if (!isDebugEnabled()) return;
- if (message == null) return;
- this.delegate.debug(I18n.replaceParameters(message, params));
- }
+ /**
+ * Log a message at the DEBUG level according to the specified format and (optional)
parameters. The message should contain a
+ * pair of empty curly braces for each of the parameter, which should be passed in the
correct order. This method is efficient
+ * and avoids superfluous object creation when the logger is disabled for the DEBUG
level.
+ *
+ * @param message the message string
+ * @param params the parameter values that are to replace the variables in the format
string
+ */
+ public void debug( String message,
+ Object... params ) {
+ if (!isDebugEnabled()) return;
+ if (message == null) return;
+ this.delegate.debug(StringUtil.createString(message, params));
+ }
- /**
- * Log an exception (throwable) at the DEBUG level with an accompanying message. If
the exception is null, then this method
- * calls {@link #debug(String, Object...)}.
- * @param t the exception (throwable) to log
- * @param message the message accompanying the exception
- * @param params the parameter values that are to replace the variables in the format
string
- */
- public void debug( Throwable t, String message, Object... params ) {
- if (!isDebugEnabled()) return;
- if (t == null) {
- debug(message, params);
- return;
- }
- if (message == null) {
- this.delegate.debug(null, t);
- return;
- }
- this.delegate.debug(I18n.replaceParameters(message, params), t);
- }
+ /**
+ * Log an exception (throwable) at the DEBUG level with an accompanying message. If the
exception is null, then this method
+ * calls {@link #debug(String, Object...)}.
+ *
+ * @param t the exception (throwable) to log
+ * @param message the message accompanying the exception
+ * @param params the parameter values that are to replace the variables in the format
string
+ */
+ public void debug( Throwable t,
+ String message,
+ Object... params ) {
+ if (!isDebugEnabled()) return;
+ if (t == null) {
+ debug(message, params);
+ return;
+ }
+ if (message == null) {
+ this.delegate.debug(null, t);
+ return;
+ }
+ this.delegate.debug(StringUtil.createString(message, params), t);
+ }
- /**
- * Log a message at the ERROR level according to the specified format and (optional)
parameters. The message should contain a
- * pair of empty curly braces for each of the parameter, which should be passed in
the correct order. This method is efficient
- * and avoids superfluous object creation when the logger is disabled for the ERROR
level.
- * @param message the message string
- * @param params the parameter values that are to replace the variables in the format
string
- */
- public void error( I18n message, Object... params ) {
- if (!isErrorEnabled()) return;
- if (message == null) return;
- this.delegate.error(message.text(LOGGING_LOCALE.get(), params));
- }
+ /**
+ * Log a message at the ERROR level according to the specified format and (optional)
parameters. The message should contain a
+ * pair of empty curly braces for each of the parameter, which should be passed in the
correct order. This method is efficient
+ * and avoids superfluous object creation when the logger is disabled for the ERROR
level.
+ *
+ * @param message the message string
+ * @param params the parameter values that are to replace the variables in the format
string
+ */
+ public void error( I18n message,
+ Object... params ) {
+ if (!isErrorEnabled()) return;
+ if (message == null) return;
+ this.delegate.error(message.text(LOGGING_LOCALE.get(), params));
+ }
- /**
- * Log an exception (throwable) at the ERROR level with an accompanying message. If
the exception is null, then this method
- * calls {@link #error(I18n, Object...)}.
- * @param t the exception (throwable) to log
- * @param message the message accompanying the exception
- * @param params the parameter values that are to replace the variables in the format
string
- */
- public void error( Throwable t, I18n message, Object... params ) {
- if (!isErrorEnabled()) return;
- if (t == null) {
- error(message, params);
- return;
- }
- if (message == null) {
- this.delegate.error(null, t);
- return;
- }
- this.delegate.error(message.text(LOGGING_LOCALE.get(), params), t);
- }
+ /**
+ * Log an exception (throwable) at the ERROR level with an accompanying message. If the
exception is null, then this method
+ * calls {@link #error(I18n, Object...)}.
+ *
+ * @param t the exception (throwable) to log
+ * @param message the message accompanying the exception
+ * @param params the parameter values that are to replace the variables in the format
string
+ */
+ public void error( Throwable t,
+ I18n message,
+ Object... params ) {
+ if (!isErrorEnabled()) return;
+ if (t == null) {
+ error(message, params);
+ return;
+ }
+ if (message == null) {
+ this.delegate.error(null, t);
+ return;
+ }
+ this.delegate.error(message.text(LOGGING_LOCALE.get(), params), t);
+ }
- /**
- * Log a message at the INFO level according to the specified format and (optional)
parameters. The message should contain a
- * pair of empty curly braces for each of the parameter, which should be passed in
the correct order. This method is efficient
- * and avoids superfluous object creation when the logger is disabled for the INFO
level.
- * @param message the message string
- * @param params the parameter values that are to replace the variables in the format
string
- */
- public void info( I18n message, Object... params ) {
- if (!isInfoEnabled()) return;
- if (message == null) return;
- this.delegate.info(message.text(LOGGING_LOCALE.get(), params));
- }
+ /**
+ * Log a message at the INFO level according to the specified format and (optional)
parameters. The message should contain a
+ * pair of empty curly braces for each of the parameter, which should be passed in the
correct order. This method is efficient
+ * and avoids superfluous object creation when the logger is disabled for the INFO
level.
+ *
+ * @param message the message string
+ * @param params the parameter values that are to replace the variables in the format
string
+ */
+ public void info( I18n message,
+ Object... params ) {
+ if (!isInfoEnabled()) return;
+ if (message == null) return;
+ this.delegate.info(message.text(LOGGING_LOCALE.get(), params));
+ }
- /**
- * Log an exception (throwable) at the INFO level with an accompanying message. If
the exception is null, then this method
- * calls {@link #info(I18n, Object...)}.
- * @param t the exception (throwable) to log
- * @param message the message accompanying the exception
- * @param params the parameter values that are to replace the variables in the format
string
- */
- public void info( Throwable t, I18n message, Object... params ) {
- if (!isInfoEnabled()) return;
- if (t == null) {
- info(message, params);
- return;
- }
- if (message == null) {
- this.delegate.info(null, t);
- return;
- }
- this.delegate.info(message.text(LOGGING_LOCALE.get(), params), t);
- }
+ /**
+ * Log an exception (throwable) at the INFO level with an accompanying message. If the
exception is null, then this method
+ * calls {@link #info(I18n, Object...)}.
+ *
+ * @param t the exception (throwable) to log
+ * @param message the message accompanying the exception
+ * @param params the parameter values that are to replace the variables in the format
string
+ */
+ public void info( Throwable t,
+ I18n message,
+ Object... params ) {
+ if (!isInfoEnabled()) return;
+ if (t == null) {
+ info(message, params);
+ return;
+ }
+ if (message == null) {
+ this.delegate.info(null, t);
+ return;
+ }
+ this.delegate.info(message.text(LOGGING_LOCALE.get(), params), t);
+ }
- /**
- * Log a message at the TRACE level according to the specified format and (optional)
parameters. The message should contain a
- * pair of empty curly braces for each of the parameter, which should be passed in
the correct order. This method is efficient
- * and avoids superfluous object creation when the logger is disabled for the TRACE
level.
- * @param message the message string
- * @param params the parameter values that are to replace the variables in the format
string
- */
- public void trace( String message, Object... params ) {
- if (!isTraceEnabled()) return;
- if (message == null) return;
- this.delegate.trace(I18n.replaceParameters(message, params));
- }
+ /**
+ * Log a message at the TRACE level according to the specified format and (optional)
parameters. The message should contain a
+ * pair of empty curly braces for each of the parameter, which should be passed in the
correct order. This method is efficient
+ * and avoids superfluous object creation when the logger is disabled for the TRACE
level.
+ *
+ * @param message the message string
+ * @param params the parameter values that are to replace the variables in the format
string
+ */
+ public void trace( String message,
+ Object... params ) {
+ if (!isTraceEnabled()) return;
+ if (message == null) return;
+ this.delegate.trace(StringUtil.createString(message, params));
+ }
- /**
- * Log an exception (throwable) at the TRACE level with an accompanying message. If
the exception is null, then this method
- * calls {@link #trace(String, Object...)}.
- * @param t the exception (throwable) to log
- * @param message the message accompanying the exception
- * @param params the parameter values that are to replace the variables in the format
string
- */
- public void trace( Throwable t, String message, Object... params ) {
- if (!isTraceEnabled()) return;
- if (t == null) {
- this.trace(message, params);
- return;
- }
- if (message == null) {
- this.delegate.trace(null, t);
- return;
- }
- this.delegate.trace(I18n.replaceParameters(message, params), t);
- }
+ /**
+ * Log an exception (throwable) at the TRACE level with an accompanying message. If the
exception is null, then this method
+ * calls {@link #trace(String, Object...)}.
+ *
+ * @param t the exception (throwable) to log
+ * @param message the message accompanying the exception
+ * @param params the parameter values that are to replace the variables in the format
string
+ */
+ public void trace( Throwable t,
+ String message,
+ Object... params ) {
+ if (!isTraceEnabled()) return;
+ if (t == null) {
+ this.trace(message, params);
+ return;
+ }
+ if (message == null) {
+ this.delegate.trace(null, t);
+ return;
+ }
+ this.delegate.trace(StringUtil.createString(message, params), t);
+ }
- /**
- * Log a message at the WARNING level according to the specified format and
(optional) parameters. The message should contain
- * a pair of empty curly braces for each of the parameter, which should be passed in
the correct order. This method is
- * efficient and avoids superfluous object creation when the logger is disabled for
the WARNING level.
- * @param message the message string
- * @param params the parameter values that are to replace the variables in the format
string
- */
- public void warn( I18n message, Object... params ) {
- if (!isWarnEnabled()) return;
- if (message == null) return;
- this.delegate.warn(message.text(LOGGING_LOCALE.get(), params));
- }
+ /**
+ * Log a message at the WARNING level according to the specified format and (optional)
parameters. The message should contain
+ * a pair of empty curly braces for each of the parameter, which should be passed in the
correct order. This method is
+ * efficient and avoids superfluous object creation when the logger is disabled for the
WARNING level.
+ *
+ * @param message the message string
+ * @param params the parameter values that are to replace the variables in the format
string
+ */
+ public void warn( I18n message,
+ Object... params ) {
+ if (!isWarnEnabled()) return;
+ if (message == null) return;
+ this.delegate.warn(message.text(LOGGING_LOCALE.get(), params));
+ }
- /**
- * Log an exception (throwable) at the WARNING level with an accompanying message. If
the exception is null, then this method
- * calls {@link #warn(I18n, Object...)}.
- * @param t the exception (throwable) to log
- * @param message the message accompanying the exception
- * @param params the parameter values that are to replace the variables in the format
string
- */
- public void warn( Throwable t, I18n message, Object... params ) {
- if (!isWarnEnabled()) return;
- if (t == null) {
- warn(message, params);
- return;
- }
- if (message == null) {
- this.delegate.warn(null, t);
- return;
- }
- this.delegate.warn(message.text(LOGGING_LOCALE.get(), params), t);
- }
+ /**
+ * Log an exception (throwable) at the WARNING level with an accompanying message. If
the exception is null, then this method
+ * calls {@link #warn(I18n, Object...)}.
+ *
+ * @param t the exception (throwable) to log
+ * @param message the message accompanying the exception
+ * @param params the parameter values that are to replace the variables in the format
string
+ */
+ public void warn( Throwable t,
+ I18n message,
+ Object... params ) {
+ if (!isWarnEnabled()) return;
+ if (t == null) {
+ warn(message, params);
+ return;
+ }
+ if (message == null) {
+ this.delegate.warn(null, t);
+ return;
+ }
+ this.delegate.warn(message.text(LOGGING_LOCALE.get(), params), t);
+ }
- /**
- * Return whether messages at the INFORMATION level are being logged.
- * @return true if INFORMATION log messages are currently being logged, or false
otherwise.
- */
- public boolean isInfoEnabled() {
- return this.delegate.isInfoEnabled();
- }
+ /**
+ * Return whether messages at the INFORMATION level are being logged.
+ *
+ * @return true if INFORMATION log messages are currently being logged, or false
otherwise.
+ */
+ public boolean isInfoEnabled() {
+ return this.delegate.isInfoEnabled();
+ }
- /**
- * Return whether messages at the WARNING level are being logged.
- * @return true if WARNING log messages are currently being logged, or false
otherwise.
- */
- public boolean isWarnEnabled() {
- return this.delegate.isWarnEnabled();
- }
+ /**
+ * Return whether messages at the WARNING level are being logged.
+ *
+ * @return true if WARNING log messages are currently being logged, or false otherwise.
+ */
+ public boolean isWarnEnabled() {
+ return this.delegate.isWarnEnabled();
+ }
- /**
- * Return whether messages at the ERROR level are being logged.
- * @return true if ERROR log messages are currently being logged, or false
otherwise.
- */
- public boolean isErrorEnabled() {
- return this.delegate.isErrorEnabled();
- }
+ /**
+ * Return whether messages at the ERROR level are being logged.
+ *
+ * @return true if ERROR log messages are currently being logged, or false otherwise.
+ */
+ public boolean isErrorEnabled() {
+ return this.delegate.isErrorEnabled();
+ }
- /**
- * Return whether messages at the DEBUG level are being logged.
- * @return true if DEBUG log messages are currently being logged, or false
otherwise.
- */
- public boolean isDebugEnabled() {
- return this.delegate.isDebugEnabled();
- }
+ /**
+ * Return whether messages at the DEBUG level are being logged.
+ *
+ * @return true if DEBUG log messages are currently being logged, or false otherwise.
+ */
+ public boolean isDebugEnabled() {
+ return this.delegate.isDebugEnabled();
+ }
- /**
- * Return whether messages at the TRACE level are being logged.
- * @return true if TRACE log messages are currently being logged, or false
otherwise.
- */
- public boolean isTraceEnabled() {
- return this.delegate.isTraceEnabled();
- }
+ /**
+ * Return whether messages at the TRACE level are being logged.
+ *
+ * @return true if TRACE log messages are currently being logged, or false otherwise.
+ */
+ public boolean isTraceEnabled() {
+ return this.delegate.isTraceEnabled();
+ }
- /**
- * Get the logging level at which this logger is current set.
- * @return the current logging level
- */
- public Level getLevel() {
- if (this.isTraceEnabled()) return Level.TRACE;
- if (this.isDebugEnabled()) return Level.DEBUG;
- if (this.isInfoEnabled()) return Level.INFO;
- if (this.isWarnEnabled()) return Level.WARNING;
- if (this.isErrorEnabled()) return Level.ERROR;
- return Level.OFF;
- }
+ /**
+ * Get the logging level at which this logger is current set.
+ *
+ * @return the current logging level
+ */
+ public Level getLevel() {
+ if (this.isTraceEnabled()) return Level.TRACE;
+ if (this.isDebugEnabled()) return Level.DEBUG;
+ if (this.isInfoEnabled()) return Level.INFO;
+ if (this.isWarnEnabled()) return Level.WARNING;
+ if (this.isErrorEnabled()) return Level.ERROR;
+ return Level.OFF;
+ }
}
Modified: trunk/dna-common/src/main/java/org/jboss/dna/common/util/StringUtil.java
===================================================================
--- trunk/dna-common/src/main/java/org/jboss/dna/common/util/StringUtil.java 2008-05-07
13:37:37 UTC (rev 119)
+++ trunk/dna-common/src/main/java/org/jboss/dna/common/util/StringUtil.java 2008-05-07
16:25:17 UTC (rev 120)
@@ -2,7 +2,7 @@
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
+ * distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
@@ -35,543 +35,607 @@
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.jboss.dna.common.CommonI18n;
import org.jboss.dna.common.SystemFailureException;
-import org.jboss.dna.common.i18n.I18n;
/**
* Utilities for string processing and manipulation.
*/
public class StringUtil {
- /**
- */
- public static final String[] EMPTY_STRING_ARRAY = new String[0];
+ public static final String[] EMPTY_STRING_ARRAY = new String[0];
+ private static final Pattern PARAMETER_COUNT_PATTERN =
Pattern.compile("\\{(\\d+)\\}");
- /**
- * Split the supplied content into lines, returning each line as an element in the
returned list.
- * @param content the string content that is to be split
- * @return the list of lines; never null but may be an empty (unmodifiable) list if
the supplied content is null or empty
- */
- public static List<String> splitLines( final String content ) {
- if (content == null || content.length() == 0) return Collections.emptyList();
- String[] lines = content.split("[\\r]?\\n");
- return Arrays.asList(lines);
- }
+ /**
+ * Split the supplied content into lines, returning each line as an element in the
returned list.
+ *
+ * @param content the string content that is to be split
+ * @return the list of lines; never null but may be an empty (unmodifiable) list if the
supplied content is null or empty
+ */
+ public static List<String> splitLines( final String content ) {
+ if (content == null || content.length() == 0) return Collections.emptyList();
+ String[] lines = content.split("[\\r]?\\n");
+ return Arrays.asList(lines);
+ }
- /**
- * Create a string by substituting the parameters into all key occurrences in the
supplied format. The pattern consists of
- * zero or more keys of the form <code>{n}</code>, where
<code>n</code> is an integer starting at 1. Therefore, the first
- * parameter replaces all occurrences of "{1}", the second parameter
replaces all occurrences of "{2}", etc.
- * <p>
- * If any parameter is null, the corresponding key is replaced with the string
"null". Therefore, consider using an empty
- * string when keys are to be removed altogether.
- * </p>
- * <p>
- * If there are no parameters, this method does nothing and returns the supplied
pattern as is.
- * </p>
- * @param pattern the pattern
- * @param parameters the parameters used to replace keys
- * @return the string with all keys replaced (or removed)
- */
- public static String createString( String pattern, Object... parameters ) {
- return I18n.replaceParameters(pattern, parameters);
- }
+ /**
+ * Create a string by substituting the parameters into all key occurrences in the
supplied format. The pattern consists of
+ * zero or more keys of the form <code>{n}</code>, where
<code>n</code> is an integer starting at 1. Therefore, the first
+ * parameter replaces all occurrences of "{1}", the second parameter replaces
all occurrences of "{2}", etc.
+ * <p>
+ * If any parameter is null, the corresponding key is replaced with the string
"null". Therefore, consider using an empty
+ * string when keys are to be removed altogether.
+ * </p>
+ * <p>
+ * If there are no parameters, this method does nothing and returns the supplied pattern
as is.
+ * </p>
+ *
+ * @param pattern the pattern
+ * @param parameters the parameters used to replace keys
+ * @return the string with all keys replaced (or removed)
+ */
+ public static String createString( String pattern,
+ Object... parameters ) {
+ ArgCheck.isNotNull(pattern, "pattern");
+ if (parameters == null) parameters = EMPTY_STRING_ARRAY;
+ Matcher matcher = PARAMETER_COUNT_PATTERN.matcher(pattern);
+ StringBuffer text = new StringBuffer();
+ int requiredParameterCount = 0;
+ boolean err = false;
+ while (matcher.find()) {
+ int ndx = Integer.valueOf(matcher.group(1));
+ if (requiredParameterCount <= ndx) {
+ requiredParameterCount = ndx + 1;
+ }
+ if (ndx >= parameters.length) {
+ err = true;
+ matcher.appendReplacement(text, matcher.group());
+ } else {
+ Object parameter = parameters[ndx];
+ matcher.appendReplacement(text, Matcher.quoteReplacement(parameter == null ?
"null" : parameter.toString()));
+ }
+ }
+ if (err || requiredParameterCount < parameters.length) {
+ throw new IllegalArgumentException(
+
CommonI18n.requiredToSuppliedParameterMismatch.text(parameters.length,
+
parameters.length == 1 ? "" : "s",
+
requiredParameterCount,
+
requiredParameterCount == 1 ? "" : "s",
+
pattern,
+
text.toString()));
+ }
+ matcher.appendTail(text);
- /**
- * Create a new string containing the specified character repeated a specific number
of times.
- * @param charToRepeat the character to repeat
- * @param numberOfRepeats the number of times the character is to repeat in the
result; must be greater than 0
- * @return the resulting string
- */
- public static String createString( final char charToRepeat, int numberOfRepeats ) {
- assert numberOfRepeats >= 0;
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < numberOfRepeats; ++i) {
- sb.append(charToRepeat);
- }
- return sb.toString();
- }
+ return text.toString();
+ }
- /**
- * Set the length of the string, padding with the supplied character if the supplied
string is shorter than desired, or
- * truncating the string if it is longer than desired. Unlike {@link
#justifyLeft(String, int, char)}, this method does not
- * remove leading and trailing whitespace.
- * @param original the string for which the length is to be set; may not be null
- * @param length the desired length; must be positive
- * @param padChar the character to use for padding, if the supplied string is not
long enough
- * @return the string of the desired length
- * @see #justifyLeft(String, int, char)
- */
- public static String setLength( String original, int length, char padChar ) {
- return justifyLeft(original, length, padChar, false);
- }
+ /**
+ * Create a new string containing the specified character repeated a specific number of
times.
+ *
+ * @param charToRepeat the character to repeat
+ * @param numberOfRepeats the number of times the character is to repeat in the result;
must be greater than 0
+ * @return the resulting string
+ */
+ public static String createString( final char charToRepeat,
+ int numberOfRepeats ) {
+ assert numberOfRepeats >= 0;
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < numberOfRepeats; ++i) {
+ sb.append(charToRepeat);
+ }
+ return sb.toString();
+ }
- /**
- * Right justify the contents of the string, ensuring that the string ends at the
last character. If the supplied string is
- * longer than the desired width, the leading characters are removed so that the last
character in the supplied string at the
- * last position. If the supplied string is shorter than the desired width, the
padding character is inserted one or more
- * times such that the last character in the supplied string appears as the last
character in the resulting string and that
- * the length matches that specified.
- * @param str the string to be right justified; if null, an empty string is used
- * @param width the desired width of the string; must be positive
- * @param padWithChar the character to use for padding, if needed
- * @return the right justified string
- */
- public static String justifyRight( String str, final int width, char padWithChar ) {
- assert width > 0;
- // Trim the leading and trailing whitespace ...
- str = str != null ? str.trim() : "";
+ /**
+ * Set the length of the string, padding with the supplied character if the supplied
string is shorter than desired, or
+ * truncating the string if it is longer than desired. Unlike {@link
#justifyLeft(String, int, char)}, this method does not
+ * remove leading and trailing whitespace.
+ *
+ * @param original the string for which the length is to be set; may not be null
+ * @param length the desired length; must be positive
+ * @param padChar the character to use for padding, if the supplied string is not long
enough
+ * @return the string of the desired length
+ * @see #justifyLeft(String, int, char)
+ */
+ public static String setLength( String original,
+ int length,
+ char padChar ) {
+ return justifyLeft(original, length, padChar, false);
+ }
- final int length = str.length();
- int addChars = width - length;
- if (addChars < 0) {
- // truncate the first characters, keep the last
- return str.subSequence(length - width, length).toString();
- }
- // Prepend the whitespace ...
- final StringBuilder sb = new StringBuilder();
- while (addChars > 0) {
- sb.append(padWithChar);
- --addChars;
- }
+ /**
+ * Right justify the contents of the string, ensuring that the string ends at the last
character. If the supplied string is
+ * longer than the desired width, the leading characters are removed so that the last
character in the supplied string at the
+ * last position. If the supplied string is shorter than the desired width, the padding
character is inserted one or more
+ * times such that the last character in the supplied string appears as the last
character in the resulting string and that
+ * the length matches that specified.
+ *
+ * @param str the string to be right justified; if null, an empty string is used
+ * @param width the desired width of the string; must be positive
+ * @param padWithChar the character to use for padding, if needed
+ * @return the right justified string
+ */
+ public static String justifyRight( String str,
+ final int width,
+ char padWithChar ) {
+ assert width > 0;
+ // Trim the leading and trailing whitespace ...
+ str = str != null ? str.trim() : "";
- // Write the content ...
- sb.append(str);
- return sb.toString();
- }
+ final int length = str.length();
+ int addChars = width - length;
+ if (addChars < 0) {
+ // truncate the first characters, keep the last
+ return str.subSequence(length - width, length).toString();
+ }
+ // Prepend the whitespace ...
+ final StringBuilder sb = new StringBuilder();
+ while (addChars > 0) {
+ sb.append(padWithChar);
+ --addChars;
+ }
- /**
- * Left justify the contents of the string, ensuring that the supplied string begins
at the first character and that the
- * resulting string is of the desired length. If the supplied string is longer than
the desired width, it is truncated to the
- * specified length. If the supplied string is shorter than the desired width, the
padding character is added to the end of
- * the string one or more times such that the length is that specified. All leading
and trailing whitespace is removed.
- * @param str the string to be left justified; if null, an empty string is used
- * @param width the desired width of the string; must be positive
- * @param padWithChar the character to use for padding, if needed
- * @return the left justified string
- * @see #setLength(String, int, char)
- */
- public static String justifyLeft( String str, final int width, char padWithChar ) {
- return justifyLeft(str, width, padWithChar, true);
- }
+ // Write the content ...
+ sb.append(str);
+ return sb.toString();
+ }
- protected static String justifyLeft( String str, final int width, char padWithChar,
boolean trimWhitespace ) {
- // Trim the leading and trailing whitespace ...
- str = str != null ? (trimWhitespace ? str.trim() : str) : "";
+ /**
+ * Left justify the contents of the string, ensuring that the supplied string begins at
the first character and that the
+ * resulting string is of the desired length. If the supplied string is longer than the
desired width, it is truncated to the
+ * specified length. If the supplied string is shorter than the desired width, the
padding character is added to the end of
+ * the string one or more times such that the length is that specified. All leading and
trailing whitespace is removed.
+ *
+ * @param str the string to be left justified; if null, an empty string is used
+ * @param width the desired width of the string; must be positive
+ * @param padWithChar the character to use for padding, if needed
+ * @return the left justified string
+ * @see #setLength(String, int, char)
+ */
+ public static String justifyLeft( String str,
+ final int width,
+ char padWithChar ) {
+ return justifyLeft(str, width, padWithChar, true);
+ }
- int addChars = width - str.length();
- if (addChars < 0) {
- // truncate
- return str.subSequence(0, width).toString();
- }
- // Write the content ...
- final StringBuilder sb = new StringBuilder();
- sb.append(str);
+ protected static String justifyLeft( String str,
+ final int width,
+ char padWithChar,
+ boolean trimWhitespace ) {
+ // Trim the leading and trailing whitespace ...
+ str = str != null ? (trimWhitespace ? str.trim() : str) : "";
- // Append the whitespace ...
- while (addChars > 0) {
- sb.append(padWithChar);
- --addChars;
- }
+ int addChars = width - str.length();
+ if (addChars < 0) {
+ // truncate
+ return str.subSequence(0, width).toString();
+ }
+ // Write the content ...
+ final StringBuilder sb = new StringBuilder();
+ sb.append(str);
- return sb.toString();
- }
+ // Append the whitespace ...
+ while (addChars > 0) {
+ sb.append(padWithChar);
+ --addChars;
+ }
- /**
- * Center the contents of the string. If the supplied string is longer than the
desired width, it is truncated to the
- * specified length. If the supplied string is shorter than the desired width,
padding characters are added to the beginning
- * and end of the string such that the length is that specified; one additional
padding character is prepended if required.
- * All leading and trailing whitespace is removed before centering.
- * @param str the string to be left justified; if null, an empty string is used
- * @param width the desired width of the string; must be positive
- * @param padWithChar the character to use for padding, if needed
- * @return the left justified string
- * @see #setLength(String, int, char)
- */
- public static String justifyCenter( String str, final int width, char padWithChar )
{
- // Trim the leading and trailing whitespace ...
- str = str != null ? str.trim() : "";
+ return sb.toString();
+ }
- int addChars = width - str.length();
- if (addChars < 0) {
- // truncate
- return str.subSequence(0, width).toString();
- }
- // Write the content ...
- int prependNumber = addChars / 2;
- int appendNumber = prependNumber;
- if ((prependNumber + appendNumber) != addChars) {
- ++prependNumber;
- }
+ /**
+ * Center the contents of the string. If the supplied string is longer than the desired
width, it is truncated to the
+ * specified length. If the supplied string is shorter than the desired width, padding
characters are added to the beginning
+ * and end of the string such that the length is that specified; one additional padding
character is prepended if required.
+ * All leading and trailing whitespace is removed before centering.
+ *
+ * @param str the string to be left justified; if null, an empty string is used
+ * @param width the desired width of the string; must be positive
+ * @param padWithChar the character to use for padding, if needed
+ * @return the left justified string
+ * @see #setLength(String, int, char)
+ */
+ public static String justifyCenter( String str,
+ final int width,
+ char padWithChar ) {
+ // Trim the leading and trailing whitespace ...
+ str = str != null ? str.trim() : "";
- final StringBuilder sb = new StringBuilder();
+ int addChars = width - str.length();
+ if (addChars < 0) {
+ // truncate
+ return str.subSequence(0, width).toString();
+ }
+ // Write the content ...
+ int prependNumber = addChars / 2;
+ int appendNumber = prependNumber;
+ if ((prependNumber + appendNumber) != addChars) {
+ ++prependNumber;
+ }
- // Prepend the pad character(s) ...
- while (prependNumber > 0) {
- sb.append(padWithChar);
- --prependNumber;
- }
+ final StringBuilder sb = new StringBuilder();
- // Add the actual content
- sb.append(str);
+ // Prepend the pad character(s) ...
+ while (prependNumber > 0) {
+ sb.append(padWithChar);
+ --prependNumber;
+ }
- // Append the pad character(s) ...
- while (appendNumber > 0) {
- sb.append(padWithChar);
- --appendNumber;
- }
+ // Add the actual content
+ sb.append(str);
- return sb.toString();
- }
+ // Append the pad character(s) ...
+ while (appendNumber > 0) {
+ sb.append(padWithChar);
+ --appendNumber;
+ }
- /**
- * Truncate the supplied string to be no more than the specified length. This method
returns an empty string if the supplied
- * object is null.
- * @param obj the object from which the string is to be obtained using {@link
Object#toString()}.
- * @param maxLength the maximum length of the string being returned
- * @return the supplied string if no longer than the maximum length, or the supplied
string truncated to be no longer than the
- * maximum length (including the suffix)
- * @throws IllegalArgumentException if the maximum length is negative
- */
- public static String truncate( Object obj, int maxLength ) {
- return truncate(obj, maxLength, null);
- }
+ return sb.toString();
+ }
- /**
- * Truncate the supplied string to be no more than the specified length. This method
returns an empty string if the supplied
- * object is null.
- * @param obj the object from which the string is to be obtained using {@link
Object#toString()}.
- * @param maxLength the maximum length of the string being returned
- * @param suffix the suffix that should be added to the content if the string must be
truncated, or null if the default suffix
- * of "..." should be used
- * @return the supplied string if no longer than the maximum length, or the supplied
string truncated to be no longer than the
- * maximum length (including the suffix)
- * @throws IllegalArgumentException if the maximum length is negative
- */
- public static String truncate( Object obj, int maxLength, String suffix ) {
- ArgCheck.isNonNegative(maxLength, "maxLength");
- if (obj == null || maxLength == 0) {
- return "";
- }
- String str = obj.toString();
- if (str.length() <= maxLength) return str;
- if (suffix == null) suffix = "...";
- int maxNumChars = maxLength - suffix.length();
- if (maxNumChars < 0) {
- // Then the max length is actually shorter than the suffix ...
- str = suffix.substring(0, maxLength);
- } else if (str.length() > maxNumChars) {
- str = str.substring(0, maxNumChars) + suffix;
- }
- return str;
- }
+ /**
+ * Truncate the supplied string to be no more than the specified length. This method
returns an empty string if the supplied
+ * object is null.
+ *
+ * @param obj the object from which the string is to be obtained using {@link
Object#toString()}.
+ * @param maxLength the maximum length of the string being returned
+ * @return the supplied string if no longer than the maximum length, or the supplied
string truncated to be no longer than the
+ * maximum length (including the suffix)
+ * @throws IllegalArgumentException if the maximum length is negative
+ */
+ public static String truncate( Object obj,
+ int maxLength ) {
+ return truncate(obj, maxLength, null);
+ }
- /**
- * Read and return the entire contents of the supplied {@link Reader}. This method
always closes the reader when finished
- * reading.
- * @param reader the reader of the contents; may be null
- * @return the contents, or an empty string if the supplied reader is null
- * @throws IOException if there is an error reading the content
- */
- public static String read( Reader reader ) throws IOException {
- return IoUtil.read(reader);
- }
+ /**
+ * Truncate the supplied string to be no more than the specified length. This method
returns an empty string if the supplied
+ * object is null.
+ *
+ * @param obj the object from which the string is to be obtained using {@link
Object#toString()}.
+ * @param maxLength the maximum length of the string being returned
+ * @param suffix the suffix that should be added to the content if the string must be
truncated, or null if the default suffix
+ * of "..." should be used
+ * @return the supplied string if no longer than the maximum length, or the supplied
string truncated to be no longer than the
+ * maximum length (including the suffix)
+ * @throws IllegalArgumentException if the maximum length is negative
+ */
+ public static String truncate( Object obj,
+ int maxLength,
+ String suffix ) {
+ ArgCheck.isNonNegative(maxLength, "maxLength");
+ if (obj == null || maxLength == 0) {
+ return "";
+ }
+ String str = obj.toString();
+ if (str.length() <= maxLength) return str;
+ if (suffix == null) suffix = "...";
+ int maxNumChars = maxLength - suffix.length();
+ if (maxNumChars < 0) {
+ // Then the max length is actually shorter than the suffix ...
+ str = suffix.substring(0, maxLength);
+ } else if (str.length() > maxNumChars) {
+ str = str.substring(0, maxNumChars) + suffix;
+ }
+ return str;
+ }
- /**
- * Read and return the entire contents of the supplied {@link InputStream}. This
method always closes the stream when
- * finished reading.
- * @param stream the streamed contents; may be null
- * @return the contents, or an empty string if the supplied stream is null
- * @throws IOException if there is an error reading the content
- */
- public static String read( InputStream stream ) throws IOException {
- return IoUtil.read(stream);
- }
+ /**
+ * Read and return the entire contents of the supplied {@link Reader}. This method
always closes the reader when finished
+ * reading.
+ *
+ * @param reader the reader of the contents; may be null
+ * @return the contents, or an empty string if the supplied reader is null
+ * @throws IOException if there is an error reading the content
+ */
+ public static String read( Reader reader ) throws IOException {
+ return IoUtil.read(reader);
+ }
- /**
- * Write the entire contents of the supplied string to the given stream. This method
always flushes and closes the stream when
- * finished.
- * @param content the content to write to the stream; may be null
- * @param stream the stream to which the content is to be written
- * @throws IOException
- * @throws IllegalArgumentException if the stream is null
- */
- public static void write( String content, OutputStream stream ) throws IOException {
- IoUtil.write(content, stream);
- }
+ /**
+ * Read and return the entire contents of the supplied {@link InputStream}. This method
always closes the stream when
+ * finished reading.
+ *
+ * @param stream the streamed contents; may be null
+ * @return the contents, or an empty string if the supplied stream is null
+ * @throws IOException if there is an error reading the content
+ */
+ public static String read( InputStream stream ) throws IOException {
+ return IoUtil.read(stream);
+ }
- /**
- * Write the entire contents of the supplied string to the given writer. This method
always flushes and closes the writer when
- * finished.
- * @param content the content to write to the writer; may be null
- * @param writer the writer to which the content is to be written
- * @throws IOException
- * @throws IllegalArgumentException if the writer is null
- */
- public static void write( String content, Writer writer ) throws IOException {
- IoUtil.write(content, writer);
- }
+ /**
+ * Write the entire contents of the supplied string to the given stream. This method
always flushes and closes the stream when
+ * finished.
+ *
+ * @param content the content to write to the stream; may be null
+ * @param stream the stream to which the content is to be written
+ * @throws IOException
+ * @throws IllegalArgumentException if the stream is null
+ */
+ public static void write( String content,
+ OutputStream stream ) throws IOException {
+ IoUtil.write(content, stream);
+ }
- /**
- * Create a human-readable form of the supplied object by choosing the representation
format based upon the object type.
- * <p>
- * <ul>
- * <li>A null reference results in the "null" string.</li>
- * <li>A string is written wrapped by double quotes.</li>
- * <li>A boolean is written using {@link Boolean#toString()}.</li>
- * <li>A {@link Number number} is written using the standard {@link
Number#toString() toString()} method.</li>
- * <li>A {@link java.util.Date date} is written using the the {@link
DateUtil#getDateAsStandardString(java.util.Date)}
- * utility method.</li>
- * <li>A {@link java.sql.Date SQL date} is written using the the {@link
DateUtil#getDateAsStandardString(java.util.Date)}
- * utility method.</li>
- * <li>A {@link Calendar Calendar instance} is written using the the {@link
DateUtil#getDateAsStandardString(Calendar)}
- * utility method.</li>
- * <li>An array of bytes is written with a leading "[ " and trailing
" ]" surrounding the bytes written as UTF-8.
- * <li>An array of objects is written with a leading "[ " and
trailing " ]", and with all objects sent through
- * {@link #readableString(Object)} and separated by ", ".</li>
- * <li>A collection of objects (e.g,
<code>Collection<?></code>) is written with a leading "[ " and
trailing " ]", and
- * with all objects sent through {@link #readableString(Object)} and separated by
", ".</li>
- * <li>A map of objects (e.g, <code>Map<?></code>) is written
with a leading "{ " and trailing " }", and with all map
- * entries written in the form "key => value" and separated by ",
". All key and value objects are sent through the
- * {@link #readableString(Object)} method.</li>
- * <li>Any other object is written using the object's {@link
Object#toString() toString()} method.</li>
- * </ul>
- * </p>
- * <p>
- * This method is capable of generating strings for nested objects. For example, a
<code>Map<Date,Object[]></code> would be
- * written in the form:
- *
- * <pre>
- * { 2008-02-03T14:22:49 => [ "description", 3, [
003459de7389g23aef, true ] ] }
- * </pre>
- *
- * </p>
- * @param obj the object that is to be converted to a string.
- * @return the string representation that is to be human readable
- */
- public static String readableString( Object obj ) {
- if (obj == null) return "null";
- if (obj instanceof Boolean) return ((Boolean)obj).toString();
- if (obj instanceof String) return "\"" + obj.toString() +
"\"";
- if (obj instanceof Number) return obj.toString();
- if (obj instanceof Map) return readableString((Map)obj);
- if (obj instanceof Collection) return readableString((Collection)obj);
- if (obj instanceof byte[]) return readableString((byte[])obj);
- if (obj instanceof boolean[]) return readableString((boolean[])obj);
- if (obj instanceof short[]) return readableString((short[])obj);
- if (obj instanceof int[]) return readableString((int[])obj);
- if (obj instanceof long[]) return readableString((long[])obj);
- if (obj instanceof float[]) return readableString((float[])obj);
- if (obj instanceof double[]) return readableString((double[])obj);
- if (obj instanceof Object[]) return readableString((Object[])obj);
- if (obj instanceof Calendar) return
DateUtil.getDateAsStandardString((Calendar)obj);
- if (obj instanceof java.util.Date) return
DateUtil.getDateAsStandardString((java.util.Date)obj);
- if (obj instanceof java.sql.Date) return
DateUtil.getDateAsStandardString((java.sql.Date)obj);
- return obj.toString();
- }
+ /**
+ * Write the entire contents of the supplied string to the given writer. This method
always flushes and closes the writer when
+ * finished.
+ *
+ * @param content the content to write to the writer; may be null
+ * @param writer the writer to which the content is to be written
+ * @throws IOException
+ * @throws IllegalArgumentException if the writer is null
+ */
+ public static void write( String content,
+ Writer writer ) throws IOException {
+ IoUtil.write(content, writer);
+ }
- protected static String readableEmptyArray( Class arrayClass ) {
- assert arrayClass != null;
- Class componentType = arrayClass.getComponentType();
- if (componentType.isArray()) return "[" +
readableEmptyArray(componentType) + "]";
- return "[]";
- }
+ /**
+ * Create a human-readable form of the supplied object by choosing the representation
format based upon the object type.
+ * <p>
+ * <ul>
+ * <li>A null reference results in the "null" string.</li>
+ * <li>A string is written wrapped by double quotes.</li>
+ * <li>A boolean is written using {@link Boolean#toString()}.</li>
+ * <li>A {@link Number number} is written using the standard {@link
Number#toString() toString()} method.</li>
+ * <li>A {@link java.util.Date date} is written using the the {@link
DateUtil#getDateAsStandardString(java.util.Date)}
+ * utility method.</li>
+ * <li>A {@link java.sql.Date SQL date} is written using the the {@link
DateUtil#getDateAsStandardString(java.util.Date)}
+ * utility method.</li>
+ * <li>A {@link Calendar Calendar instance} is written using the the {@link
DateUtil#getDateAsStandardString(Calendar)}
+ * utility method.</li>
+ * <li>An array of bytes is written with a leading "[ " and trailing
" ]" surrounding the bytes written as UTF-8.
+ * <li>An array of objects is written with a leading "[ " and trailing
" ]", and with all objects sent through
+ * {@link #readableString(Object)} and separated by ", ".</li>
+ * <li>A collection of objects (e.g, <code>Collection<?></code>)
is written with a leading "[ " and trailing " ]", and
+ * with all objects sent through {@link #readableString(Object)} and separated by
", ".</li>
+ * <li>A map of objects (e.g, <code>Map<?></code>) is written
with a leading "{ " and trailing " }", and with all map
+ * entries written in the form "key => value" and separated by ",
". All key and value objects are sent through the
+ * {@link #readableString(Object)} method.</li>
+ * <li>Any other object is written using the object's {@link Object#toString()
toString()} method.</li>
+ * </ul>
+ * </p>
+ * <p>
+ * This method is capable of generating strings for nested objects. For example, a
<code>Map<Date,Object[]></code> would be
+ * written in the form:
+ *
+ * <pre>
+ * { 2008-02-03T14:22:49 => [ "description", 3, [
003459de7389g23aef, true ] ] }
+ * </pre>
+ *
+ * </p>
+ *
+ * @param obj the object that is to be converted to a string.
+ * @return the string representation that is to be human readable
+ */
+ public static String readableString( Object obj ) {
+ if (obj == null) return "null";
+ if (obj instanceof Boolean) return ((Boolean)obj).toString();
+ if (obj instanceof String) return "\"" + obj.toString() +
"\"";
+ if (obj instanceof Number) return obj.toString();
+ if (obj instanceof Map) return readableString((Map)obj);
+ if (obj instanceof Collection) return readableString((Collection)obj);
+ if (obj instanceof byte[]) return readableString((byte[])obj);
+ if (obj instanceof boolean[]) return readableString((boolean[])obj);
+ if (obj instanceof short[]) return readableString((short[])obj);
+ if (obj instanceof int[]) return readableString((int[])obj);
+ if (obj instanceof long[]) return readableString((long[])obj);
+ if (obj instanceof float[]) return readableString((float[])obj);
+ if (obj instanceof double[]) return readableString((double[])obj);
+ if (obj instanceof Object[]) return readableString((Object[])obj);
+ if (obj instanceof Calendar) return DateUtil.getDateAsStandardString((Calendar)obj);
+ if (obj instanceof java.util.Date) return
DateUtil.getDateAsStandardString((java.util.Date)obj);
+ if (obj instanceof java.sql.Date) return
DateUtil.getDateAsStandardString((java.sql.Date)obj);
+ return obj.toString();
+ }
- protected static String readableString( Object[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (Object value : array) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
+ protected static String readableEmptyArray( Class arrayClass ) {
+ assert arrayClass != null;
+ Class componentType = arrayClass.getComponentType();
+ if (componentType.isArray()) return "[" + readableEmptyArray(componentType) +
"]";
+ return "[]";
+ }
- protected static String readableString( int[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (int value : array) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
+ protected static String readableString( Object[] array ) {
+ assert array != null;
+ if (array.length == 0) return readableEmptyArray(array.getClass());
+ StringBuilder sb = new StringBuilder();
+ boolean first = true;
+ sb.append("[ ");
+ for (Object value : array) {
+ if (first) {
+ first = false;
+ } else {
+ sb.append(", ");
+ }
+ sb.append(readableString(value));
+ }
+ sb.append(" ]");
+ return sb.toString();
+ }
- protected static String readableString( short[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (short value : array) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
+ protected static String readableString( int[] array ) {
+ assert array != null;
+ if (array.length == 0) return readableEmptyArray(array.getClass());
+ StringBuilder sb = new StringBuilder();
+ boolean first = true;
+ sb.append("[ ");
+ for (int value : array) {
+ if (first) {
+ first = false;
+ } else {
+ sb.append(", ");
+ }
+ sb.append(readableString(value));
+ }
+ sb.append(" ]");
+ return sb.toString();
+ }
- protected static String readableString( long[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (long value : array) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
+ protected static String readableString( short[] array ) {
+ assert array != null;
+ if (array.length == 0) return readableEmptyArray(array.getClass());
+ StringBuilder sb = new StringBuilder();
+ boolean first = true;
+ sb.append("[ ");
+ for (short value : array) {
+ if (first) {
+ first = false;
+ } else {
+ sb.append(", ");
+ }
+ sb.append(readableString(value));
+ }
+ sb.append(" ]");
+ return sb.toString();
+ }
- protected static String readableString( boolean[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (boolean value : array) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
+ protected static String readableString( long[] array ) {
+ assert array != null;
+ if (array.length == 0) return readableEmptyArray(array.getClass());
+ StringBuilder sb = new StringBuilder();
+ boolean first = true;
+ sb.append("[ ");
+ for (long value : array) {
+ if (first) {
+ first = false;
+ } else {
+ sb.append(", ");
+ }
+ sb.append(readableString(value));
+ }
+ sb.append(" ]");
+ return sb.toString();
+ }
- protected static String readableString( float[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (float value : array) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
+ protected static String readableString( boolean[] array ) {
+ assert array != null;
+ if (array.length == 0) return readableEmptyArray(array.getClass());
+ StringBuilder sb = new StringBuilder();
+ boolean first = true;
+ sb.append("[ ");
+ for (boolean value : array) {
+ if (first) {
+ first = false;
+ } else {
+ sb.append(", ");
+ }
+ sb.append(readableString(value));
+ }
+ sb.append(" ]");
+ return sb.toString();
+ }
- protected static String readableString( double[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (double value : array) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
+ protected static String readableString( float[] array ) {
+ assert array != null;
+ if (array.length == 0) return readableEmptyArray(array.getClass());
+ StringBuilder sb = new StringBuilder();
+ boolean first = true;
+ sb.append("[ ");
+ for (float value : array) {
+ if (first) {
+ first = false;
+ } else {
+ sb.append(", ");
+ }
+ sb.append(readableString(value));
+ }
+ sb.append(" ]");
+ return sb.toString();
+ }
- protected static String readableString( byte[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- sb.append("[ ");
- try {
- sb.append(new String(array, "UTF-8"));
- } catch (UnsupportedEncodingException e) {
- throw new SystemFailureException(e);
- }
- sb.append(" ]");
- return sb.toString();
- }
+ protected static String readableString( double[] array ) {
+ assert array != null;
+ if (array.length == 0) return readableEmptyArray(array.getClass());
+ StringBuilder sb = new StringBuilder();
+ boolean first = true;
+ sb.append("[ ");
+ for (double value : array) {
+ if (first) {
+ first = false;
+ } else {
+ sb.append(", ");
+ }
+ sb.append(readableString(value));
+ }
+ sb.append(" ]");
+ return sb.toString();
+ }
- protected static String readableString( Collection<?> collection ) {
- assert collection != null;
- if (collection.isEmpty()) return "[]";
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (Object value : collection) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
+ protected static String readableString( byte[] array ) {
+ assert array != null;
+ if (array.length == 0) return readableEmptyArray(array.getClass());
+ StringBuilder sb = new StringBuilder();
+ sb.append("[ ");
+ try {
+ sb.append(new String(array, "UTF-8"));
+ } catch (UnsupportedEncodingException e) {
+ throw new SystemFailureException(e);
+ }
+ sb.append(" ]");
+ return sb.toString();
+ }
- protected static String readableString( Map<?, ?> map ) {
- assert map != null;
- if (map.isEmpty()) return "{}";
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("{ ");
- for (Map.Entry<?, ?> entry : map.entrySet()) {
- Object key = entry.getKey();
- Object value = entry.getValue();
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(key));
- sb.append(" => ");
- sb.append(readableString(value));
- }
- sb.append(" }");
- return sb.toString();
- }
+ protected static String readableString( Collection<?> collection ) {
+ assert collection != null;
+ if (collection.isEmpty()) return "[]";
+ StringBuilder sb = new StringBuilder();
+ boolean first = true;
+ sb.append("[ ");
+ for (Object value : collection) {
+ if (first) {
+ first = false;
+ } else {
+ sb.append(", ");
+ }
+ sb.append(readableString(value));
+ }
+ sb.append(" ]");
+ return sb.toString();
+ }
- /**
- * Get the stack trace of the supplied exception.
- * @param t the exception for which the stack trace is to be returned
- * @return the stack trace, or null if the supplied exception is null
- */
- public static String getStackTrace( Throwable t ) {
- if (t == null) return null;
- final ByteArrayOutputStream bas = new ByteArrayOutputStream();
- final PrintWriter pw = new PrintWriter(bas);
- t.printStackTrace(pw);
- pw.close();
- return bas.toString();
- }
+ protected static String readableString( Map<?, ?> map ) {
+ assert map != null;
+ if (map.isEmpty()) return "{}";
+ StringBuilder sb = new StringBuilder();
+ boolean first = true;
+ sb.append("{ ");
+ for (Map.Entry<?, ?> entry : map.entrySet()) {
+ Object key = entry.getKey();
+ Object value = entry.getValue();
+ if (first) {
+ first = false;
+ } else {
+ sb.append(", ");
+ }
+ sb.append(readableString(key));
+ sb.append(" => ");
+ sb.append(readableString(value));
+ }
+ sb.append(" }");
+ return sb.toString();
+ }
- private StringUtil() {
- // Prevent construction
- }
+ /**
+ * Get the stack trace of the supplied exception.
+ *
+ * @param t the exception for which the stack trace is to be returned
+ * @return the stack trace, or null if the supplied exception is null
+ */
+ public static String getStackTrace( Throwable t ) {
+ if (t == null) return null;
+ final ByteArrayOutputStream bas = new ByteArrayOutputStream();
+ final PrintWriter pw = new PrintWriter(bas);
+ t.printStackTrace(pw);
+ pw.close();
+ return bas.toString();
+ }
+
+ private StringUtil() {
+ // Prevent construction
+ }
}
Modified: trunk/dna-common/src/test/java/org/jboss/dna/common/i18n/I18nTest.java
===================================================================
--- trunk/dna-common/src/test/java/org/jboss/dna/common/i18n/I18nTest.java 2008-05-07
13:37:37 UTC (rev 119)
+++ trunk/dna-common/src/test/java/org/jboss/dna/common/i18n/I18nTest.java 2008-05-07
16:25:17 UTC (rev 120)
@@ -349,7 +349,6 @@
try {
TestI18n.testMessage1.text();
} catch (IllegalArgumentException err) {
- assertThat(err.getMessage(), is(CommonI18n.i18nArgumentsMismatchedParameter.text(0,
"testMessage1", 1, "{0}", "{0}")));
System.err.println(err);
throw err;
}
@@ -361,8 +360,6 @@
try {
TestI18n.testMessage1.text("Test", "Message");
} catch (IllegalArgumentException err) {
- assertThat(err.getMessage(),
- is(CommonI18n.i18nArgumentsMismatchedParameter.text(2,
"testMessage1", 1, "{0}", "Test")));
System.err.println(err);
throw err;
}
Modified: trunk/dna-common/src/test/java/org/jboss/dna/common/util/StringUtilTest.java
===================================================================
---
trunk/dna-common/src/test/java/org/jboss/dna/common/util/StringUtilTest.java 2008-05-07
13:37:37 UTC (rev 119)
+++
trunk/dna-common/src/test/java/org/jboss/dna/common/util/StringUtilTest.java 2008-05-07
16:25:17 UTC (rev 120)
@@ -2,7 +2,7 @@
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
+ * distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
@@ -41,370 +41,431 @@
public class StringUtilTest {
- @Before
- public void beforeEach() throws Exception {
- }
+ @Before
+ public void beforeEach() throws Exception {
+ }
- public void compareSeparatedLines( Object... lines ) {
- ByteArrayOutputStream content = new ByteArrayOutputStream();
- PrintStream stream = new PrintStream(content);
- for (Object line : lines) {
- stream.println(line);
- }
- List<String> actualLines = StringUtil.splitLines(content.toString());
- assertArrayEquals(lines, actualLines.toArray());
- }
+ public void compareSeparatedLines( Object... lines ) {
+ ByteArrayOutputStream content = new ByteArrayOutputStream();
+ PrintStream stream = new PrintStream(content);
+ for (Object line : lines) {
+ stream.println(line);
+ }
+ List<String> actualLines = StringUtil.splitLines(content.toString());
+ assertArrayEquals(lines, actualLines.toArray());
+ }
- @Test
- public void splitLinesShouldWorkCorrectly() {
- compareSeparatedLines("Line 1", "Line 2", "Line 3",
"Line 4");
- }
+ @Test
+ public void splitLinesShouldWorkCorrectly() {
+ compareSeparatedLines("Line 1", "Line 2", "Line 3",
"Line 4");
+ }
- @Test
- public void createStringShouldCreateStringFromPattern() {
- String pattern = "This {0} is {1} should {2} not {3} last {4}";
- assertEquals("This one is two should three not four last five",
StringUtil.createString(pattern, "one", "two", "three",
"four", "five"));
- }
+ @Test( expected = IllegalArgumentException.class )
+ public void createStringShouldFailIfNoPatternSupplied() {
+ StringUtil.createString(null, (Object[])null);
+ }
- @Test
- public void setLengthShouldTruncateStringsThatAreTooLong() {
- assertEquals("This is the st", StringUtil.setLength("This is the
string", 14, ' '));
- }
+ @Test
+ public void createStringShouldAllowNoParametersSupplied() {
+ assertThat(StringUtil.createString("test", (Object[])null),
is("test"));
+ }
- @Test
- public void setLengthShouldAppendCharacterForStringsThatAreTooShort() {
- assertEquals("This ", StringUtil.setLength("This", 10,
' '));
- }
+ @Test
+ public void createStringShouldCreateStringFromPattern() {
+ String pattern = "This {0} is {1} should {2} not {3} last {4}";
+ assertEquals("This one is two should three not four last five",
StringUtil.createString(pattern,
+
"one",
+
"two",
+
"three",
+
"four",
+
"five"));
+ }
- @Test
- public void setLengthShouldNotRemoveLeadingWhitespace() {
- assertEquals(" This ", StringUtil.setLength(" This", 10,
' '));
- assertEquals("\tThis ", StringUtil.setLength("\tThis",
10, ' '));
- }
+ @Test( expected = IllegalArgumentException.class )
+ public void createStringShouldFailIfTooFewArgumentsSupplied() {
+ String pattern = "This {0} is {1} should {2} not {3} last {4}";
+ try {
+ StringUtil.createString(pattern, "one", "two", "three",
"four");
+ } catch (IllegalArgumentException err) {
+ System.err.println(err);
+ throw err;
+ }
+ }
- @Test
- public void setLengthShouldAppendCharacterForEmptyStrings() {
- assertEquals(" ", StringUtil.setLength("", 10, '
'));
- }
+ @Test( expected = IllegalArgumentException.class )
+ public void createStringShouldFailIfTooManyArgumentsSupplied() {
+ String pattern = "This {0} is {1} should {2} not {3} last {4}";
+ try {
+ StringUtil.createString(pattern, "one", "two", "three",
"four", "five", "six");
+ } catch (IllegalArgumentException err) {
+ System.err.println(err);
+ throw err;
+ }
+ }
- @Test
- public void setLengthShouldAppendCharacterForNullStrings() {
- assertEquals(" ", StringUtil.setLength(null, 10, '
'));
- }
+ @Test
+ public void createStringExceptionMessageShouldbeGrammaticallyCorrect() {
+ String pattern = "One = {0}";
+ try {
+ StringUtil.createString(pattern);
+ } catch (IllegalArgumentException err) {
+ assertThat(err.getMessage().startsWith("0 parameters supplied, but 1 parameter
required"), is(true));
+ }
+ pattern = "One";
+ try {
+ StringUtil.createString(pattern, "one");
+ } catch (IllegalArgumentException err) {
+ assertThat(err.getMessage().startsWith("1 parameter supplied, but 0 parameters
required"), is(true));
+ }
+ pattern = "One = {0}, Two = {1}";
+ try {
+ StringUtil.createString(pattern);
+ } catch (IllegalArgumentException err) {
+ assertThat(err.getMessage().startsWith("0 parameters supplied, but 2 parameters
required"), is(true));
+ }
+ }
- @Test
- public void setLengthShouldReturnStringsThatAreTheDesiredLength() {
- assertEquals("This is the string", StringUtil.setLength("This is
the string", 18, ' '));
- }
+ @Test
+ public void setLengthShouldTruncateStringsThatAreTooLong() {
+ assertEquals("This is the st", StringUtil.setLength("This is the
string", 14, ' '));
+ }
- @Test
- public void justifyLeftShouldTruncateStringsThatAreTooLong() {
- assertEquals("This is the st", StringUtil.justifyLeft("This is the
string", 14, ' '));
- }
+ @Test
+ public void setLengthShouldAppendCharacterForStringsThatAreTooShort() {
+ assertEquals("This ", StringUtil.setLength("This", 10, '
'));
+ }
- @Test
- public void justifyLeftShouldAppendCharacterForStringsThatAreTooShort() {
- assertEquals("This ", StringUtil.justifyLeft("This", 10,
' '));
- }
+ @Test
+ public void setLengthShouldNotRemoveLeadingWhitespace() {
+ assertEquals(" This ", StringUtil.setLength(" This", 10, '
'));
+ assertEquals("\tThis ", StringUtil.setLength("\tThis", 10,
' '));
+ }
- @Test
- public void justifyLeftShouldRemoveLeadingWhitespace() {
- assertEquals("This ", StringUtil.justifyLeft(" This",
10, ' '));
- assertEquals("This ", StringUtil.justifyLeft("\tThis",
10, ' '));
- }
+ @Test
+ public void setLengthShouldAppendCharacterForEmptyStrings() {
+ assertEquals(" ", StringUtil.setLength("", 10, '
'));
+ }
- @Test
- public void justifyLeftShouldAppendCharacterForEmptyStrings() {
- assertEquals(" ", StringUtil.justifyLeft("", 10,
' '));
- }
+ @Test
+ public void setLengthShouldAppendCharacterForNullStrings() {
+ assertEquals(" ", StringUtil.setLength(null, 10, ' '));
+ }
- @Test
- public void justifyLeftShouldAppendCharacterForNullStrings() {
- assertEquals(" ", StringUtil.justifyLeft(null, 10, '
'));
- }
+ @Test
+ public void setLengthShouldReturnStringsThatAreTheDesiredLength() {
+ assertEquals("This is the string", StringUtil.setLength("This is the
string", 18, ' '));
+ }
- @Test
- public void justifyLeftShouldReturnStringsThatAreTheDesiredLength() {
- assertEquals("This is the string", StringUtil.justifyLeft("This is
the string", 18, ' '));
- }
+ @Test
+ public void justifyLeftShouldTruncateStringsThatAreTooLong() {
+ assertEquals("This is the st", StringUtil.justifyLeft("This is the
string", 14, ' '));
+ }
- @Test
- public void justifyRightShouldTruncateStringsThatAreTooLong() {
- assertEquals(" is the string", StringUtil.justifyRight("This is
the string", 14, ' '));
- }
+ @Test
+ public void justifyLeftShouldAppendCharacterForStringsThatAreTooShort() {
+ assertEquals("This ", StringUtil.justifyLeft("This", 10, '
'));
+ }
- @Test
- public void justifyRightShouldPrependCharacterForStringsThatAreTooShort() {
- assertEquals(" This", StringUtil.justifyRight("This",
10, ' '));
- }
+ @Test
+ public void justifyLeftShouldRemoveLeadingWhitespace() {
+ assertEquals("This ", StringUtil.justifyLeft(" This", 10,
' '));
+ assertEquals("This ", StringUtil.justifyLeft("\tThis", 10,
' '));
+ }
- @Test
- public void justifyRightShouldPrependCharacterForEmptyStrings() {
- assertEquals(" ", StringUtil.justifyRight("", 10,
' '));
- }
+ @Test
+ public void justifyLeftShouldAppendCharacterForEmptyStrings() {
+ assertEquals(" ", StringUtil.justifyLeft("", 10, '
'));
+ }
- @Test
- public void justifyRightShouldPrependCharacterForNullStrings() {
- assertEquals(" ", StringUtil.justifyRight(null, 10, '
'));
- }
+ @Test
+ public void justifyLeftShouldAppendCharacterForNullStrings() {
+ assertEquals(" ", StringUtil.justifyLeft(null, 10, ' '));
+ }
- @Test
- public void justifyRightShouldReturnStringsThatAreTheDesiredLength() {
- assertEquals("This is the string", StringUtil.justifyRight("This
is the string", 18, ' '));
- }
+ @Test
+ public void justifyLeftShouldReturnStringsThatAreTheDesiredLength() {
+ assertEquals("This is the string", StringUtil.justifyLeft("This is the
string", 18, ' '));
+ }
- @Test
- public void justifyCenterShouldTruncateStringsThatAreTooLong() {
- assertEquals("This is the st", StringUtil.justifyCenter("This is
the string", 14, ' '));
- }
+ @Test
+ public void justifyRightShouldTruncateStringsThatAreTooLong() {
+ assertEquals(" is the string", StringUtil.justifyRight("This is the
string", 14, ' '));
+ }
- @Test
- public void
justifyCenterShouldPrependAndAppendSameNumberOfCharacterForStringsThatAreTooShortButOfAnEvenLength()
{
- assertEquals(" This ", StringUtil.justifyCenter("This",
10, ' '));
- }
+ @Test
+ public void justifyRightShouldPrependCharacterForStringsThatAreTooShort() {
+ assertEquals(" This", StringUtil.justifyRight("This", 10,
' '));
+ }
- @Test
- public void
justifyCenterShouldPrependOneMoreCharacterThanAppendingForStringsThatAreTooShortButOfAnOddLength()
{
- assertEquals(" Thing ", StringUtil.justifyCenter("Thing",
10, ' '));
- }
+ @Test
+ public void justifyRightShouldPrependCharacterForEmptyStrings() {
+ assertEquals(" ", StringUtil.justifyRight("", 10, '
'));
+ }
- @Test
- public void justifyCenterShouldPrependCharacterForEmptyStrings() {
- assertEquals(" ", StringUtil.justifyCenter("", 10,
' '));
- }
+ @Test
+ public void justifyRightShouldPrependCharacterForNullStrings() {
+ assertEquals(" ", StringUtil.justifyRight(null, 10, ' '));
+ }
- @Test
- public void justifyCenterShouldPrependCharacterForNullStrings() {
- assertEquals(" ", StringUtil.justifyCenter(null, 10, '
'));
- }
+ @Test
+ public void justifyRightShouldReturnStringsThatAreTheDesiredLength() {
+ assertEquals("This is the string", StringUtil.justifyRight("This is the
string", 18, ' '));
+ }
- @Test
- public void justifyCenterShouldReturnStringsThatAreTheDesiredLength() {
- assertEquals("This is the string", StringUtil.justifyCenter("This
is the string", 18, ' '));
- }
+ @Test
+ public void justifyCenterShouldTruncateStringsThatAreTooLong() {
+ assertEquals("This is the st", StringUtil.justifyCenter("This is the
string", 14, ' '));
+ }
- @Test
- public void truncateShouldReturnEmptyStringIfNullReferenceIsSupplied() {
- assertThat(StringUtil.truncate(null, 0), is(""));
- assertThat(StringUtil.truncate(null, 1), is(""));
- assertThat(StringUtil.truncate(null, 100), is(""));
- }
+ @Test
+ public void
justifyCenterShouldPrependAndAppendSameNumberOfCharacterForStringsThatAreTooShortButOfAnEvenLength()
{
+ assertEquals(" This ", StringUtil.justifyCenter("This", 10,
' '));
+ }
- @Test( expected = IllegalArgumentException.class )
- public void truncateShouldNotAllowNegativeLength() {
- StringUtil.truncate("some string", -1);
- }
+ @Test
+ public void
justifyCenterShouldPrependOneMoreCharacterThanAppendingForStringsThatAreTooShortButOfAnOddLength()
{
+ assertEquals(" Thing ", StringUtil.justifyCenter("Thing", 10,
' '));
+ }
- @Test
- public void truncateShouldReturnEmptyStringForMaximumLengthOfZero() {
- String str = "This is the string with some text";
- assertThat(StringUtil.truncate(str, 0), is(""));
- assertThat(StringUtil.truncate("", 0), is(""));
- assertThat(StringUtil.truncate(str, 0, "123"), is(""));
- assertThat(StringUtil.truncate("", 0, "123"),
is(""));
- }
+ @Test
+ public void justifyCenterShouldPrependCharacterForEmptyStrings() {
+ assertEquals(" ", StringUtil.justifyCenter("", 10, '
'));
+ }
- @Test
- public void truncateShouldNotTruncateStringShorterThanMaximumLength() {
- String str = "This is the string with some text";
- assertThat(StringUtil.truncate(str, str.length() + 2), is(str));
- assertThat(StringUtil.truncate(str, str.length() + 2, null), is(str));
- assertThat(StringUtil.truncate(str, str.length() + 2, "really long
suffix"), is(str));
- }
+ @Test
+ public void justifyCenterShouldPrependCharacterForNullStrings() {
+ assertEquals(" ", StringUtil.justifyCenter(null, 10, ' '));
+ }
- @Test
- public void truncateShouldNotTruncateStringWithLengthEqualToMaximumLength() {
- String str = "This is the string with some text";
- assertThat(StringUtil.truncate(str, str.length()), is(str));
- assertThat(StringUtil.truncate(str, str.length(), null), is(str));
- assertThat(StringUtil.truncate(str, str.length(), "really long
suffix"), is(str));
- }
+ @Test
+ public void justifyCenterShouldReturnStringsThatAreTheDesiredLength() {
+ assertEquals("This is the string", StringUtil.justifyCenter("This is the
string", 18, ' '));
+ }
- @Test
- public void truncateShouldProperlyTruncateStringWithLengthGreaterThanMaximumLength()
{
- String str = "This is the string";
- assertThat(StringUtil.truncate(str, str.length() - 1), is("This is the
st..."));
- assertThat(StringUtil.truncate(str, str.length() - 1, null), is("This is the
st..."));
- assertThat(StringUtil.truncate(str, str.length() - 1, "X"),
is("This is the striX"));
- }
+ @Test
+ public void truncateShouldReturnEmptyStringIfNullReferenceIsSupplied() {
+ assertThat(StringUtil.truncate(null, 0), is(""));
+ assertThat(StringUtil.truncate(null, 1), is(""));
+ assertThat(StringUtil.truncate(null, 100), is(""));
+ }
- @Test
- public void
truncateShouldProperlyTruncateStringWithLengthGreaterThanMaximumLengthAndMaximumLengthLongerThanPrefixLength()
{
- String str = "This is the string";
- assertThat(StringUtil.truncate(str, 2), is(".."));
- assertThat(StringUtil.truncate(str, 2, null), is(".."));
- assertThat(StringUtil.truncate(str, 1, "XX"), is("X"));
- }
+ @Test( expected = IllegalArgumentException.class )
+ public void truncateShouldNotAllowNegativeLength() {
+ StringUtil.truncate("some string", -1);
+ }
- @Test
- public void readShouldReturnEmptyStringForNullInputStream() throws Exception {
- assertThat(StringUtil.read((InputStream)null), is(""));
- }
+ @Test
+ public void truncateShouldReturnEmptyStringForMaximumLengthOfZero() {
+ String str = "This is the string with some text";
+ assertThat(StringUtil.truncate(str, 0), is(""));
+ assertThat(StringUtil.truncate("", 0), is(""));
+ assertThat(StringUtil.truncate(str, 0, "123"), is(""));
+ assertThat(StringUtil.truncate("", 0, "123"), is(""));
+ }
- @Test
- public void readShouldReturnEmptyStringForNullReader() throws Exception {
- assertThat(StringUtil.read((Reader)null), is(""));
- }
+ @Test
+ public void truncateShouldNotTruncateStringShorterThanMaximumLength() {
+ String str = "This is the string with some text";
+ assertThat(StringUtil.truncate(str, str.length() + 2), is(str));
+ assertThat(StringUtil.truncate(str, str.length() + 2, null), is(str));
+ assertThat(StringUtil.truncate(str, str.length() + 2, "really long suffix"),
is(str));
+ }
- @Test
- public void readShouldReadInputStreamCorrectlyAndShouldCloseStream() throws Exception
{
- // Read content shorter than buffer size ...
- String content = "This is the way to grandma's house.";
- InputStream stream = new ByteArrayInputStream(content.getBytes());
- InputStreamWrapper wrapper = new InputStreamWrapper(stream);
- assertThat(wrapper.isClosed(), is(false));
- assertThat(StringUtil.read(wrapper), is(content));
- assertThat(wrapper.isClosed(), is(true));
+ @Test
+ public void truncateShouldNotTruncateStringWithLengthEqualToMaximumLength() {
+ String str = "This is the string with some text";
+ assertThat(StringUtil.truncate(str, str.length()), is(str));
+ assertThat(StringUtil.truncate(str, str.length(), null), is(str));
+ assertThat(StringUtil.truncate(str, str.length(), "really long suffix"),
is(str));
+ }
- // Read content longer than buffer size ...
- for (int i = 0; i != 10; ++i) {
- content += content; // note this doubles each time!
- }
- stream = new ByteArrayInputStream(content.getBytes());
- wrapper = new InputStreamWrapper(stream);
- assertThat(wrapper.isClosed(), is(false));
- assertThat(StringUtil.read(wrapper), is(content));
- assertThat(wrapper.isClosed(), is(true));
- }
+ @Test
+ public void truncateShouldProperlyTruncateStringWithLengthGreaterThanMaximumLength() {
+ String str = "This is the string";
+ assertThat(StringUtil.truncate(str, str.length() - 1), is("This is the
st..."));
+ assertThat(StringUtil.truncate(str, str.length() - 1, null), is("This is the
st..."));
+ assertThat(StringUtil.truncate(str, str.length() - 1, "X"), is("This is
the striX"));
+ }
- @Test
- public void readShouldReadReaderCorrectlyAndShouldCloseStream() throws Exception {
- // Read content shorter than buffer size ...
- String content = "This is the way to grandma's house.";
- Reader reader = new StringReader(content);
- ReaderWrapper wrapper = new ReaderWrapper(reader);
- assertThat(wrapper.isClosed(), is(false));
- assertThat(StringUtil.read(wrapper), is(content));
- assertThat(wrapper.isClosed(), is(true));
+ @Test
+ public void
truncateShouldProperlyTruncateStringWithLengthGreaterThanMaximumLengthAndMaximumLengthLongerThanPrefixLength()
{
+ String str = "This is the string";
+ assertThat(StringUtil.truncate(str, 2), is(".."));
+ assertThat(StringUtil.truncate(str, 2, null), is(".."));
+ assertThat(StringUtil.truncate(str, 1, "XX"), is("X"));
+ }
- // Read content longer than buffer size ...
- for (int i = 0; i != 10; ++i) {
- content += content; // note this doubles each time!
- }
- reader = new StringReader(content);
- wrapper = new ReaderWrapper(reader);
- assertThat(wrapper.isClosed(), is(false));
- assertThat(StringUtil.read(wrapper), is(content));
- assertThat(wrapper.isClosed(), is(true));
- }
+ @Test
+ public void readShouldReturnEmptyStringForNullInputStream() throws Exception {
+ assertThat(StringUtil.read((InputStream)null), is(""));
+ }
- @Test
- public void getStackTraceShouldReturnStackTrace() {
- String msg = "This is the message for a test exception";
- Throwable t = new IllegalArgumentException(msg);
- String trace = StringUtil.getStackTrace(t);
- assertThat(trace, containsString(msg));
- assertThat(trace, containsString(this.getClass().getName()));
- }
+ @Test
+ public void readShouldReturnEmptyStringForNullReader() throws Exception {
+ assertThat(StringUtil.read((Reader)null), is(""));
+ }
- @Test
- public void readableStringShouldReturnStringForNull() {
- assertThat(StringUtil.readableString((Object)null), is("null"));
- }
+ @Test
+ public void readShouldReadInputStreamCorrectlyAndShouldCloseStream() throws Exception {
+ // Read content shorter than buffer size ...
+ String content = "This is the way to grandma's house.";
+ InputStream stream = new ByteArrayInputStream(content.getBytes());
+ InputStreamWrapper wrapper = new InputStreamWrapper(stream);
+ assertThat(wrapper.isClosed(), is(false));
+ assertThat(StringUtil.read(wrapper), is(content));
+ assertThat(wrapper.isClosed(), is(true));
- @Test
- public void readableStringShouldReturnStringFormOfBoolean() {
- assertThat(StringUtil.readableString(true), is(Boolean.TRUE.toString()));
- assertThat(StringUtil.readableString(false), is(Boolean.FALSE.toString()));
- assertThat(StringUtil.readableString(Boolean.TRUE),
is(Boolean.TRUE.toString()));
- assertThat(StringUtil.readableString(Boolean.FALSE),
is(Boolean.FALSE.toString()));
- }
+ // Read content longer than buffer size ...
+ for (int i = 0; i != 10; ++i) {
+ content += content; // note this doubles each time!
+ }
+ stream = new ByteArrayInputStream(content.getBytes());
+ wrapper = new InputStreamWrapper(stream);
+ assertThat(wrapper.isClosed(), is(false));
+ assertThat(StringUtil.read(wrapper), is(content));
+ assertThat(wrapper.isClosed(), is(true));
+ }
- @Test
- public void readableStringShouldReturnStringFormOfNumber() {
- assertThat(StringUtil.readableString(1), is("1"));
- assertThat(StringUtil.readableString(-513), is("-513"));
- assertThat(StringUtil.readableString(-513.3f), is("-513.3"));
- assertThat(StringUtil.readableString(-513.3d), is("-513.3"));
- assertThat(StringUtil.readableString(new Short((short)1)), is("1"));
- assertThat(StringUtil.readableString(new Integer(-513)), is("-513"));
- assertThat(StringUtil.readableString(new Float(-513.3f)),
is("-513.3"));
- assertThat(StringUtil.readableString(new Double(-513.3d)),
is("-513.3"));
- }
+ @Test
+ public void readShouldReadReaderCorrectlyAndShouldCloseStream() throws Exception {
+ // Read content shorter than buffer size ...
+ String content = "This is the way to grandma's house.";
+ Reader reader = new StringReader(content);
+ ReaderWrapper wrapper = new ReaderWrapper(reader);
+ assertThat(wrapper.isClosed(), is(false));
+ assertThat(StringUtil.read(wrapper), is(content));
+ assertThat(wrapper.isClosed(), is(true));
- @Test
- public void readableStringShouldWrapObjectArrayWithSquareBraces() {
- assertThat(StringUtil.readableString(new int[] {}), is("[]"));
- assertThat(StringUtil.readableString(new int[] {1}), is("[ 1 ]"));
- assertThat(StringUtil.readableString(new int[] {1, 2, 3, 4}), is("[ 1, 2, 3,
4 ]"));
- assertThat(StringUtil.readableString(new short[] {1, 2, 3, 4}), is("[ 1, 2,
3, 4 ]"));
- assertThat(StringUtil.readableString(new boolean[] {true, false}), is("[
true, false ]"));
- assertThat(StringUtil.readableString(new long[] {1, 2, 3, 4}), is("[ 1, 2,
3, 4 ]"));
- assertThat(StringUtil.readableString(new float[] {51.0f, 52.0f, 53.0f, 54.0f}),
is("[ 51.0, 52.0, 53.0, 54.0 ]"));
- assertThat(StringUtil.readableString(new double[] {51.0d, 52.0d, 53.0d, 54.0d}),
is("[ 51.0, 52.0, 53.0, 54.0 ]"));
- }
+ // Read content longer than buffer size ...
+ for (int i = 0; i != 10; ++i) {
+ content += content; // note this doubles each time!
+ }
+ reader = new StringReader(content);
+ wrapper = new ReaderWrapper(reader);
+ assertThat(wrapper.isClosed(), is(false));
+ assertThat(StringUtil.read(wrapper), is(content));
+ assertThat(wrapper.isClosed(), is(true));
+ }
- @Test
- public void readableStringShouldHandleEmptyArraysOfArrays() {
- assertThat(StringUtil.readableString(new int[][] {}), is("[[]]"));
- assertThat(StringUtil.readableString(new boolean[][][][][][] {}),
is("[[[[[[]]]]]]"));
- assertThat(StringUtil.readableString(new
ArrayList<List<List<?>>>()), is("[]"));
- }
+ @Test
+ public void getStackTraceShouldReturnStackTrace() {
+ String msg = "This is the message for a test exception";
+ Throwable t = new IllegalArgumentException(msg);
+ String trace = StringUtil.getStackTrace(t);
+ assertThat(trace, containsString(msg));
+ assertThat(trace, containsString(this.getClass().getName()));
+ }
- @Test
- public void readableStringShouldHandleNestedObjects() {
- assertThat(StringUtil.readableString(new int[][] {new int[] {1, 2}, new int[] {3,
4}}), is("[ [ 1, 2 ], [ 3, 4 ] ]"));
- List<String> list1 = new ArrayList<String>();
- list1.add("a1");
- list1.add("a2");
- List<String> list2 = new ArrayList<String>();
- list2.add("b1");
- list2.add("b2");
- List<List<String>> list3 = new
ArrayList<List<String>>();
- list3.add(list1);
- list3.add(list2);
- assertThat(StringUtil.readableString(list3), is("[ [ \"a1\",
\"a2\" ], [ \"b1\", \"b2\" ] ]"));
- }
+ @Test
+ public void readableStringShouldReturnStringForNull() {
+ assertThat(StringUtil.readableString((Object)null), is("null"));
+ }
- protected class InputStreamWrapper extends InputStream {
+ @Test
+ public void readableStringShouldReturnStringFormOfBoolean() {
+ assertThat(StringUtil.readableString(true), is(Boolean.TRUE.toString()));
+ assertThat(StringUtil.readableString(false), is(Boolean.FALSE.toString()));
+ assertThat(StringUtil.readableString(Boolean.TRUE), is(Boolean.TRUE.toString()));
+ assertThat(StringUtil.readableString(Boolean.FALSE), is(Boolean.FALSE.toString()));
+ }
- private boolean closed = false;
- private final InputStream stream;
+ @Test
+ public void readableStringShouldReturnStringFormOfNumber() {
+ assertThat(StringUtil.readableString(1), is("1"));
+ assertThat(StringUtil.readableString(-513), is("-513"));
+ assertThat(StringUtil.readableString(-513.3f), is("-513.3"));
+ assertThat(StringUtil.readableString(-513.3d), is("-513.3"));
+ assertThat(StringUtil.readableString(new Short((short)1)), is("1"));
+ assertThat(StringUtil.readableString(new Integer(-513)), is("-513"));
+ assertThat(StringUtil.readableString(new Float(-513.3f)), is("-513.3"));
+ assertThat(StringUtil.readableString(new Double(-513.3d)), is("-513.3"));
+ }
- protected InputStreamWrapper( InputStream stream ) {
- this.stream = stream;
- }
+ @Test
+ public void readableStringShouldWrapObjectArrayWithSquareBraces() {
+ assertThat(StringUtil.readableString(new int[] {}), is("[]"));
+ assertThat(StringUtil.readableString(new int[] {1}), is("[ 1 ]"));
+ assertThat(StringUtil.readableString(new int[] {1, 2, 3, 4}), is("[ 1, 2, 3, 4
]"));
+ assertThat(StringUtil.readableString(new short[] {1, 2, 3, 4}), is("[ 1, 2, 3, 4
]"));
+ assertThat(StringUtil.readableString(new boolean[] {true, false}), is("[ true,
false ]"));
+ assertThat(StringUtil.readableString(new long[] {1, 2, 3, 4}), is("[ 1, 2, 3, 4
]"));
+ assertThat(StringUtil.readableString(new float[] {51.0f, 52.0f, 53.0f, 54.0f}),
is("[ 51.0, 52.0, 53.0, 54.0 ]"));
+ assertThat(StringUtil.readableString(new double[] {51.0d, 52.0d, 53.0d, 54.0d}),
is("[ 51.0, 52.0, 53.0, 54.0 ]"));
+ }
- public boolean isClosed() {
- return closed;
- }
+ @Test
+ public void readableStringShouldHandleEmptyArraysOfArrays() {
+ assertThat(StringUtil.readableString(new int[][] {}), is("[[]]"));
+ assertThat(StringUtil.readableString(new boolean[][][][][][] {}),
is("[[[[[[]]]]]]"));
+ assertThat(StringUtil.readableString(new ArrayList<List<List<?>>>()),
is("[]"));
+ }
- @Override
- public int read() throws IOException {
- return stream.read();
- }
+ @Test
+ public void readableStringShouldHandleNestedObjects() {
+ assertThat(StringUtil.readableString(new int[][] {new int[] {1, 2}, new int[] {3, 4}}),
is("[ [ 1, 2 ], [ 3, 4 ] ]"));
+ List<String> list1 = new ArrayList<String>();
+ list1.add("a1");
+ list1.add("a2");
+ List<String> list2 = new ArrayList<String>();
+ list2.add("b1");
+ list2.add("b2");
+ List<List<String>> list3 = new ArrayList<List<String>>();
+ list3.add(list1);
+ list3.add(list2);
+ assertThat(StringUtil.readableString(list3), is("[ [ \"a1\",
\"a2\" ], [ \"b1\", \"b2\" ] ]"));
+ }
- @Override
- public void close() throws IOException {
- stream.close();
- this.closed = true;
- }
+ protected class InputStreamWrapper extends InputStream {
- }
+ private boolean closed = false;
+ private final InputStream stream;
- protected class ReaderWrapper extends Reader {
+ protected InputStreamWrapper( InputStream stream ) {
+ this.stream = stream;
+ }
- private boolean closed = false;
- private final Reader reader;
+ public boolean isClosed() {
+ return closed;
+ }
- protected ReaderWrapper( Reader reader ) {
- this.reader = reader;
- }
+ @Override
+ public int read() throws IOException {
+ return stream.read();
+ }
- public boolean isClosed() {
- return closed;
- }
+ @Override
+ public void close() throws IOException {
+ stream.close();
+ this.closed = true;
+ }
- @Override
- public void close() throws IOException {
- reader.close();
- this.closed = true;
- }
+ }
- @Override
- public int read( char[] cbuf, int off, int len ) throws IOException {
- return reader.read(cbuf, off, len);
- }
- }
+ protected class ReaderWrapper extends Reader {
+ private boolean closed = false;
+ private final Reader reader;
+
+ protected ReaderWrapper( Reader reader ) {
+ this.reader = reader;
+ }
+
+ public boolean isClosed() {
+ return closed;
+ }
+
+ @Override
+ public void close() throws IOException {
+ reader.close();
+ this.closed = true;
+ }
+
+ @Override
+ public int read( char[] cbuf,
+ int off,
+ int len ) throws IOException {
+ return reader.read(cbuf, off, len);
+ }
+ }
+
}