All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.springframework.util.SortProperties Maven / Gradle / Ivy

package org.springframework.util;

import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.springframework.util.Assert;
import org.springframework.util.comparator.NullSafeComparator;

public class SortProperties extends Properties {
  private static final long serialVersionUID = -8842314902328663478L;

  protected final CharSequence suffix;
  protected final CharSequence prefix;

  public SortProperties(Map map) {
    this(map, "", "");
  }

  public SortProperties(Map map, CharSequence suffix, CharSequence prefix) {
    Assert.notEmpty(map, "'map' must have entries");
    Assert.notNull(this.suffix = suffix, "'suffix' must not be null");
    Assert.notNull(this.prefix = prefix, "'prefix' must not be null");
    putAll(map);
  }

  /**
   * @see java.util.TreeSet#TreeSet(java.util.Collection)
   */
  @Override
  public synchronized Enumeration keys() {
    return keys(false);
  }

  @SuppressWarnings("unchecked")
  public synchronized Enumeration keys(boolean nullsLow) {
    List list = Collections.list(super.keys());
    Collections.sort(list, nullsLow ? NullSafeComparator.NULLS_LOW : NullSafeComparator.NULLS_HIGH);
    return Collections.enumeration(list);
  }

  /**
   * @see java.lang.StringBuilder#charAt(int)
   * @see java.lang.StringBuilder#deleteCharAt(int)
   * @see java.lang.StringBuilder#setLength(int)
   */
  @Override
  public synchronized String toString() {
    StringBuilder stringBuilder = new StringBuilder();
    for (Enumeration enumeration = keys(); enumeration.hasMoreElements();) {
      Object nextElement = enumeration.nextElement();
      stringBuilder.append(this.prefix);
      stringBuilder.append(nextElement);
      stringBuilder.append('=');
      stringBuilder.append(get(nextElement));
      stringBuilder.append(this.suffix);
    }
    return new String(stringBuilder).substring(0, Math.max(stringBuilder.length() - this.suffix.length(), 0));
  }
}