[flaptor-util commit] r193 - Added several utility methods and classes

0 views
Skip to first unread message

codesite...@google.com

unread,
May 14, 2009, 1:50:41 PM5/14/09
to flaptor-o...@googlegroups.com
Author: san...@santip.com.ar
Date: Thu May 14 10:32:36 2009
New Revision: 193

Added:
trunk/src/com/flaptor/util/FunctionUtils.java
trunk/src/com/flaptor/util/collect/CacheMap.java
Modified:
trunk/src/com/flaptor/util/CollectionsUtil.java
trunk/src/com/flaptor/util/DateUtil.java
trunk/src/com/flaptor/util/Pairs.java

Log:
Added several utility methods and classes

Modified: trunk/src/com/flaptor/util/CollectionsUtil.java
==============================================================================
--- trunk/src/com/flaptor/util/CollectionsUtil.java (original)
+++ trunk/src/com/flaptor/util/CollectionsUtil.java Thu May 14 10:32:36 2009
@@ -19,11 +19,19 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
+import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;

+import com.google.common.base.Function;
+import com.google.common.base.Objects;
+import com.google.common.base.Predicate;
+import com.google.common.collect.AbstractIterator;
+import com.google.common.collect.Comparators;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;

/**
@@ -164,6 +172,89 @@
}
}

+ public static <T extends Comparable<T>> Iterable<T>
mergeIterables(final Iterable<? extends Iterable<? extends T>> iterables) {
+ return mergeIterables(iterables, Comparators.naturalOrder());
+ }
+
+ public static <T> Iterable<T> mergeIterables(final Iterable<? extends
Iterable<? extends T>> iterables, final Comparator<? super T> comparator) {
+ return new Iterable<T>() {
+ public Iterator<T> iterator() {
+ return mergeIterators(Iterables.transform(iterables, new
Function<Iterable<? extends T>, Iterator<? extends T>>() {
+ public Iterator<? extends T> apply(Iterable<? extends
T> from) {
+ return from.iterator();
+ }
+ }).iterator(), comparator);
+ }
+ };
+ }
+
+ public static <T extends Comparable<T>> Iterator<T>
mergeIterators(Iterator<? extends Iterator<? extends T>> iterators) {
+ return mergeIterators(iterators, Comparators.naturalOrder());
+ }
+
+ public static <T> Iterator<T> mergeIterators(Iterator<? extends
Iterator<? extends T>> iterators, final Comparator<? super T> comparator) {
+ final List<PeekingIterator<? extends T>> peekingIterators =
Lists.newArrayList(Iterators.transform(iterators, new Function<Iterator<?
extends T>, PeekingIterator<? extends T>>() {
+ public PeekingIterator<? extends T> apply(Iterator<? extends
T> from) {
+ return new PeekingIterator<T>(from);
+ }
+ }));
+
+ return new AbstractIterator<T>() {
+ protected T computeNext() {
+ int bestIndex = -1;
+ T bestElement = null;
+ for (int i = 0; i < peekingIterators.size(); i++) {
+ PeekingIterator<? extends T> it =
peekingIterators.get(i);
+ if (it.hasNext()) {
+ T element = it.peek();
+ if (bestElement == null ||
comparator.compare(element, bestElement) < 0) {
+ bestElement = element;
+ bestIndex = i;
+ }
+ }
+ }
+ if (bestIndex == -1) {
+ return endOfData();
+ } else {
+ return peekingIterators.get(bestIndex).next();
+ }
+ }
+ };
+ }
+
+ public static class PeekingIterator<T> implements Iterator<T> {
+ private Iterator<? extends T> delegate;
+ private boolean peeked = false;
+ private T next;
+
+ public PeekingIterator(Iterator<? extends T> delegate) {
+ this.delegate = delegate;
+ }
+
+ public T peek() {
+ try {
+ return peeked ? next : (next = delegate.next());
+ } finally {
+ peeked = true;
+ }
+ }
+
+ public boolean hasNext() {
+ return peeked || delegate.hasNext();
+ }
+ public T next() {
+ try {
+ return peeked ? next : delegate.next();
+ } finally {
+ peeked = false;
+ }
+ }
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+
+ }
+
/**
* Creates a list of sorted entries by copying them from the entrySet
of a map.
*
@@ -219,4 +310,107 @@
if (count == null) count = 0;
map.put(key, count + 1);
}
+
+ public static <T> Iterable<T> allButOne(Iterable<T> all, final T one) {
+ return Iterables.filter(all, new Predicate<T>() {
+ public boolean apply(T t) {
+ return !Objects.equal(one, t);
+ }
+ });
+
+ }
+
+ public static Function<String, Integer> PARSE_INT_FUNCTION = new
Function<String, Integer>() {
+ public Integer apply(String from) {
+ return Integer.valueOf(from);
+ }
+ };
+
+ public static Function<String, Long> PARSE_LONG_FUNCTION = new
Function<String, Long>() {
+ public Long apply(String from) {
+ return Long.valueOf(from);
+ }
+ };
+
+ public static Function<String, Float> PARSE_FLOAT_FUNCTION = new
Function<String, Float>() {
+ public Float apply(String from) {
+ return Float.valueOf(from);
+ }
+ };
+
+ public static List<Long> toLongList(Iterable<String> strings) {
+ return Lists.newArrayList(Iterables.transform(strings,
PARSE_LONG_FUNCTION));
+ }
+
+ public static List<Integer> toIntList(Iterable<String> strings) {
+ return Lists.newArrayList(Iterables.transform(strings,
PARSE_INT_FUNCTION));
+ }
+
+ public static List<Float> toFloatList(Iterable<String> strings) {
+ return Lists.newArrayList(Iterables.transform(strings,
PARSE_FLOAT_FUNCTION));
+ }
+
+ public static List<Integer> toIntList(String... strings) {
+ return toIntList(Arrays.asList(strings));
+ }
+
+ public static List<Long> toLongList(String... strings) {
+ return toLongList(Arrays.asList(strings));
+ }
+
+ public static List<Float> toFloatList(String... strings) {
+ return toFloatList(Arrays.asList(strings));
+ }
+
+ public static int[] toIntArray(Iterable<String> strings) {
+ List<Integer> list = toIntList(strings);
+ int[] array = new int[list.size()];
+ for (int i = 0; i < array.length; i++) {
+ array[i] = list.get(i);
+ }
+ return array;
+ }
+
+ public static long[] toLongArray(Iterable<String> strings) {
+ List<Long> list = toLongList(strings);
+ long[] array = new long[list.size()];
+ for (int i = 0; i < array.length; i++) {
+ array[i] = list.get(i);
+ }
+ return array;
+ }
+
+ public static float[] toFloatArray(Iterable<String> strings) {
+ List<Float> list = toFloatList(strings);
+ float[] array = new float[list.size()];
+ for (int i = 0; i < array.length; i++) {
+ array[i] = list.get(i);
+ }
+ return array;
+ }
+
+ public static long[] toLongArray(String... strings) {
+ long[] longs = new long[strings.length];
+ for (int i = 0; i < longs.length; i++) {
+ longs[i] = Long.parseLong(strings[i]);
+ }
+ return longs;
+ }
+ public static int[] toIntArray(String... strings) {
+ int[] ints = new int[strings.length];
+ for (int i = 0; i < ints.length; i++) {
+ ints[i] = Integer.parseInt(strings[i]);
+ }
+ return ints;
+ }
+ public static float[] toFloatArray(String... strings) {
+ float[] floats = new float[strings.length];
+ for (int i = 0; i < floats.length; i++) {
+ floats[i] = Float.parseFloat(strings[i]);
+ }
+ return floats;
+ }
+
+
+
}

Modified: trunk/src/com/flaptor/util/DateUtil.java
==============================================================================
--- trunk/src/com/flaptor/util/DateUtil.java (original)
+++ trunk/src/com/flaptor/util/DateUtil.java Thu May 14 10:32:36 2009
@@ -25,6 +25,12 @@
c.setTime(date);
return c;
}
+
+ public static Calendar toGMTCalendar(Date date) {
+ Calendar c = getGMTCalendar();
+ c.setTime(date);
+ return c;
+ }

public static Date toDate(Calendar calendar) {
return calendar.getTime();
@@ -68,6 +74,7 @@
public static Calendar getCanonicalDay(Calendar cal) {
Calendar ret = new GregorianCalendar(cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0 ,0 ,0);
ret.set(Calendar.MILLISECOND, 0);
+ ret.setTimeZone(cal.getTimeZone());
return ret;
}

@@ -143,25 +150,65 @@
return cal;
}

- public static Date getDeltaFromDate(Date source, int field, int delta)
{
+ public static Date addSeconds(Date source, int seconds) {
+ return addField(source, Calendar.SECOND, seconds);
+ }
+
+ public static Date addMinutes(Date source, int minutes) {
+ return addField(source, Calendar.MINUTE, minutes);
+ }
+
+ public static Date addHours(Date source, int hours) {
+ return addField(source, Calendar.HOUR_OF_DAY, hours);
+ }
+
+ public static Date addDays(Date source, int days) {
+ return addField(source, Calendar.DAY_OF_YEAR, days);
+ }
+
+ public static Date addMonths(Date source, int months) {
+ return addField(source, Calendar.MONTH, months);
+ }
+
+ public static Date addYears(Date source, int years) {
+ return addField(source, Calendar.YEAR, years);
+ }
+
+ public static Date addField(Date source, int field, int delta) {
Calendar c = Calendar.getInstance();
c.setTime(source);
c.add(field, delta);
return c.getTime();
}

- public static Date getMinDate(Iterable<Date> dates) {
+ public static Date min(Iterable<Date> dates) {
+ Date min = null;
+ for (Date date : dates) {
+ if (date != null && (min == null || min.after(date)))
+ min = date;
+ }
+ return min;
+ }
+ public static Date max(Iterable<Date> dates) {
+ Date max = null;
+ for (Date date : dates) {
+ if (date != null && (max == null || max.before(date)))
+ max = date;
+ }
+ return max;
+ }
+ public static Date min(Date... dates) {
Date min = null;
for (Date date : dates) {
- if (min == null || min.after(date))
+ if (date != null && (min == null || min.after(date)))
min = date;
}
return min;
}
- public static Date getMaxDate(Iterable<Date> dates) {
+ public static Date max(Date... dates) {
Date max = null;
for (Date date : dates) {
- if (max == null || max.before(date))
+ if (date != null && (max == null || max.before(date)))
max = date;
}
return max;
@@ -187,9 +234,23 @@

public static SimpleDateFormat getGMTDateFormat(String strFormat) {
SimpleDateFormat format = new SimpleDateFormat(strFormat);
- Calendar gmt = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
- format.setCalendar(gmt);
+ format.setCalendar(getGMTCalendar());
return format;
}

+ public static Calendar getGMTCalendar() {
+ return Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
+ }
+
+ public static Calendar truncateHour(Calendar c) {
+ c.set(Calendar.MINUTE, 0);
+ c.set(Calendar.SECOND, 0);
+ c.set(Calendar.MILLISECOND, 0);
+ return c;
+ }
+
+ public static Date truncateHour(Date d) {
+ return toDate(truncateHour(toCalendar(d)));
+ }
+
}

Added: trunk/src/com/flaptor/util/FunctionUtils.java
==============================================================================
--- (empty file)
+++ trunk/src/com/flaptor/util/FunctionUtils.java Thu May 14 10:32:36 2009
@@ -0,0 +1,76 @@
+package com.flaptor.util;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+import com.google.common.base.Function;
+
+public class FunctionUtils {
+
+ public static Function<Object, String> getToString() {
+ return new Function<Object, String>() {
+ public String apply(Object from) {
+ return String.valueOf(from);
+ }
+ };
+ }
+
+ public static <T> Function<String, T> getValueOf(final Class<T> type) {
+ return getStaticMethod(type, String.class, type, "valueOf");
+ }
+
+ public static <F, T> Function<F, T> getStaticMethod(Class<?> type,
Class<F> fromType, final Class<T> toType, String methodName) {
+ try {
+ final Method method = type.getMethod(methodName, fromType);
+ return new Function<F, T>() {
+ public T apply(F from) {
+ try {
+ return toType.cast(method.invoke(null, from));
+ } catch (IllegalArgumentException e) {
+ throw new RuntimeException(e);
+ } catch (IllegalAccessException e) {
+ throw new RuntimeException(e);
+ } catch (InvocationTargetException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
+ } catch (SecurityException e) {
+ throw new RuntimeException(e);
+ } catch (NoSuchMethodException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static Object invokeMethod(Object target, String method) {
+ return getMethodInvoker(method).apply(target);
+ }
+
+ public static Function<Object, Object> getMethodInvoker(final String
methodName) {
+ return getMethodInvoker(Object.class, methodName);
+ }
+
+ public static <T> Function<Object, T> getMethodInvoker(final Class<T>
returnType, final String methodName) {
+ return new Function<Object, T>() {
+ public T apply(Object from) {
+ if (from == null) return null;
+ try {
+ Method method = from.getClass().getMethod(methodName,
new Class[0]);
+ return returnType.cast(method.invoke(from, new
Object[0]));
+ } catch (SecurityException e) {
+ throw new RuntimeException(e);
+ } catch (NoSuchMethodException e) {
+ throw new RuntimeException(e);
+ } catch (IllegalArgumentException e) {
+ throw new RuntimeException(e);
+ } catch (IllegalAccessException e) {
+ throw new RuntimeException(e);
+ } catch (InvocationTargetException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
+ }
+
+
+}

Modified: trunk/src/com/flaptor/util/Pairs.java
==============================================================================
--- trunk/src/com/flaptor/util/Pairs.java (original)
+++ trunk/src/com/flaptor/util/Pairs.java Thu May 14 10:32:36 2009
@@ -5,12 +5,29 @@
import java.util.List;
import java.util.Set;

+import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;


public class Pairs {

+ public static <T> Function<Pair<T, ?>, T> getFirstFunction() {
+ return new Function<Pair<T, ?>, T>() {
+ public T apply(Pair<T, ?> from) {
+ return from.first();
+ }
+ };
+ }
+
+ public static <T> Function<Pair<?, T>, T> getLastFunction() {
+ return new Function<Pair<?, T>, T>() {
+ public T apply(Pair<?, T> from) {
+ return from.last();
+ }
+ };
+ }
+
/**
* The empty pair (immutable).
* @see #emptyPair()

Added: trunk/src/com/flaptor/util/collect/CacheMap.java
==============================================================================
--- (empty file)
+++ trunk/src/com/flaptor/util/collect/CacheMap.java Thu May 14 10:32:36
2009
@@ -0,0 +1,16 @@
+package com.flaptor.util.collect;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class CacheMap<K,V> extends LinkedHashMap<K,V> {
+ private int maxSize;
+
+ public CacheMap(int maxSize) {
+ this.maxSize = maxSize;
+ }
+
+ protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
+ return size() > maxSize;
+ }
+}

Reply all
Reply to author
Forward
0 new messages