PageRenderTime 29ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/src/play/utils/Utils.java

https://github.com/hsablonniere/play
Java | 236 lines | 200 code | 27 blank | 9 comment | 31 complexity | 6b2eb73d053d83a109bd4a53f219bf16 MD5 | raw file
  1. package play.utils;
  2. import play.Play;
  3. import play.mvc.Scope;
  4. import java.lang.annotation.Annotation;
  5. import java.nio.ByteBuffer;
  6. import java.nio.charset.CharacterCodingException;
  7. import java.nio.charset.CharsetDecoder;
  8. import java.text.ParseException;
  9. import java.text.SimpleDateFormat;
  10. import java.util.*;
  11. import java.util.regex.Matcher;
  12. import java.util.regex.Pattern;
  13. /**
  14. * Generic utils
  15. */
  16. public class Utils {
  17. public static <T> String join(Iterable<T> values, String separator) {
  18. if (values == null) {
  19. return "";
  20. }
  21. Iterator<T> iter = values.iterator();
  22. if (!iter.hasNext()) {
  23. return "";
  24. }
  25. StringBuffer toReturn = new StringBuffer(String.valueOf(iter.next()));
  26. while (iter.hasNext()) {
  27. toReturn.append(separator + String.valueOf(iter.next()));
  28. }
  29. return toReturn.toString();
  30. }
  31. public static String join(String[] values, String separator) {
  32. return (values == null) ? "" : join(Arrays.asList(values), separator);
  33. }
  34. public static String join(Annotation[] values, String separator) {
  35. return (values == null) ? "" : join(Arrays.asList(values), separator);
  36. }
  37. public static String getSimpleNames(Annotation[] values) {
  38. if (values == null) {
  39. return "";
  40. }
  41. List<Annotation> a = Arrays.asList(values);
  42. Iterator<Annotation> iter = a.iterator();
  43. if (!iter.hasNext()) {
  44. return "";
  45. }
  46. StringBuffer toReturn = new StringBuffer("@" + iter.next().annotationType().getSimpleName());
  47. while (iter.hasNext()) {
  48. toReturn.append(", @" + iter.next().annotationType().getSimpleName());
  49. }
  50. return toReturn.toString();
  51. }
  52. /**
  53. * @deprecated Use Utils.join(values, " ");
  54. */
  55. @Deprecated
  56. public static String toString(Annotation[] values) {
  57. return join(values, " ");
  58. }
  59. public static String open(String file, Integer line) {
  60. if (Play.configuration.containsKey("play.editor")) {
  61. return String.format(Play.configuration.getProperty("play.editor"), Play.getFile(file).getAbsolutePath(), line);
  62. }
  63. return null;
  64. }
  65. /**
  66. * for java.util.Map
  67. */
  68. public static class Maps {
  69. public static void mergeValueInMap(Map<String, String[]> map, String name, String value) {
  70. String[] newValues = null;
  71. String[] oldValues = map.get(name);
  72. if (oldValues == null) {
  73. newValues = new String[1];
  74. newValues[0] = value;
  75. } else {
  76. newValues = new String[oldValues.length + 1];
  77. System.arraycopy(oldValues, 0, newValues, 0, oldValues.length);
  78. newValues[oldValues.length] = value;
  79. }
  80. map.put(name, newValues);
  81. }
  82. public static void mergeValueInMap(Map<String, String[]> map, String name, String[] values) {
  83. for (String value : values) {
  84. mergeValueInMap(map, name, value);
  85. }
  86. }
  87. public static <K, V> Map<K, V> filterMap(Map<K, V> map, String keypattern) {
  88. try {
  89. @SuppressWarnings("unchecked")
  90. Map<K, V> filtered = map.getClass().newInstance();
  91. for (Map.Entry<K, V> entry : map.entrySet()) {
  92. K key = entry.getKey();
  93. if (key.toString().matches(keypattern)) {
  94. filtered.put(key, entry.getValue());
  95. }
  96. }
  97. return filtered;
  98. } catch (Exception iex) {
  99. return null;
  100. }
  101. }
  102. }
  103. private static ThreadLocal<SimpleDateFormat> httpFormatter = new ThreadLocal<SimpleDateFormat>();
  104. public static SimpleDateFormat getHttpDateFormatter() {
  105. if (httpFormatter.get() == null) {
  106. httpFormatter.set(new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US));
  107. httpFormatter.get().setTimeZone(TimeZone.getTimeZone("GMT"));
  108. }
  109. return httpFormatter.get();
  110. }
  111. public static Map<String, String[]> filterMap(Map<String, String[]> map, String prefix) {
  112. Map<String, String[]> newMap = new HashMap<String, String[]>();
  113. for (String key : map.keySet()) {
  114. if (!key.startsWith(prefix + ".")) {
  115. newMap.put(key, map.get(key));
  116. }
  117. }
  118. return newMap;
  119. }
  120. public static Map<String, String> filterParams(Scope.Params params, String prefix) {
  121. return filterParams(params.all(), prefix);
  122. }
  123. public static Map<String, String> filterParams(Map<String, String[]> params, String prefix, String separator) {
  124. Map<String, String> filteredMap = new LinkedHashMap<String, String>();
  125. prefix += ".";
  126. for(Map.Entry<String, String[]> e: params.entrySet()){
  127. if(e.getKey().startsWith(prefix)) {
  128. filteredMap.put(
  129. e.getKey().substring(prefix.length()),
  130. Utils.join(e.getValue(), separator)
  131. );
  132. }
  133. }
  134. return filteredMap;
  135. }
  136. public static Map<String, String> filterParams(Map<String, String[]> params, String prefix) {
  137. return filterParams(params, prefix, ", ");
  138. }
  139. public static void kill(String pid) throws Exception {
  140. String os = System.getProperty("os.name");
  141. String command = (os.startsWith("Windows"))
  142. ? "taskkill /F /PID " + pid
  143. : "kill " + pid;
  144. Runtime.getRuntime().exec(command).waitFor();
  145. }
  146. public static class AlternativeDateFormat {
  147. Locale locale;
  148. List<SimpleDateFormat> formats = new ArrayList<SimpleDateFormat>();
  149. public AlternativeDateFormat(Locale locale, String... alternativeFormats) {
  150. super();
  151. this.locale = locale;
  152. setFormats(alternativeFormats);
  153. }
  154. public void setFormats(String... alternativeFormats) {
  155. for (String format : alternativeFormats) {
  156. formats.add(new SimpleDateFormat(format, locale));
  157. }
  158. }
  159. public Date parse(String source) throws ParseException {
  160. for (SimpleDateFormat dateFormat : formats) {
  161. if (source.length() == dateFormat.toPattern().replace("\'", "").length()) {
  162. try {
  163. return dateFormat.parse(source);
  164. } catch (ParseException ex) {
  165. }
  166. }
  167. }
  168. throw new ParseException("Date format not understood", 0);
  169. }
  170. static ThreadLocal<AlternativeDateFormat> dateformat = new ThreadLocal<AlternativeDateFormat>();
  171. public static AlternativeDateFormat getDefaultFormatter() {
  172. if (dateformat.get() == null) {
  173. dateformat.set(new AlternativeDateFormat(Locale.US,
  174. "yyyy-MM-dd'T'HH:mm:ss'Z'", // ISO8601 + timezone
  175. "yyyy-MM-dd'T'HH:mm:ss", // ISO8601
  176. "yyyy-MM-dd HH:mm:ss",
  177. "yyyyMMdd HHmmss",
  178. "yyyy-MM-dd",
  179. "yyyyMMdd'T'HHmmss",
  180. "yyyyMMddHHmmss",
  181. "dd'/'MM'/'yyyy",
  182. "dd-MM-yyyy",
  183. "dd'/'MM'/'yyyy HH:mm:ss",
  184. "dd-MM-yyyy HH:mm:ss",
  185. "ddMMyyyy HHmmss",
  186. "ddMMyyyy"));
  187. }
  188. return dateformat.get();
  189. }
  190. }
  191. private static final Pattern encodedChars = Pattern.compile("%([a-fA-F0-9][a-fA-F0-9])");
  192. public static String decodeBytes(String enc, CharsetDecoder decoder) {
  193. Matcher matcher = encodedChars.matcher(enc);
  194. StringBuffer buf = new StringBuffer();
  195. ByteBuffer bytes = ByteBuffer.allocate(enc.length() / 3);
  196. while (matcher.find()) {
  197. int b = Integer.parseInt(matcher.group(1), 16);
  198. bytes.put((byte) b);
  199. }
  200. bytes.flip();
  201. try {
  202. if (bytes.hasRemaining())
  203. return decoder.decode(bytes).toString();
  204. return enc;
  205. } catch (CharacterCodingException e) {
  206. throw new RuntimeException(e);
  207. }
  208. }
  209. }