示例#1
0
  /**
   * 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 0. Therefore, the first parameter replaces all occurrences of "{0}", the
   * second parameter replaces all occurrences of "{1}", 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>If there are no parameters, this method does nothing and returns the supplied pattern as is.
   *
   * @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) {
    CheckArg.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];

        // Automatically pretty-print arrays
        if (parameter != null && parameter.getClass().isArray()) {
          parameter = Arrays.asList((Object[]) parameter);
        }

        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);

    return text.toString();
  }
示例#2
0
 /**
  * Removes leading and trailing whitespace from the supplied text, and reduces other consecutive
  * whitespace characters to a single space. Whitespace includes line-feeds.
  *
  * @param text the text to be normalized
  * @return the normalized text
  */
 public static String normalize(String text) {
   CheckArg.isNotNull(text, "text");
   // This could be much more efficient.
   return NORMALIZE_PATTERN.matcher(text).replaceAll(" ").trim();
 }